diff --git a/Cargo.lock b/Cargo.lock index e706a54a74..1b5c9f13c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1543,6 +1543,8 @@ dependencies = [ "dim-client", "futures-util", "jiff", + "regex", + "regex-syntax", "reqwest 0.12.28", "rutis", "serde", diff --git a/benchmarks/usercases/pack.py b/benchmarks/usercases/pack.py new file mode 100644 index 0000000000..834e8853e3 --- /dev/null +++ b/benchmarks/usercases/pack.py @@ -0,0 +1,1071 @@ +#!/usr/bin/env python3 +"""Pack a Timeline export for an evidence pack. + +Content is omitted unless a rule or the submitter keeps it, identifiers in +what is kept are replaced, and no pack is written when a check fails. The +contract is docs/eval/evidence-pack.md. The tool reads the JSONL written by +`dimcode export`, runs on the submitter's machine and connects to nothing. + + pack.py EXPORT --out DIR --dimcode /absolute/path/to/dimcode [--decisions FILE] [--confirm DIGEST] + +DIR/pack/ is the pack. Until confirmed, it is for local review only. +DIR/review.md and the decisions file always stay local. +""" + +from __future__ import annotations + +import argparse +import functools +import hashlib +import json +import math +import os +import re +import secrets +import sys +import tempfile +import subprocess +from contextlib import ExitStack, contextmanager +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from xml.sax.saxutils import unescape + +RULES_VERSION = 9 +PACK_ID = re.compile(r"[0-9a-f]{16}") +PROVIDER_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}") +LEVEL_ONE = {"user-input", "assistant-text"} +# A string seen in several places takes the first of these kinds that any of +# its occurrences has, so the kind does not depend on the order of the lines. +# The export puts every child branch before `main` (branch ids sort before +# "main"), and a child's requests carry the context it inherited: taking the +# first occurrence's kind would make the whole dialogue `other`. Once a string +# is kept anywhere it is in the pack, so a level-one kind always wins. +PRECEDENCE = ("user-input", "assistant-text", "thinking", "tool-args", "tool-result", "injected", "error", + "system", "tool-def", "attachment", "other") +RANK = {kind: rank for rank, kind in enumerate(PRECEDENCE)} +OPAQUE = {"signature", "thought_signature", "thoughtSignature", "encryptedContent", "encrypted_content"} +REMOVED = "[removed]" +SESSION = "00000000-0000-4000-8000-000000000000" +STUB = re.compile(r"\[omitted u\d+ [a-z-]+ \d+B\]") +PSEUDONYM = re.compile(r"(item|call|tool)-\d+") +RUNS = {"thinking": "thinking", "text": "assistant-text"} +KEPT_TOOL_SOURCES = {"builtin", "extension"} +ASSIGNMENT = re.compile(r"(?i)\b\w*(?:api_?key|secret|token|password|passwd|credential)\w*\s*[=:]\s*\S{6,}") +HOME = re.compile(r"([^<\n]+)") +PASTED = re.compile(r"\[Pasted text: ([^\s\]]+)") +URL_HOST = re.compile(r"https?://([A-Za-z0-9.-]+\.[A-Za-z]{2,})") +HOSTED_OWNER = re.compile(r"(?:github|gitlab)\.com[/:]([A-Za-z0-9_.-]+)/|bitbucket\.org/([A-Za-z0-9_.-]+)/") +PUBLIC_HOSTS = {"github.com", "api.github.com", "raw.githubusercontent.com", "gitlab.com", "bitbucket.org", + "example.com", "example.org", "json-schema.org"} + + +class Refused(Exception): + """The pack is not written; the message says which check failed.""" + + +# Field allowlists for the documented Timeline export and reviewed event payloads. + +KEEP = ("keep",) +INTEGER = ("integer",) +NUMBER = ("number",) +BOOL = ("bool",) +PASS = ("pass",) +CALL = ("id", "call") +ITEM = ("id", "item") +TOOL = ("tool",) +SESSION_ID = ("session",) +USER_CONTENT = ("user-content",) + +# crates/dim-agent-types/src/markup.rs: MARKERS and char::is_whitespace. +RUNTIME_MARKUP = re.compile( + r"\t-\r \x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" +) + + +def text(kind): + return ("text", kind) + + +def obj(kind): + return ("object", kind) + + +@functools.cache +def content(kind): + """A message or result body: one string, or a list of blocks.""" + return lambda value: [block(kind)] if isinstance(value, list) else text(kind) + + +@functools.cache +def block(kind): + return { + "type": KEEP, "text": text(kind), "thinking": text("thinking"), + "id": CALL, "tool_use_id": CALL, "name": TOOL, "input": obj("tool-args"), + "content": content("tool-result"), "mimeType": KEEP, "data": text("attachment"), + "source": {"type": KEEP, "mediaType": KEEP, "fileId": text("attachment"), + "data": text("attachment"), "url": text("attachment")}, + "providerMetadata": metadata_spec, + **dict.fromkeys(OPAQUE, KEEP), + } + + +def opaque_field(container, key): + return key in OPAQUE or ( + key == "data" and container.get("protocol") in ("bedrock-redacted", "anthropic-redacted")) + + +def metadata_spec(value): + spec = {"protocol": KEEP, "itemId": ITEM, "summaryIndex": INTEGER, "phase": KEEP, + **dict.fromkeys(OPAQUE, KEEP)} + if isinstance(value, dict) and opaque_field(value, "data"): + spec["data"] = KEEP + return spec + + +def system(value): + return [{"type": KEEP, "text": text("system")}] if isinstance(value, list) else text("system") + + +IDS = {"turn_id": KEEP, "request_id": KEEP} +REF = {"timeline": KEEP, "revision": KEEP} +TOOL_DEFINITION = {"name": TOOL, "source": KEEP, "risk": text("tool-def"), + "description": text("tool-def"), "inputSchema": obj("tool-def")} +CAPABILITIES = { + "modalities": [KEEP], "toolCalling": BOOL, "streaming": BOOL, "structuredOutput": BOOL, + "vision": BOOL, "audio": BOOL, "reasoning": BOOL, "contextWindow": INTEGER, "maxOutputTokens": INTEGER, +} +MODEL = {"providerId": KEEP, "modelId": KEEP, + "capabilitySnapshot": {"target": {"providerId": KEEP, "modelId": KEEP}, + "capabilities": CAPABILITIES, "reasoning": {"mode": KEEP}, + "serviceTier": {"supported": BOOL, "default": KEEP, "options": [KEEP]}}, + "metadata": {"providerProtocol": KEEP}, "tools": [TOOL_DEFINITION], + "config": {**dict.fromkeys(("temperature", "maxTokens", "topP", "topK"), NUMBER), + "stopSequences": [text("other")], "reasoning": obj("other"), "providerOptions": obj("other")}} +USAGE = {**dict.fromkeys(("promptTokens", "completionTokens", "totalTokens", "cacheReadTokens", + "cacheWriteTokens", "reasoningTokens", "cost"), NUMBER), "currency": KEEP} +# Messages inside a request are `other`: a request-only message has no known +# origin. The same string in an event field outranks it (PRECEDENCE). +REQUEST = {**MODEL, "messages": [{"role": KEEP, "content": content("other")}], "system": system} +CALLED = {"id": CALL, "name": TOOL, "input": obj("tool-args")} +RESULT = {"content": content("tool-result"), "structuredContent": obj("tool-result"), "isError": BOOL, + "effects": [{"kind": KEEP, "command": text("tool-result"), "path": text("tool-result"), + "exitCode": INTEGER, "signal": text("tool-result")}]} +SENT = {**IDS, "request": REQUEST, "configuration": REF, "prompt": REF} +# `status` and `finish_reason` are enum tags; `reason` and `error` are free text. +OUTCOME = {"status": KEEP, "finish_reason": KEEP, "reason": text("error"), "error": text("error")} +# `BranchSource` carries a provider call id beside the internal ones. +SOURCE = {"kind": KEEP, "turn_id": KEEP, "request_id": KEEP, "call_id": CALL, "operation_id": KEEP} +TARGET = {"kind": KEEP, "agent_id": KEEP, "session_id": SESSION_ID, "profile": obj("tool-def")} +PEER = {"turn_id": KEEP, "request_id": KEEP, "call_id": CALL, "agent_id": KEEP, "session_id": SESSION_ID} +COMPACT = {**IDS, "command": INTEGER, "through": INTEGER, "trigger": KEEP, "strategy": KEEP} +COMPACTION = {**IDS, "command": INTEGER, "start": INTEGER, "through": INTEGER, "status": KEEP, + "retain_from": KEEP, "strategy": KEEP, "reason": text("error"), "error": text("error"), + "replacement": [{"role": KEEP, "content": content("injected")}], "diagnostics": obj("other"), + "replacement_parts": {"strategy": INTEGER, "digest": INTEGER}, "pinned_inputs": [KEEP], + "digest_entries": obj("other"), + "context_baseline": [{"key": text("injected"), "sourceEvent": KEEP, + "message": {"role": KEEP, "content": content("injected")}}]} + +EVENTS = { + "approval/cancelled": {"approval_id": KEEP, "reason": text("error")}, + "approval/request": {"approval_id": KEEP, "source": SOURCE, "reason": text("tool-args"), + "call": {"name": TOOL, "input": obj("tool-args")}}, + "approval/respond": {"approval_id": KEEP, "decision": KEEP}, + "branch/create": {"at": {"kind": KEEP, "sequence": INTEGER}, "source": SOURCE, + "branch": KEEP, "prompt": text("tool-args")}, + "branch/create-failed": {"status": KEEP, "branch": KEEP, "createEvent": INTEGER, + "error": text("error"), "reason": text("error")}, + "branch/end": {"source": SOURCE, "ancestor": KEEP}, + "branch/ended": {"branch": KEEP, "endEvent": INTEGER, "source": SOURCE, "ancestor": KEEP}, + "branch/default": {"branch": KEEP, "from": KEEP, "source": SOURCE}, + "branch/resume": {}, + "branch/start": {"parent": KEEP, "createEvent": INTEGER}, + "collaboration/cancel": PEER, + "collaboration/close": PEER, + "collaboration/delivered": {"op_event_id": KEEP, "status": KEEP, "agent_id": KEEP, "session_id": SESSION_ID, + "input_event_id": KEEP, "outcome": KEEP, "error": KEEP}, + "collaboration/message": {**PEER, "mode": KEEP, "content": text("tool-args")}, + "collaboration/request": {**PEER, "target": TARGET, "prompt": text("tool-args"), "title": text("tool-args")}, + "collaboration/result": {"request_event_id": KEEP, "agent_id": KEEP, "session_id": SESSION_ID, + "last_turn_id": KEEP, "text": text("tool-result"), + "status": KEEP, "reason": text("error")}, + "context/budget": {**IDS, "boundary": KEEP, "baselineSource": KEEP, "estimatedInputTokens": NUMBER, + "baselinePromptTokens": NUMBER, "deltaTokens": NUMBER, "contextWindow": NUMBER, + "outputTokens": NUMBER}, + "context/compact": {}, + "context/compaction": COMPACTION, + "context/compaction-start": COMPACT, + "context/configured": {**REF, "prompt": REF, "settings": MODEL, "system": system, "system_source": system}, + "context/prepare": {**SENT, "through": INTEGER}, + "context/scope": {"scope": {"kind": KEEP, "timeline": KEEP, "id": KEEP}, "status": KEEP}, + "exec/ended": {"task_id": KEEP, "status": KEEP, "result": RESULT}, + "exec/started": {**IDS, "call_id": CALL, "task_id": KEEP, "description": text("tool-args"), + "title": text("tool-args"), "output_path": text("tool-result")}, + "input/applied": {"input_id": KEEP, "mode": KEEP}, + "input/consumed": {"input_id": KEEP}, + "input/deleted": {"input_id": KEEP}, + "input/message": {"submission_id": KEEP, "mode": KEEP, "user": {"content": USER_CONTENT}, + "blocks": [{"type": KEEP, "text": text("injected"), "key": text("injected")}]}, + "input/withdraw": {"input_id": KEEP}, + "model/call": SENT, + "model/usage": {**IDS, "usage": USAGE}, + "permission/changed": {"policy": obj("injected")}, + "prompt/changed": REF, + "prompt/configure-request": {"operation_id": KEEP}, + "prompt/configure-result": {"operation_id": KEEP}, + "session/forked": {}, + "step/model-content": {**IDS, "content": [block("assistant-text")]}, + "step/model-output-end": {**IDS, **OUTCOME}, + "step/model-start": IDS, + "step/text": {**IDS, "delta": text("assistant-text")}, + "step/thinking": {**IDS, "delta": text("thinking")}, + "step/tool-call": {**IDS, "calls": [CALLED]}, + "step/tool-completed": {**IDS, "call_id": CALL, "result": RESULT, "call_event_id": KEEP}, + "step/tool-result": {**IDS, "call_event_id": KEEP, "results": [{"call_id": CALL, "result": RESULT}]}, + "step/tool-start": {**IDS, "call_id": CALL, "call_event_id": KEEP}, + "step/tool-use": {**IDS, "call": CALLED}, + "step/tool-use-start": {**IDS, "call_id": CALL, "name": TOOL}, + "stop/interrupt": {"reason": text("error"), "scope": KEEP}, + "turn/end": {"turn_id": KEEP, **OUTCOME}, + "turn/start": {"turn_id": KEEP}, +} +LINES = { + "header": {"kind": KEEP, "session_id": SESSION_ID, "export": INTEGER, + "store_format": INTEGER, "sensitive": BOOL}, + "branch": {"kind": KEEP, "head": INTEGER, + "info": {"id": KEEP, "parent": KEEP, "branch_point": INTEGER, "create_anchor": INTEGER}}, + "end": {"kind": KEEP, "branches": INTEGER, "events": INTEGER}, +} + + +def line_spec(record, data=None): + """The spec of one line; `data` overrides the spec of an event's data.""" + event = record.get("event") + if record.get("kind") != "event" or not isinstance(event, dict): + return LINES.get(record.get("kind"), {"kind": KEEP}) + if data is None: + data = EVENTS.get(f"{event.get('type')}/{event.get('name')}", ("omit-data",)) + return {"kind": KEEP, "branch_id": KEEP, "batch_end": INTEGER, "trace": obj("other"), + "event": {"id": KEEP, "sequence": INTEGER, "create_at": INTEGER, "parent_call_id": CALL, + "type": KEEP, "name": KEEP, "data": data}} + + +def walk(value, spec, visit): + """Projects declared fields and passes reviewable values to `visit`.""" + if callable(spec): + spec = spec(value) + if spec == ("omit-data",): + return {} + if value is None: + return None + if spec == USER_CONTENT: + if not isinstance(value, list): + return walk(value, text("user-input"), visit) + projected = [] + for index, item in enumerate(value): + body = item.get("text") if isinstance(item, dict) and item.get("type") == "text" else None + kind = "injected" if index and isinstance(body, str) and RUNTIME_MARKUP.match(body) else "user-input" + projected.append(walk(item, block(kind), visit)) + return projected + if isinstance(spec, dict) and isinstance(value, dict): + return {k: visit("opaque", None, v) if opaque_field(value, k) else walk(v, spec[k], visit) + for k, v in value.items() if k in spec} + if isinstance(spec, list) and isinstance(value, list): + return [walk(v, spec[0], visit) for v in value] + if ((spec == INTEGER and type(value) is int) + or (spec == BOOL and type(value) is bool) + or (spec == NUMBER and (type(value) is int or type(value) is float and math.isfinite(value)))): + return value + if isinstance(spec, tuple): + op, *args = spec + if isinstance(value, str) and op in ("keep", "session", "id", "tool", "pass"): + return visit(op, args[0] if args else None, value) if value else value + if op == "text" and isinstance(value, str): + return visit("text", args[0], value) if value else value + if op == "object" and isinstance(value, (dict, list)): + return visit("object", args[0], value) if value else value + raise Refused("input: a listed Timeline field has an unexpected JSON type") + + +def canonical(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def read(path): + with open(path, encoding="utf-8") as lines: + for line in lines: + if line.strip(): + record = json.loads(line) + if not isinstance(record, dict): + raise Refused("input: each Timeline line must be a JSON object") + if not isinstance(record.get("kind"), str): + raise Refused("input: each Timeline line must have a string `kind`") + yield record + + +# Delta text is dealt with at stream scope; its other fields use the same allowlist as ordinary events. +DELTA = {**IDS, "delta": PASS} + + +def is_delta(record): + """Whether a line is one delta of a stream, whatever other fields its data has. + + `dimcode export` writes `DeltaData` (`turn_id`, `request_id`, `delta`); a + copy read from the store's batched rows may carry the delta alone. + """ + event = record.get("event") + return (record.get("kind") == "event" and isinstance(event, dict) and event.get("type") == "step" + and event.get("name") in RUNS and isinstance(event.get("data"), dict) + and isinstance(event["data"].get("delta"), str)) + + +def streams(records): + """Pairs each line with the stream its delta belongs to, or with None. + + Streamed output is committed as many delta events, each as short as one + character, and other events can be committed between two of them; an + identifier can straddle any two. A stream is every delta of one kind in + one model request of one branch, from its `step/model-start` to its + `step/model-output-end`, whatever lies between: it is replaced, kept and + checked as one string. + """ + segment, branch = 0, None + for record in records: + event = record.get("event") + if record.get("kind") == "event" and isinstance(event, dict): + if record.get("branch_id") != branch or ( + event.get("type") == "step" and event.get("name") in ("model-start", "model-output-end")): + segment += 1 + branch = record.get("branch_id") + yield record, ((branch, segment, event["name"]) if is_delta(record) else None) + + +def with_delta(record, delta): + event = record["event"] + return {**record, "event": {**event, "data": {**event["data"], "delta": delta}}} + + +# ---- Pass one: what the export holds ----------------------------------------- + + +@dataclass +class Unit: + number: int + kind: str + size: int + where: str + seen: int = 1 + kept: bool = False + + @property + def name(self): + return f"u{self.number}" + + @property + def stub(self): + return f"[omitted {self.name} {self.kind} {self.size}B]" + + +class Scan: + def __init__(self, export): + self.units = {} + self.ids = {"call": {}, "item": {}} + self.tools = {} + self.sources = {} + self.sessions = {} + self.homes = set() + self.models = set() + self.external = set() + self.streams = {} # stream -> (where it starts, its deltas) + self.where = "" + header = last = None + lines = events = branches = 0 + for record, stream in streams(read(export)): + header = header or record + last = record + lines += 1 + events += record.get("kind") == "event" + branches += record.get("kind") == "branch" + self.where = self.position(record) + if stream is None: + self.note(record) + walk(record, line_spec(record), self.visit) + continue + self.streams.setdefault(stream, (self.where, []))[1].append(record["event"]["data"]["delta"]) + walk(record, line_spec(record, DELTA), self.visit) + for (_, _, name), (where, parts) in self.streams.items(): + if any(parts): + self.where = where + self.unit("".join(parts), RUNS[name]) + if not header or header.get("kind") != "header" or not header.get("session_id"): + raise Refused("input: the export does not start with a header line containing a Session ID") + if type(header.get("export")) is not int or header["export"] != 1 or type(header.get("store_format")) is not int: + raise Refused("input: expected a v1 Timeline export and integer storage version") + if header.get("sensitive") is not True: + raise Refused("input: expected the Timeline export to be marked sensitive") + if not last or last.get("kind") != "end" or last.get("events") != events or last.get("branches") != branches: + raise Refused("input: the export is incomplete; it must end with an `end` line whose counts match") + self.lines = lines + self.export = {"export": header.get("export"), "store_format": header.get("store_format")} + + @staticmethod + def position(record): + event = record.get("event") + if isinstance(event, dict): + return f"{record.get('branch_id')}#{event.get('sequence')}" + return str(record.get("kind")) + + def note(self, record): + """Facts read outside the walk: environment, tool sources, the model, and external files.""" + event = record.get("event") + data = event.get("data") if isinstance(event, dict) else None + if not isinstance(data, dict): + return + event_kind = f"{event.get('type')}/{event.get('name')}" + if event_kind == "input/message" and isinstance(data.get("blocks"), list): + for item in data["blocks"]: + if not isinstance(item, dict) or item.get("type") != "raw": + continue + key, body = item.get("key"), item.get("text") + if (isinstance(key, str) and key.split(":", 2)[:2] == ["state", "dim/environment/context"] + and isinstance(body, str)): + self.homes.update(unescape(value) for value in HOME.findall(body)) + model_field = {"model/call": "request", "context/prepare": "request", + "context/configured": "settings"}.get(event_kind) + holder = data.get(model_field) + if isinstance(holder, dict): + provider, model = holder.get("providerId"), holder.get("modelId") + if isinstance(provider, str) and isinstance(model, str): + self.models.add(f"{provider}/{model}") + tools = holder.get("tools") + for tool in tools if isinstance(tools, list) else (): + if isinstance(tool, dict) and isinstance(tool.get("name"), str): + source = tool.get("source") + self.sources.setdefault(tool["name"], source if isinstance(source, str) else None) + stack = [data] + while stack: + value = stack.pop() + if isinstance(value, dict): + for key, child in value.items(): + if key in ("output_path", "outputPath") and isinstance(child, str) and child: + self.external.add(child) + stack.append(child) + elif isinstance(value, list): + stack.extend(value) + + def unit(self, key, kind): + unit = self.units.get(key) + if unit is None: + self.units[key] = Unit(len(self.units) + 1, kind, len(key.encode()), self.where) + return + unit.seen += 1 + if RANK[kind] < RANK[unit.kind]: + unit.kind, unit.where = kind, self.where + + def visit(self, op, arg, value): + if op == "text": + self.unit(value, arg) + if arg == "user-input": + self.external.update(PASTED.findall(value)) + elif op == "object": + self.unit("\0" + canonical(value), arg) + elif op == "id": + self.ids[arg].setdefault(value, len(self.ids[arg]) + 1) + elif op == "tool": + self.tools.setdefault(value, len(self.tools) + 1) + elif op == "session": + if value not in self.sessions: + self.sessions[value] = f"00000000-0000-4000-8000-{len(self.sessions):012x}" + return value + + +# ---- Decisions and replacements ------------------------------------------------ + + +def load_decisions(path): + if path.exists(): + decisions = json.loads(path.read_text(encoding="utf-8")) + else: + # The pack id is random: it is derived from no account, Session or content. + decisions = {"pack_id": secrets.token_hex(8)} + if not isinstance(decisions, dict): + raise Refused("decisions: expected a JSON object") + pack_id = decisions.get("pack_id") + if not isinstance(pack_id, str) or not PACK_ID.fullmatch(pack_id): + raise Refused("decisions: `pack_id` must be the generated 16-digit lowercase hex identifier") + for name in ("keep", "omit", "terms", "number_tools"): + decisions.setdefault(name, []) + if not isinstance(decisions[name], list) or not all(isinstance(v, str) and v for v in decisions[name]): + raise Refused(f"decisions: `{name}` must be a list of non-empty strings") + return decisions + + +def save_decisions(path, decisions): + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + handle, temporary = tempfile.mkstemp(dir=path.parent) + temporary = Path(temporary) + try: + with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as output: + json.dump(decisions, output, ensure_ascii=False, indent=2, allow_nan=False) + output.write("\n") + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def consent_of(decisions, replacements): + consent = decisions.get("consent") + if not isinstance(consent, dict): + raise Refused("consent: name `diagnosis`, `regression`, `providers` and `expires`" + " in the decisions file before confirming") + for name in ("diagnosis", "regression"): + if not isinstance(consent.get(name), bool): + raise Refused(f"consent: `{name}` must be true or false") + providers = consent.get("providers") + if not isinstance(providers, list) or not all( + isinstance(v, str) and PROVIDER_ID.fullmatch(v) and not replacements.inspect(v)["secret"] for v in providers): + raise Refused("consent: `providers` must contain only provider IDs (letters, digits, `.`, `_`, `-`), not credentials") + if consent["regression"] and not providers: + raise Refused("consent: a pack kept for the corpus must name at least one provider") + expires = consent.get("expires") + if not isinstance(expires, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", expires): + raise Refused("consent: `expires` must be an ISO date, YYYY-MM-DD") + try: + expiry = date.fromisoformat(expires) + except ValueError: + raise Refused("consent: `expires` is not a valid calendar date") from None + given = date.today() + if expiry < given: + raise Refused("consent: `expires` has already passed; confirm with a current expiry date") + return {"diagnosis": consent["diagnosis"], "regression": consent["regression"], + "providers": providers, "expires": expires, "given": given.isoformat()} + + +class Redactor: + def __init__(self, process, scan, decisions, kept): + self.process = process + self.memo = {} + self.counted = set() + self.calls = {v: f"call-{n}" for v, n in scan.ids["call"].items()} + self.items = {v: f"item-{n}" for v, n in scan.ids["item"].items()} + self.kept_tools = {name for name in scan.tools + if scan.sources.get(name) in KEPT_TOOL_SOURCES and name not in decisions["number_tools"]} + self.tools = {name: name if name in self.kept_tools else f"tool-{n}" for name, n in scan.tools.items()} + identifiers = {**self.calls, **self.items, **self.tools} + self.sessions = scan.sessions + primary, *members = self.sessions + if {s.casefold() for s in self.sessions} & set(self.sessions.values()): + raise Refused("input: a Session ID collides with a pack stand-in") + init = self.request({"facts": {"homes": sorted(scan.homes), "session": primary, + "member_sessions": [(s, self.sessions[s]) for s in members], + "identifiers": list(identifiers.items()), "terms": decisions["terms"]}, + "kept": kept}) + self.labels = init["labels"] + self.hits = dict.fromkeys(self.labels, 0) + self.homes = init["homes"] + self.unreplaced_accounts = set(init["unreplaced_accounts"]) + if init["session"] != SESSION or any(self.labels.get(s) != label for s, label in self.sessions.items()): + raise Refused("evidence-redact: expected a distinct stand-in for every Session ID; use an up-to-date dimcode") + if any(self.inspect(s)["text"] != label for s, label in self.sessions.items()): + raise Refused("evidence-redact: Session IDs do not have unambiguous stand-ins") + + def request(self, value): + try: + self.process.stdin.write(json.dumps(value) + "\n") + self.process.stdin.flush() + return json.loads(self.process.stdout.readline()) + except (OSError, ValueError) as error: + raise Refused("evidence-redact: could not exchange JSONL with the trusted dimcode") from error + + def inspect(self, value): + if value not in self.memo: + self.memo[value] = self.request(value) + return self.memo[value] + + def text(self, value): + reply = self.inspect(value) + if value not in self.counted: + self.counted.add(value) + for _, _, original, _ in reply["spans"]: + self.hits[original] += 1 + return reply["text"] + + def tree(self, value): + if isinstance(value, str): + return REMOVED if value == REMOVED else self.text(value) + if isinstance(value, dict): + return {self.text(k): REMOVED if opaque_field(value, k) else self.tree(v) for k, v in value.items()} + if isinstance(value, list): + return [self.tree(v) for v in value] + return value + + def cut(self, parts): + """Replaces in the joined text and cuts it again at the original boundaries.""" + full = "".join(parts) + new = self.text(full) + moved = [] # (old end, new end) of each replaced span + shift = 0 + for start, end, _, label in self.inspect(full)["spans"]: + shift += len(label) - (end - start) + moved.append((start, end, end + shift)) + out, at, previous = [], 0, 0 + for part in parts: + at += len(part) + cut = at + for start, end, new_end in moved: + if at <= start: + break + # A boundary inside a replaced span moves to the span's end. + cut = new_end if at < end else at + (new_end - end) + out.append(new[previous:cut]) + previous = cut + return out + + +# ---- Pass two: the pack ---------------------------------------------------------- + + +class Packer: + def __init__(self, scan, replacements): + self.scan = scan + self.replace = replacements + + def visit(self, op, arg, value): + if op in ("keep", "pass"): + return value + if op == "opaque": + return REMOVED + if op == "session": + return self.replace.sessions[value] + if op == "id": + return (self.replace.calls if arg == "call" else self.replace.items)[value] + if op == "tool": + return self.replace.tools[value] + if op == "text": + unit = self.scan.units[value] + return self.replace.text(value) if unit.kept else unit.stub + unit = self.scan.units["\0" + canonical(value)] + if unit.kept: + return self.replace.tree(value) + return {"omitted": unit.stub} if isinstance(value, dict) else [unit.stub] + + def lines(self, export): + parts = {} + for record, stream in streams(read(export)): + if stream is None: + yield walk(record, line_spec(record), self.visit) + continue + if stream not in parts: + original = self.scan.streams[stream][1] + unit = self.scan.units.get("".join(original)) + if unit is None: + new = original + elif unit.kept: + new = self.replace.cut(original) + else: + new = [unit.stub] + [""] * (len(original) - 1) + parts[stream] = iter(new) + yield walk(with_delta(record, next(parts[stream])), line_spec(record, DELTA), self.visit) + + +# ---- Checks: read the pack again ------------------------------------------------- + + +def same_shape(before, after): + """Whether two values have the same JSON types; an omitted subtree matches any container.""" + if isinstance(after, dict) and set(after) == {"omitted"} and isinstance(before, dict): + return True + if isinstance(after, list) and len(after) == 1 and isinstance(after[0], str) and STUB.fullmatch(after[0]): + return isinstance(before, list) + if isinstance(before, dict) and isinstance(after, dict): + return len(before) == len(after) and all(same_shape(a, b) for a, b in zip(before.values(), after.values())) + if isinstance(before, list) and isinstance(after, list): + return len(before) == len(after) and all(same_shape(a, b) for a, b in zip(before, after)) + return type(before) is type(after) + + +def strings(value): + """Every string and every key of a JSON value.""" + if isinstance(value, str): + yield None, value + elif isinstance(value, dict): + for key, child in value.items(): + yield None, key + if opaque_field(value, key) and child != REMOVED: + yield key, "" + else: + yield from strings(child) + elif isinstance(value, list): + for child in value: + yield from strings(child) + + +def audit(export, packed, scan, replacements): + """Reads the written pack and returns what is wrong with it, one line per finding. + + Nothing here trusts what the packer computed while writing: the pack is + parsed and classified again, and compared with the export line by line. + """ + kept_text = {replacements.text(key) for key, unit in scan.units.items() if unit.kept and key[:1] != "\0"} + kept_trees = {canonical(replacements.tree(json.loads(key[1:]))) + for key, unit in scan.units.items() if unit.kept and key[:1] == "\0"} + tools = set(replacements.kept_tools) + found = [] + clean = set() # placeholders repeat in every request; each distinct string is searched once + + def content_ok(value): + return not value or bool(STUB.fullmatch(value)) or value in kept_text + + def source_field(op, arg, value): + if op == "session": + expected_sessions.append(replacements.sessions[value]) + return value + + def visit(op, arg, value): + if op == "session": + written_sessions.append(value) + elif op == "text" and not content_ok(value): + found.append(f"content: {where} holds a string that is neither a placeholder nor a kept unit") + elif op == "object": + stub = value.get("omitted") if isinstance(value, dict) and set(value) == {"omitted"} else ( + value[0] if isinstance(value, list) and len(value) == 1 else None) + if not (isinstance(stub, str) and STUB.fullmatch(stub)) and canonical(value) not in kept_trees: + found.append(f"content: {where} holds a subtree that is neither a placeholder nor a kept unit") + elif op == "id" and not PSEUDONYM.fullmatch(value): + found.append(f"identifier: {where} holds a provider identifier") + elif op == "tool" and value not in tools and not PSEUDONYM.fullmatch(value): + found.append(f"tool name: {where} holds a name that is neither kept nor numbered") + elif op == "opaque" and value != REMOVED: + found.append(f"opaque: {where} still holds a provider blob") + return value + + def residue(where, value): + reply = replacements.inspect(value) + if reply["spans"]: + found.append(f"replacement: {where} still holds a replaced identifier") + elif reply["secret"]: + found.append(f"secret: {where} holds a string shaped like a credential") + else: + return False + return True + + before = read(export) + pending = {} # stream -> (where it starts, its deltas in the pack) + count = 0 + for new, stream in streams(read(packed)): + old = next(before, None) + if old is None: + found.append("structure: the pack has more lines than the export") + break + where = Scan.position(new) + count += 1 + spec = line_spec(old, DELTA if is_delta(old) else None) + expected_sessions, written_sessions = [], [] + projected = walk(old, spec, source_field) + if not same_shape(projected, new) or any( + old.get(k) != new.get(k) for k in ("kind", "branch_id", "batch_end")) or any( + (old.get("event") or {}).get(k) != (new.get("event") or {}).get(k) + for k in ("id", "sequence", "create_at", "type", "name") if isinstance(old.get("event"), dict)): + found.append(f"structure: {Scan.position(old)} differs from the allowed export structure") + try: + if walk(new, spec, visit) != new: + found.append(f"structure: {where} holds an unlisted field") + if expected_sessions != written_sessions: + found.append(f"identifier: {where} does not reference the expected Session stand-in") + except Refused: + found.append(f"structure: {where} holds an unexpected JSON type") + for key, value in strings(new): + if key and value != REMOVED: + found.append(f"opaque: {where} still holds a provider blob") + elif value not in clean and not residue(where, value): + clean.add(value) + if stream is not None: + pending.setdefault(stream, (where, []))[1].append(new["event"]["data"]["delta"]) + # A reader joins the deltas, so the check reads them joined: two halves + # of a name pass every check one at a time. + for start, parts in pending.values(): + joined = "".join(parts) + if not content_ok(joined): + found.append(f"content: the stream starting at {start} is neither a placeholder nor a kept unit") + residue(f"the stream starting at {start}", joined) + if next(before, None) is not None or count != scan.lines: + found.append("structure: the pack and the export have different line counts") + for labels in (replacements.calls, replacements.items): + if len(set(labels.values())) != len(labels): + found.append("structure: two identifiers share one stand-in") + return found + + +# ---- Output ----------------------------------------------------------------------- + + +def private(path, body): + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + handle = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as out: + out.write(body) + except BaseException: + path.unlink(missing_ok=True) + raise + + +def fence(body): + ticks = "`" * max(3, 1 + max((len(run) for run in re.findall(r"`+", body)), default=0)) + return f"{ticks}text\n{body}\n{ticks}" + + +def review(scan, replacements, candidate, confirmation): + kept = [(key, unit) for key, unit in scan.units.items() if unit.kept] + omitted = [unit for unit in scan.units.values() if not unit.kept] + lines = [ + "# Evidence pack review", "", + "This file stays on your machine. Do not upload it or commit it.", "", + "Read the full [Timeline](pack/timeline.jsonl) and the exact manifest in section 5." + " The units below are a reading aid, not a substitute for reviewing both files.", "", + "## 1. Kept content", "", + "Read every unit on each pass, even when its id is unchanged. To drop a unit, remove it from" + " `keep` if listed there, and add its id to `omit` if it is kept by default. Then run again.", "", + ] + hosts, owners, folders = set(), set(), set() + homes = {h.rstrip("/") for h in scan.homes.union(replacements.homes) if h.rstrip("/")} + for key, unit in kept: + body = key[1:] if key[:1] == "\0" else key + shown = canonical(replacements.tree(json.loads(body))) if key[:1] == "\0" else replacements.text(body) + lines += [f"### {unit.name}: {unit.kind}, first at {unit.where}, {unit.seen} occurrences", ""] + hints = sorted({m.group(0)[:60] for m in ASSIGNMENT.finditer(shown)}) + if hints: + lines += ["Looks like an assignment of a secret; check it: " + ", ".join(f"`{h}`" for h in hints), ""] + lines += [fence(shown), ""] + hosts.update(h.lower() for h in URL_HOST.findall(shown)) + owners.update(a or b for a, b in HOSTED_OWNER.findall(shown)) + for home in homes: + folders.update(re.findall(re.escape(home) + r"/([^/\s\"'<>]+)", shown)) + lines += ["## 2. Replacements", "", "| Original | Stands in | Times |", "|---|---|---:|"] + lines += [f"| `{original}` | `{replacements.labels[original]}` | {times} |" + for original, times in replacements.hits.items() if times] + candidates = sorted((hosts - PUBLIC_HOSTS) | owners | folders | replacements.unreplaced_accounts) + if not scan.homes: + lines += ["", "The export records no home directory, so no account name was replaced. Add yours to" + " `terms`."] + lines += ["", "Not replaced, and possibly identifying. Add any of these to `terms` to replace it:", ""] + lines += [f"- `{c}`" for c in candidates] or ["- none found"] + extension = sorted(n for n in replacements.kept_tools if scan.sources.get(n) != "builtin") + lines += ["", "Tool names kept as they are. Add one to `number_tools` to number it instead:", ""] + lines += [f"- `{n}`" for n in extension] or ["- none besides the built-in tools"] + lines += ["", "## 3. Omitted units", "", + "Each is a placeholder in the pack. To keep one, add its id to `keep` and run again.", "", + "| Unit | Kind | First at | Bytes | Occurrences |", "|---|---|---|---:|---:|"] + lines += [f"| {u.name} | {u.kind} | {u.where} | {u.size} | {u.seen} |" for u in omitted] + lines += ["", "## 4. Files the Timeline refers to", "", "They are not in the export and are not packed.", ""] + lines += [f"- `{p}`" for p in sorted(scan.external)] or ["- none"] + lines += ["", "## 5. Manifest and confirmation", "", fence(candidate.rstrip("\n")), ""] + if confirmation is None: + lines += ["Add `diagnosis`, `regression`, `providers` and `expires` under `consent` and rerun without" + " `--confirm` to preview the complete manifest.", ""] + else: + lines += [f"After reviewing both files in full, run again with `--confirm {confirmation}`.", + "If either file or the authorization changes, rerun the preview and review both again.", ""] + return "\n".join(lines) + + +def manifest(scan, replacements, decisions, digest): + kinds = {} + for unit in scan.units.values(): + entry = kinds.setdefault(unit.kind, {"kept": 0, "kept_bytes": 0, "omitted": 0, "omitted_bytes": 0}) + state = "kept" if unit.kept else "omitted" + entry[state] += 1 + entry[f"{state}_bytes"] += unit.size + stand_ins = sorted({replacements.labels[o] for o, times in replacements.hits.items() if times}) + manifest = { + "pack_id": decisions["pack_id"], "rules": RULES_VERSION, "level": 2 if decisions["keep"] else 1, + "source": scan.export, "models": sorted(scan.models), "units": dict(sorted(kinds.items())), + "stand_ins": stand_ins, "files_not_packed": len(scan.external), "timeline_sha256": digest, + } + return manifest + + +@contextmanager +def prepare(export, decisions, dimcode=None): + """Reads the export and applies the decisions: which units are kept, what is replaced.""" + scan = Scan(export) + names = {unit.name for unit in scan.units.values()} + unknown = sorted(set(decisions["keep"] + decisions["omit"]) - names) + if unknown: + raise Refused(f"decisions: no unit is named {', '.join(unknown)}") + for unit in scan.units.values(): + unit.kept = unit.name in decisions["keep"] or ( + unit.kind in LEVEL_ONE and unit.name not in decisions["omit"]) + kept = [key for key, unit in scan.units.items() if unit.kept] + executable = dimcode if dimcode is not None else os.environ.get("DIM_EVIDENCE_DIMCODE") + if not executable or not Path(executable).is_absolute(): + raise Refused("evidence-redact: supply a trusted absolute dimcode path via --dimcode or DIM_EVIDENCE_DIMCODE") + with subprocess.Popen([executable, "evidence-redact"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, encoding="utf-8") as process: + try: + yield scan, Redactor(process, scan, decisions, kept) + process.stdin.close() + if process.wait(): + raise Refused("evidence-redact: the trusted dimcode failed") + finally: + if process.poll() is None: + process.kill() + + +def filesystem_path(path): + """Return a conservative, case-folded physical path for an existing or future path.""" + return os.path.realpath(path).casefold() + + +def under(path, directory): + path, directory = filesystem_path(path), filesystem_path(directory) + return path == directory or path.startswith(directory + os.sep) + + +def build(export, out, decisions_path=None, confirm=None, *, dimcode=None): + """Write the local review and pack; return a confirmation digest if consent was supplied.""" + export, out = Path(export), Path(out) + decisions_path = Path(decisions_path) if decisions_path else out / "decisions.json" + out = out.resolve() + lock = out / ".pack.lock" + reserved = (out / "pack", out / "pack.tmp", out / "review.md", out / ".pack-receipt", lock) + input_paths = (export, decisions_path) + if any(under(path, target) for path in input_paths for target in reserved): + raise Refused("input: the export and decisions must be separate from each other and the generated files") + if filesystem_path(export) == filesystem_path(decisions_path): + raise Refused("input: the export and decisions must be separate from each other and the generated files") + if not export.is_file(): + raise Refused("input: the export must be an existing file") + out.mkdir(parents=True, exist_ok=True, mode=0o700) + try: + lock.mkdir(mode=0o700) + except FileExistsError: + raise Refused("output: another build owns this directory; see .pack.lock in the packing instructions") from None + try: + return build_locked(export, out, decisions_path, confirm, dimcode) + finally: + lock.rmdir() + + +PACK_FILES = ("timeline.jsonl", "pack.json") + + +def file_digest(path): + digest = hashlib.sha256() + with path.open("rb") as stream: + while chunk := stream.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def receipt(pack_dir, review_path): + hashes = [file_digest(pack_dir / name) for name in PACK_FILES] + return "Dim evidence pack v1\n" + "\n".join([*hashes, file_digest(review_path)]) + "\n" + + +def clear_previous(pack_dir, review_path, staging, marker): + conflict = Refused("output: existing files cannot be verified as this tool's output; " + "nothing was rebuilt. Choose a fresh --out directory") + if os.path.lexists(staging): + raise conflict + if not any(os.path.lexists(path) for path in (pack_dir, review_path, marker)): + return + if (pack_dir.is_symlink() or not pack_dir.is_dir() or {p.name for p in pack_dir.iterdir()} != set(PACK_FILES) + or any(p.is_symlink() or not p.is_file() for p in [*(pack_dir / n for n in PACK_FILES), review_path, marker])): + raise conflict + expected = receipt(pack_dir, review_path).encode("ascii") + with marker.open("rb") as stream: + if stream.read(len(expected) + 1) != expected: + raise conflict + for name in PACK_FILES: + (pack_dir / name).unlink() + pack_dir.rmdir() + review_path.unlink() + marker.unlink() + + +def build_locked(export, out, decisions_path, confirm, dimcode): + pack_dir, review_path, staging, marker = (out / name for name in ("pack", "review.md", "pack.tmp", ".pack-receipt")) + clear_previous(pack_dir, review_path, staging, marker) + decisions = load_decisions(decisions_path) + staging.mkdir(mode=0o700) + try: + with prepare(export, decisions, dimcode) as (scan, replacements): + confirmation, review_text = write_preview(export, staging, scan, replacements, decisions, confirm) + decisions.pop("confirmed", None) + save_decisions(decisions_path, decisions) + with ExitStack() as rollback: + private(review_path, review_text) + rollback.callback(review_path.unlink) + private(marker, receipt(staging, review_path)) + rollback.callback(marker.unlink) + staging.rename(pack_dir) + rollback.pop_all() + return confirmation + finally: + if staging.exists(): + for name in PACK_FILES: + (staging / name).unlink(missing_ok=True) + staging.rmdir() + + +def write_preview(export, staging, scan, replacements, decisions, confirm): + consent = consent_of(decisions, replacements) if confirm is not None or "consent" in decisions else None + timeline = staging / "timeline.jsonl" + handle = os.open(timeline, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(handle, "wb") as written: + for line in Packer(scan, replacements).lines(export): + data = json.dumps(line, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + written.write((data + "\n").encode("utf-8")) + found = audit(export, timeline, scan, replacements) + if found: + shown = "\n ".join(sorted(set(found))[:20]) + raise Refused(f"the pack failed {len(set(found))} checks and was not written:\n {shown}") + preview = manifest(scan, replacements, decisions, file_digest(timeline)) + candidate = {**preview, "consent": consent} if consent is not None else preview + candidate_text = json.dumps(candidate, indent=2, allow_nan=False) + "\n" + for _, value in strings(candidate): + reply = replacements.inspect(value) + if reply["secret"] or reply["spans"]: + raise Refused("manifest: a field contains a credential or an identifier marked for replacement") + confirmation = hashlib.sha256(candidate_text.encode("utf-8")).hexdigest() if consent is not None else None + if confirm is not None and confirm != confirmation: + raise Refused("confirm: the Timeline or manifest changed; rerun without --confirm and review both files") + manifest_text = candidate_text if confirm is not None else json.dumps(preview, indent=2) + "\n" + private(staging / "pack.json", manifest_text) + if (staging / "pack.json").read_bytes() != manifest_text.encode("utf-8"): + raise Refused("manifest: the written file does not match the audited manifest") + return confirmation, review(scan, replacements, candidate_text, confirmation) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("export", help="the file written by `dimcode export`") + parser.add_argument("--out", required=True, help="directory for pack/, review.md and the decisions file") + parser.add_argument("--decisions", help="decisions file (default: OUT/decisions.json)") + parser.add_argument("--confirm", metavar="DIGEST", help="confirm both reviewed files and record consent") + parser.add_argument("--dimcode", metavar="PATH", help="trusted absolute dimcode path (or set DIM_EVIDENCE_DIMCODE)") + args = parser.parse_args(argv) + try: + digest = build(args.export, args.out, args.decisions, args.confirm, dimcode=args.dimcode) + except Refused as refusal: + print(f"refused: {refusal}", file=sys.stderr) + return 1 + except (OSError, json.JSONDecodeError) as failure: + print(f"error: {failure}", file=sys.stderr) + return 2 + print(f"pack: {Path(args.out) / 'pack'}") + print(f"review (local only): {Path(args.out) / 'review.md'}") + if digest is None: + print("local preview only: add consent and rerun to obtain a confirmation digest") + else: + print(f"confirmation digest: {digest}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarks/usercases/pack_flow_test.py b/benchmarks/usercases/pack_flow_test.py new file mode 100644 index 0000000000..ee235f4f52 --- /dev/null +++ b/benchmarks/usercases/pack_flow_test.py @@ -0,0 +1,1079 @@ +"""A Timeline export leaves the machine only as the pack the submitter read. + +The export here is built by the test: no real Session, no model. Its shape is +the one `dimcode export` writes (docs/design/appserver/timeline-export.md §5): +event data are the Rust serializations, and `test_deltas_have_the_fields_rust_writes` +pins the one whose shape the packer depends on. + +Run with DIM_EVIDENCE_DIMCODE set to a trusted absolute path to the built CLI: +python3 -m unittest discover -s benchmarks/usercases -p 'pack_flow_test.py' +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import sys +import tempfile +import unittest +import urllib.parse +from concurrent.futures import ThreadPoolExecutor +from datetime import date, timedelta +from pathlib import Path +from threading import Event +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import pack # noqa: E402 + +SESSION = "5e0b1c1e-1111-4222-8333-444455556666" +EXEC_CALL = "call_00_abcdefghijklmnop" +LOOKUP_CALL = "call_01_qrstuvwxyzabcdef" +LOOKUP = "mcp_zebra_lookup" +LISTING = "-rw-r--r-- 1 alice staff 12 MARK-RESULT notes.txt" +THINKING = ["I should look at MARK-TH", "INKING in /Users/al", "ice/work first."] +REPLY = ["It is owned by alice (", "/Users/al", "ice/work). Also \\/Users\\/alice and %2FUsers%2Falice. ", + "-rw-r--r-- 1 alice staff"] +ASK = "List /Users/alice/work and say who owns it. See https://wiki.internal.example.net/owners" +ENVIRONMENT = "\n/Users/alice/work\n/Users/alice\n" +MARKS = ["MARK-RESULT", "MARK-THINKING", "MARK-OPAQUE", "MARK-UNKNOWN", "MARK-NESTED", "MARK-ARGS", "MARK-KEY", + "MARK-LOOKUP", "MARK-REQUEST-ONLY", "MARK-TRACE", "MARK-REASON", "MARK-SYSTEM", "MARK-TOOLDEF", "zebra"] + + +def export_lines(home="/Users/alice", turn="turn-0001", end=True): + """One short Session: a question, a thought, two tool calls, an answer.""" + user = home.rsplit("/", 1)[1] + + def own(value): + return (value.replace(urllib.parse.quote("/Users/alice", safe=""), urllib.parse.quote(home, safe="")) + .replace("/Users/alice", home) + .replace("alice", user)) + + tools = [ + {"name": "exec", "source": "builtin", "description": "Run a command. MARK-TOOLDEF", + "inputSchema": {"type": "object", "properties": {"command": {"type": "string"}}}}, + {"name": "web_fetch", "source": "extension", "description": "Fetch a page.", "inputSchema": {}}, + {"name": LOOKUP, "source": "dynamic", "description": "Look things up.", "inputSchema": {}}, + ] + model = {"providerId": "test", "modelId": "model-1", "capabilitySnapshot": {"reasoning": {"mode": "effort"}}, + "metadata": {"providerProtocol": "openai-compatible"}, "config": {"maxTokens": 100.0}} + ids = {"turn_id": turn, "request_id": "request-0001"} + exec_input = {"command": own("ls -l /Users/alice/work MARK-ARGS")} + lookup_input = {"MARK-KEY": "MARK-LOOKUP arguments"} + thinking = {"type": "thinking", "thinking": own("".join(THINKING)), "signature": "MARK-OPAQUE", + "providerMetadata": {"protocol": "openai-responses", "itemId": "rs_0123456789abcdef"}} + calls = [{"type": "tool_use", "id": EXEC_CALL, "name": "exec", "input": exec_input}, + {"type": "tool_use", "id": LOOKUP_CALL, "name": LOOKUP, "input": lookup_input}] + asked = [{"role": "user", "content": [{"type": "text", "text": own(ENVIRONMENT)}]}, + {"role": "user", "content": own(ASK)}, + {"role": "user", "content": "MARK-REQUEST-ONLY reminder"}] + answered = asked + [ + {"role": "assistant", "content": [thinking] + calls}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": EXEC_CALL, "content": own(LISTING)}, + {"type": "tool_result", "tool_use_id": LOOKUP_CALL, "content": "MARK-LOOKUP result"}]}, + ] + events = [ + ("branch", "start", {}), + ("context", "configured", {"timeline": "main", "revision": "rev-1", + "settings": {**model, "tools": tools}, "system": "You are DimAgent. MARK-SYSTEM"}), + ("input", "message", {"mode": "append", "blocks": [ + {"type": "raw", "key": "state:dim/environment/context", "text": own(ENVIRONMENT)}]}), + ("input", "message", {"submission_id": "submission-1", + "user": {"content": [{"type": "text", "text": own(ASK)}]}}), + ("turn", "start", {"turn_id": turn}), + ("model", "call", {**ids, "request": {**model, "messages": asked, "tools": tools, + "system": "You are DimAgent. MARK-SYSTEM"}}), + ("step", "model-start", ids), + *[("step", "thinking", {**ids, "delta": own(part)}) for part in THINKING], + ("step", "tool-use-start", {**ids, "call_id": EXEC_CALL, "name": "exec"}), + ("step", "tool-use", {**ids, "call": {"id": EXEC_CALL, "name": "exec", "input": exec_input}}), + ("step", "tool-use", {**ids, "call": {"id": LOOKUP_CALL, "name": LOOKUP, "input": lookup_input}}), + ("step", "model-content", {**ids, "content": [thinking] + calls}), + ("step", "model-output-end", {**ids, "status": "completed", "finish_reason": "tool_use"}), + ("step", "tool-result", {**ids, "call_event_id": "event-call", "results": [ + {"call_id": EXEC_CALL, "result": { + "content": own(LISTING), + "structuredContent": {"command": exec_input["command"], "cwd": own("/Users/alice/work"), "exitCode": 0}, + "effects": [{"kind": "exec", "command": exec_input["command"], "exitCode": 0}]}}, + {"call_id": LOOKUP_CALL, "result": {"content": "MARK-LOOKUP result", "isError": False}}]}), + ("acme", "custom", {"note": "MARK-UNKNOWN", "nested": {"deep": "MARK-NESTED"}, "count": 3}), + ("model", "call", {**ids, "request_id": "request-0002", + "request": {**model, "messages": answered, "tools": tools, + "system": "You are DimAgent. MARK-SYSTEM"}}), + *[("step", "text", {**ids, "request_id": "request-0002", "delta": own(part)}) for part in REPLY], + ("step", "model-content", {**ids, "request_id": "request-0002", "content": [ + {"type": "text", "text": own("".join(REPLY)), + "providerMetadata": {"protocol": "openai-responses", "itemId": "msg_0123456789abcdef"}}]}), + ("turn", "end", {"turn_id": turn, "status": "completed", "reason": "MARK-REASON end_turn"}), + ("model", "usage", {**ids, "usage": {"promptTokens": 10.0, "completionTokens": 2.0}}), + ("exec", "started", {**ids, "call_id": EXEC_CALL, "task_id": "exec-1", "description": "MARK-ARGS in background", + "output_path": own("/Users/alice/.dimcode/output.txt")}), + ] + lines = [{"kind": "header", "export": 1, "session_id": SESSION, "store_format": 50, "sensitive": True}, + {"kind": "branch", "info": {"id": "main"}, "head": len(events)}] + for sequence, (kind, name, data) in enumerate(events, 1): + trace = {"event_id": f"event-{sequence}", "original": {"note": "MARK-TRACE"}, "steps": []} + lines.append({"kind": "event", "branch_id": "main", + "event": {"id": f"event-{sequence}", "sequence": sequence, "create_at": 1000 + sequence, + "type": kind, "name": name, "data": data}, + "trace": trace if name == "tool-result" else None, "batch_end": sequence}) + if end: + lines.append({"kind": "end", "branches": 1, "events": len(events)}) + return lines + + +CHILD = "4f1e2d3c-0000-4000-8000-00000000c41d" +CHILD_ASK = "Now do the same for /Users/alice/play." +CHILD_REPLY = "Done: /Users/alice/play is owned by alice too." +DECOY = "fn prompt() { format!(\"/home/fixture\") }" + + +def branched_export(main_first=False): + """`export_lines` with a child branch forked from `main` after its first turn. + + `dimcode export` writes branches in directory order, and every branch id + sorts before "main", so the child comes first. Its first request carries + the context it inherited from `main`; its own events start after the fork. + """ + lines = export_lines() + header, main_branch, main_events, end = lines[0], lines[1], lines[2:-1], lines[-1] + events = {line["event"]["sequence"]: line["event"]["data"] for line in main_events} + request = events[18]["request"] + inherited = [message for message in request["messages"][:2]] + [ + {"role": "assistant", "content": [{"type": "text", "text": events[23]["content"][0]["text"]}]}, + {"role": "user", "content": [{"type": "text", "text": CHILD_ASK}]}, + ] + ids = {"turn_id": "turn-child", "request_id": "request-child"} + child = [ + ("branch", "start", {}), + # A tool result that quotes the home tag, read before any of Dim's own + # environment blocks: it must not be taken for the home directory. + ("exec", "ended", {"task_id": "exec-0", "status": "completed", "result": {"content": DECOY}}), + ("input", "message", {"submission_id": "submission-child", + "user": {"content": [{"type": "text", "text": CHILD_ASK}]}}), + ("turn", "start", {"turn_id": "turn-child"}), + ("model", "call", {**ids, "request": {**request, "messages": inherited}}), + ("step", "model-start", ids), + ("step", "model-content", {**ids, "content": [{"type": "text", "text": CHILD_REPLY}]}), + ("step", "model-output-end", {**ids, "status": "completed", "finish_reason": "stop"}), + ("turn", "end", {"turn_id": "turn-child", "status": "completed", "reason": "end_turn"}), + ] + child_branch = {"kind": "branch", "info": {"id": CHILD, "parent": "main", "branch_point": 25, + "create_anchor": 25}, "head": len(child)} + child_events = [{"kind": "event", "branch_id": CHILD, + "event": {"id": f"child-{n}", "sequence": n, "create_at": 5000 + n, "type": kind, + "name": name, "data": data}, "trace": None, "batch_end": n} + for n, (kind, name, data) in enumerate(child, 1)] + end = {**end, "branches": 2, "events": end["events"] + len(child)} + if main_first: + return [header, main_branch, child_branch, *main_events, *child_events, end] + return [header, child_branch, main_branch, *child_events, *main_events, end] + + +SPLIT = ["我看完了 /Users/jin", "yaxuan/Desktop 的文件,jin", "yaxuan 说先别动"] + + +def split_export(interrupt): + """The second reply streamed as SPLIT, the account name cut across deltas. + + With `interrupt`, another event is committed between each two deltas, as a + provider may do mid-block; the reader still sees one sentence. + """ + lines, out, done = export_lines(home="/Users/jinyaxuan"), [], False + for line in lines: + event = line.get("event") or {} + if event.get("name") == "text": + if not done: + for n, part in enumerate(SPLIT): + if n and interrupt: + out.append({**line, "event": {**event, "type": "model", "name": "usage", "data": { + "turn_id": "turn-0001", "request_id": "request-0002", "usage": {"totalTokens": 1.0}}}}) + out.append({**line, "event": {**event, "data": {**event["data"], "delta": part}}}) + done = True + continue + if event.get("name") == "model-content" and event["data"]["request_id"] == "request-0002": + event["data"]["content"][0]["text"] = "".join(SPLIT) + out.append(line) + events = [line for line in out if line["kind"] == "event"] + for sequence, line in enumerate(events, 1): + line["event"] = {**line["event"], "sequence": sequence} + line["batch_end"] = sequence + out[1]["head"] = out[-1]["events"] = len(events) + return out + + +def boundary_export(): + """A denial, an interrupt, a compaction and a delegation recorded after the turn.""" + extra = [ + ("approval", "request", {"approval_id": "approval-1", + "source": {"kind": "tool", "turn_id": "turn-0001", + "request_id": "request-0001", "call_id": EXEC_CALL}, + "call": {"name": "exec", "input": {"command": "MARK-APPROVAL rm -rf /Users/alice"}}, + "reason": "MARK-APPROVAL-REASON to clean the workspace"}), + ("approval", "respond", {"approval_id": "approval-1", "decision": "deny"}), + ("approval", "cancelled", {"approval_id": "approval-2", "reason": "MARK-CANCEL superseded"}), + ("permission", "changed", {"policy": {"version": 1, "rules": "MARK-POLICY ask first"}}), + ("stop", "interrupt", {"reason": "MARK-STOP the plan changed", "scope": "turn"}), + ("context", "compaction-start", {"turn_id": "turn-0001", "request_id": "request-0001", + "command": 5, "through": 12, "trigger": "threshold", + "strategy": "latest-messages"}), + ("context", "compaction", {"turn_id": "turn-0001", "request_id": "request-0001", "command": 5, + "start": 6, "through": 12, "status": "completed", "retain_from": "event-5", + "replacement": [{"role": "user", "content": "MARK-SUMMARY the workspace is clean"}], + "strategy": "latest-messages", "diagnostics": {"tokens": 100}}), + ("collaboration", "request", {"turn_id": "turn-0001", "request_id": "request-0001", "call_id": EXEC_CALL, + "target": {"kind": "member", "agent_id": "agent-1", + "session_id": "session-9"}, + "prompt": "MARK-COLLAB clean the tests", "title": "MARK-TITLE cleanup"}), + ("collaboration", "result", {"request_event_id": "event-1", "agent_id": "agent-1", + "session_id": "session-9", + "text": "MARK-COLLAB-RESULT done", "status": "completed"}), + ] + lines = export_lines() + end = lines.pop() + last = lines[-1]["event"]["sequence"] + for offset, (kind, name, data) in enumerate(extra, 1): + sequence = last + offset + lines.append({"kind": "event", "branch_id": "main", + "event": {"id": f"event-x{sequence}", "sequence": sequence, "create_at": 2000 + sequence, + "type": kind, "name": name, "data": data}, + "trace": None, "batch_end": sequence}) + lines[1]["head"] = end["events"] = last + len(extra) + lines.append(end) + return lines + + +class PackFlowTest(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + self.export = self.write(export_lines()) + self.out = self.root / "out" + + def tearDown(self) -> None: + self._tmp.cleanup() + + def write(self, lines, name="export.jsonl") -> Path: + path = self.root / name + path.write_text("".join(json.dumps(line, ensure_ascii=False) + "\n" for line in lines), encoding="utf-8") + return path + + def decide(self, **decisions) -> None: + path = self.out / "decisions.json" + current = json.loads(path.read_text()) if path.exists() else {"pack_id": "feedfacefeedface"} + self.out.mkdir(exist_ok=True) + path.write_text(json.dumps({**current, **decisions})) + + def packed(self) -> str: + return (self.out / "pack" / "timeline.jsonl").read_text(encoding="utf-8") + + def events(self) -> dict: + lines = [json.loads(line) for line in self.packed().splitlines()] + return {line["event"]["sequence"]: line["event"]["data"] for line in lines if line["kind"] == "event"} + + def unit_at(self, placeholder: str) -> str: + self.assertRegex(placeholder, pack.STUB) + return placeholder.split()[1] + + def test_redactor_requires_an_explicit_trusted_absolute_path(self) -> None: + with patch.dict(os.environ, {"PATH": str(self.root)}, clear=True): + for path in (None, "dimcode", "./dimcode"): + with self.subTest(path=path), self.assertRaisesRegex(pack.Refused, "absolute dimcode path"): + pack.build(self.export, self.out, dimcode=path) + self.assertFalse((self.out / "pack").exists()) + self.assertFalse((self.out / "pack.tmp").exists()) + + def test_helper_failure_removes_stale_pack_and_review(self) -> None: + helper = self.root / "dimcode" + helper.write_text("#!/bin/sh\nexit 1\n") + helper.chmod(0o700) + pack.build(self.export, self.out) + with self.assertRaisesRegex(pack.Refused, "evidence-redact"): + pack.build(self.export, self.out, dimcode=helper) + for name in ("pack", "pack.tmp", "review.md", ".pack.lock"): + self.assertFalse((self.out / name).exists()) + + def test_unowned_reserved_paths_are_left_untouched(self) -> None: + for relative in ("pack/notes.txt", "pack.tmp/notes.txt", "review.md", ".pack-receipt"): + with self.subTest(relative=relative): + out = self.root / relative.replace("/", "-") / "out" + existing = out / relative + existing.parent.mkdir(parents=True) + existing.write_bytes(b"my notes") + with self.assertRaisesRegex(pack.Refused, "fresh --out"): + pack.build(self.export, out) + self.assertEqual(existing.read_bytes(), b"my notes") + self.assertFalse((out / ".pack.lock").exists()) + + def test_a_receipt_does_not_authorize_unknown_or_modified_files(self) -> None: + for action in ("extra", "edit", "link", "missing receipt", "damaged receipt"): + with self.subTest(action=action): + out = self.root / action + pack.build(self.export, out) + timeline = out / "pack" / "timeline.jsonl" + original = timeline.read_bytes() + review = out / "review.md" + notes = self.root / "notes.txt" + notes.write_bytes(b"my notes") + if action == "extra": + (timeline.parent / "notes.txt").write_bytes(notes.read_bytes()) + elif action == "edit": + review.write_bytes(notes.read_bytes()) + elif action == "link": + review.unlink() + review.symlink_to(notes) + elif action == "missing receipt": + (out / ".pack-receipt").unlink() + else: + (out / ".pack-receipt").write_bytes(b"unrelated") + with self.assertRaisesRegex(pack.Refused, "fresh --out"): + pack.build(self.export, out) + self.assertEqual(timeline.read_bytes(), original) + if action == "extra": + self.assertEqual((timeline.parent / "notes.txt").read_bytes(), notes.read_bytes()) + if action in ("edit", "link"): + self.assertEqual(review.read_bytes(), b"my notes") + if action == "link": + self.assertTrue(review.is_symlink()) + + # ---- level one ------------------------------------------------------------ + + def test_level_one_carries_the_dialogue_and_nothing_else(self) -> None: + pack.build(self.export, self.out) + packed = self.packed() + for mark in MARKS: + self.assertNotIn(mark, packed, f"{mark} left the machine without being kept") + self.assertNotIn("alice", packed.lower(), "the account name survived in some spelling") + self.assertNotIn(SESSION, packed) + self.assertNotIn("abcdefghijklmnop", packed, "a provider identifier survived") + events = self.events() + self.assertEqual(events[4]["user"]["content"][0]["text"], + "List /Users/useru/work and say who owns it. See https://wiki.internal.example.net/owners") + reply = events[23]["content"][0]["text"] + self.assertEqual(reply, "It is owned by useru (/Users/useru/work). Also /Users/useru and /Users/useru. " + "-rw-r--r-- 1 useru staff", "an escaped or encoded spelling was missed") + self.assertRegex(events[16]["results"][0]["result"]["content"], pack.STUB) + self.assertEqual(events[13]["call"]["name"], "tool-3", "a tool that is not Dim's own kept its name") + self.assertEqual(events[12]["call"]["name"], "exec") + self.assertEqual(events[14]["content"][0]["signature"], pack.REMOVED) + self.assertEqual(events[17], {}, "an unlisted event's body left the machine") + self.assertRegex(events[24]["reason"], pack.STUB, "free text of an outcome was treated as an enum") + self.assertEqual(events[24]["status"], "completed") + self.assertEqual(events[25]["usage"], {"promptTokens": 10.0, "completionTokens": 2.0}) + self.assertEqual(sorted(p.name for p in (self.out / "pack").iterdir()), ["pack.json", "timeline.jsonl"]) + manifest = (self.out / "pack" / "pack.json").read_text() + self.assertNotIn("alice", manifest) + self.assertEqual(json.loads(manifest)["level"], 1) + + def test_submit_check_context_requires_an_explicit_keep(self) -> None: + lines = export_lines() + operator = [ + 'Operator pasted this', + "Continue with the second part of my request.", + "This sentence mentions .", + "Not a runtime marker", + " Not at the start of the block", + "", + ] + hook = 'PRIVATE-HOOK /Users/alice /home/decoy' + source = Path(__file__).resolve().parents[2] / "crates" / "dim-agent-types" / "src" / "markup.rs" + markers = re.search(r"const MARKERS: .*?= &\[(.*?)\n\];", source.read_text(), re.DOTALL) + self.assertIsNotNone(markers, "MARKERS moved; point this fixture at its definition") + runtime = [hook] + [f"<{name}{boundary}" for name in re.findall(r'"(dim-[\w-]+)"', markers[1]) + for boundary in (">context", "\u00a0source=\"test\">context")] + blocks = [{"type": "text", "text": body} for body in operator + runtime] + lines[5]["event"]["data"]["user"]["content"] = blocks + for index in (7, 19): + lines[index]["event"]["data"]["request"]["messages"][1]["content"] = blocks + export = self.write(lines) + + def copies(events): + return [events[4]["user"]["content"]] + [ + events[seq]["request"]["messages"][1]["content"] for seq in (6, 18)] + + pack.build(export, self.out) + submitted, *requests = copies(self.events()) + self.assertEqual([b["text"] for b in submitted[:len(operator)]], operator) + self.assertEqual(len(submitted), len(blocks)) + self.assertEqual(requests, [submitted, submitted]) + for block in submitted[len(operator):]: + self.assertRegex(block["text"], r"^\[omitted u\d+ injected \d+B\]$") + self.assertNotIn("PRIVATE-HOOK", self.packed()) + self.assertNotIn("/home/decoy", (self.out / "review.md").read_text()) + + def restore(packed): + events = {line["event"]["sequence"]: line["event"]["data"] for line in packed if line["kind"] == "event"} + for copy in copies(events): + copy[len(operator)]["text"] = hook.replace("alice", "useru") + + findings = self.audit_of(restore, export) + for seq in (4, 6, 18): + self.assertTrue(any(f.startswith(f"content: main#{seq} ") for f in findings), findings) + + self.decide(keep=[self.unit_at(submitted[len(operator)]["text"])]) + pack.build(export, self.out) + for copy in copies(self.events()): + self.assertEqual(copy[len(operator)]["text"], hook.replace("alice", "useru")) + self.assertEqual(copy[len(operator) + 1:], submitted[len(operator) + 1:]) + manifest = json.loads((self.out / "pack" / "pack.json").read_text()) + self.assertEqual(manifest["level"], 2) + + def test_an_image_counts_as_the_first_operator_block(self) -> None: + lines = export_lines() + image = {"type": "image", "source": {"type": "base64", "mediaType": "image/png", "data": "IMAGE-BYTES"}} + hook = {"type": "text", "text": "PRIVATE-HOOK"} + lines[5]["event"]["data"]["user"]["content"] = [image, hook] + pack.build(self.write(lines), self.out) + first, second = self.events()[4]["user"]["content"] + self.assertEqual(first["type"], "image") + self.assertRegex(first["source"]["data"], r" attachment ") + self.assertRegex(second["text"], r" injected ") + self.assertNotIn("PRIVATE-HOOK", self.packed()) + + def test_one_original_has_one_stand_in_everywhere(self) -> None: + pack.build(self.export, self.out) + events = self.events() + call = events[12]["call"]["id"] + self.assertRegex(call, r"^call-\d+$") + self.assertEqual(events[11]["call_id"], call) + self.assertEqual(events[14]["content"][1]["id"], call) + self.assertEqual(events[16]["results"][0]["call_id"], call) + answered = events[18]["request"]["messages"] + self.assertEqual(answered[3]["content"][1]["id"], call) + self.assertEqual(answered[4]["content"][0]["tool_use_id"], call) + self.assertNotEqual(events[13]["call"]["id"], call) + self.assertEqual(answered[1]["content"], events[4]["user"]["content"][0]["text"], + "the question differs between the event and the request that carried it") + self.assertEqual(json.loads(self.packed().splitlines()[0])["session_id"], pack.SESSION) + + def test_the_pack_reads_as_the_export_it_came_from(self) -> None: + pack.build(self.export, self.out) + before = [json.loads(line) for line in self.export.read_text().splitlines()] + after = [json.loads(line) for line in self.packed().splitlines()] + self.assertEqual(len(before), len(after)) + for old, new in zip(before, after): + self.assertEqual(old["kind"], new["kind"]) + if old["kind"] == "event": + for field in ("id", "sequence", "create_at", "type", "name"): + self.assertEqual(old["event"][field], new["event"][field]) + self.assertEqual(old["batch_end"], new["batch_end"]) + self.assertTrue(after[0]["sensitive"], "a pack is still sensitive material") + self.assertEqual(after[-1], before[-1]) + + def test_deltas_have_the_fields_rust_writes(self) -> None: + source = Path(__file__).resolve().parents[2] / "crates" / "dim-agent-types" / "src" / "events.rs" + found = re.search(r"pub struct DeltaData \{(.*?)\n\}", source.read_text(), re.DOTALL) + self.assertIsNotNone(found, "DeltaData moved; point this test at its definition") + fields = set(re.findall(r"pub (\w+):", found.group(1))) + for line in export_lines(): + if line["kind"] == "event" and line["event"]["name"] in ("thinking", "text"): + self.assertEqual(set(line["event"]["data"]), fields, "the fixture's deltas are not DeltaData") + + def test_an_unlisted_field_of_a_delta_is_removed(self) -> None: + lines = export_lines() + at = next(i for i, line in enumerate(lines) + if line.get("event", {}).get("name") == "text") + lines[at]["event"]["data"]["annotation"] = "MARK-EXTRA-FIELD" + pack.build(self.write(lines, "extra-field.jsonl"), self.out) + events = self.events() + self.assertNotIn("annotation", events[19]) + self.assertEqual(events[19]["turn_id"], "turn-0001") + self.assertEqual(events[19]["request_id"], "request-0002") + self.assertNotIn("MARK-EXTRA-FIELD", self.packed()) + self.assertEqual("".join(events[i]["delta"] for i in (19, 20, 21, 22)), + events[23]["content"][0]["text"], "the stream lost its deltas") + + def test_a_text_field_cannot_become_an_unlisted_object(self) -> None: + lines = export_lines() + input_message = lines[5]["event"]["data"]["user"] + input_message["content"] = {"private": "MARK-OBJECT-CONTENT"} + export = self.write(lines, "object-in-text.jsonl") + with self.assertRaisesRegex(pack.Refused, "unexpected JSON type"): + pack.build(export, self.out) + self.assertTrue(export.exists(), "a rejected input must remain available") + self.assertFalse((self.out / "pack").exists()) + + def test_unknown_fields_never_enter_the_pack(self) -> None: + lines = export_lines() + lines[0]["private-header-key"] = True + lines[1]["info"]["private-branch-key"] = 197463 + lines[7]["event"]["private-event-key"] = {"number": 17} + model = lines[7]["event"]["data"]["request"] + model["capabilitySnapshot"]["reasoning"]["private-model-key"] = [True, 42] + pack.build(self.write(lines), self.out) + for key in ("private-header-key", "private-branch-key", "private-event-key", "private-model-key"): + self.assertNotIn(key, self.packed()) + unknown = next(line for line in lines if line.get("event", {}).get("type") == "acme") + self.assertEqual(self.events()[unknown["event"]["sequence"]], {}) + + def test_a_kept_trace_still_cannot_carry_provider_blobs(self) -> None: + lines = export_lines() + trace = lines[17]["trace"] + trace["original"]["parts"] = [ + {"protocol": protocol, "data": "PRIVATE-OPAQUE-PAYLOAD"} + for protocol in ("anthropic-redacted", "bedrock-redacted") + ] + [{"encrypted_content": "PRIVATE-ENCRYPTED-PAYLOAD"}] + export = self.write(lines) + pack.build(export, self.out) + first = [json.loads(line) for line in self.packed().splitlines()] + self.decide(keep=[self.unit_at(first[17]["trace"]["omitted"])]) + + for index, part in enumerate(trace["original"]["parts"]): + key = "data" if "protocol" in part else "encrypted_content" + with self.subTest(field=part.get("protocol", key)): + def restore_blob(packed): + packed[17]["trace"]["original"]["parts"][index][key] = part[key] + + found = self.audit_of(restore_blob, export) + self.assertTrue(any(f.startswith("opaque: main#16") for f in found), found) + self.assertNotIn(part[key], self.packed()) + self.assertNotIn(part[key], (self.out / "review.md").read_text(encoding="utf-8")) + self.assertIn("MARK-TRACE", self.packed(), "the trace unit was not actually kept") + + # ---- approvals, stops, compactions, delegations ---------------------------- + + def named(self) -> dict: + kinds = {"approval/request", "approval/respond", "approval/cancelled", "permission/changed", + "stop/interrupt", "context/compaction-start", "context/compaction", + "collaboration/request", "collaboration/result"} + found = {} + for line in self.packed().splitlines(): + record = json.loads(line) + event = record.get("event") or {} + key = f"{event.get('type')}/{event.get('name')}" + if record.get("kind") == "event" and key in kinds: + found[key] = event["data"] + return found + + def test_approvals_stops_and_delegations_answer_triage(self) -> None: + pack.build(self.write(boundary_export(), "boundary.jsonl"), self.out) + named = self.named() + self.assertEqual(named["approval/respond"]["decision"], "deny", "the decision was hidden") + self.assertEqual(named["approval/respond"]["approval_id"], "approval-1") + self.assertEqual(named["stop/interrupt"]["scope"], "turn", "the interrupt scope was hidden") + self.assertEqual(named["context/compaction-start"]["trigger"], "threshold") + self.assertEqual(named["context/compaction"]["status"], "completed", + "the compaction outcome was hidden") + self.assertEqual(named["collaboration/result"]["status"], "completed") + self.assertEqual(named["collaboration/result"]["agent_id"], "agent-1") + target = named["collaboration/request"]["target"] + self.assertEqual((target["kind"], target["agent_id"]), ("member", "agent-1")) + self.assertEqual(target["session_id"], named["collaboration/result"]["session_id"]) + self.assertNotIn("session-9", self.packed()) + self.assertEqual(named["approval/request"]["call"]["name"], "exec") + self.assertEqual(named["approval/request"]["source"]["call_id"], self.events()[12]["call"]["id"], + "the approval lost its call") + self.assertRegex(named["approval/request"]["reason"], pack.STUB, "the reason was kept unreviewed") + self.assertRegex(named["permission/changed"]["policy"]["omitted"], pack.STUB, + "the policy was kept unreviewed") + self.assertRegex(named["context/compaction"]["replacement"][0]["content"], pack.STUB, + "the compaction replacement was kept unreviewed") + self.assertRegex(named["collaboration/request"]["prompt"], pack.STUB, + "the delegation prompt was kept unreviewed") + for mark in ("MARK-APPROVAL", "MARK-APPROVAL-REASON", "MARK-CANCEL", "MARK-POLICY", "MARK-STOP", + "MARK-SUMMARY", "MARK-COLLAB", "MARK-COLLAB-RESULT", "MARK-TITLE"): + self.assertNotIn(mark, self.packed(), f"{mark} left the machine without being kept") + + def test_collaborators_keep_distinct_session_stand_ins_in_fields_and_text(self) -> None: + lines = boundary_export() + first = lines[-3]["event"]["data"]["target"]["session_id"] + second = "sid-b" + delivery = lines[-2] + event = delivery["event"] + lines.insert(-1, {**delivery, "batch_end": delivery["batch_end"] + 1, "event": { + **event, "id": "member-delivered", "sequence": event["sequence"] + 1, "name": "delivered", + "data": {"op_event_id": "member-request", "status": "ok", "agent_id": "agent-2", "session_id": second}}}) + lines[1]["head"] += 1 + lines[-1]["events"] += 1 + lines[5]["event"]["data"]["user"]["content"][0]["text"] = f"{first} / {second} / {SESSION}" + export = self.write(lines) + pack.build(export, self.out) + records = list(pack.read(self.out / "pack" / "timeline.jsonl")) + a = records[-4]["event"]["data"]["target"]["session_id"] + b = records[-2]["event"]["data"]["session_id"] + primary = records[0]["session_id"] + self.assertEqual(len({a, b, primary}), 3) + self.assertEqual(records[-3]["event"]["data"]["session_id"], a) + self.assertEqual(self.events()[4]["user"]["content"][0]["text"], f"{a} / {b} / {primary}") + for raw in (first, second, SESSION): + self.assertNotIn(raw, self.packed()) + self.assertNotIn(raw, (self.out / "pack" / "pack.json").read_text()) + for wrong in (first, b): + def misattribute(records): + records[-3]["event"]["data"]["session_id"] = wrong + self.assertTrue(any(f.startswith("identifier:") for f in self.audit_of(misattribute, export))) + + def test_the_roster_covers_every_core_event_kind(self) -> None: + source = Path(__file__).resolve().parents[2] / "crates" / "dim-agent-types" / "src" / "events.rs" + text = source.read_text() + block = re.search(r"RESERVED_DOMAINS: \[&str; \d+\] = \[(.*?)\];", text, re.DOTALL).group(1) + missing = [] + for domain in re.findall(r'"(\w+)"', block): + variant = re.search(r'"%s" => Self::(\w+)\(' % domain, text).group(1) + body = re.search(r"enum %sEvent \{(.*?)\n\}" % variant, text, re.DOTALL).group(1) + for name in re.findall(r'rename = "([^"]+)"', body): + if f"{domain}/{name}" not in pack.EVENTS: + missing.append(f"{domain}/{name}") + self.assertEqual(missing, [], "event kinds the source defines but the roster does not carry") + + def test_a_streamed_block_is_one_unit(self) -> None: + pack.build(self.export, self.out) + events = self.events() + self.assertEqual((events[8]["turn_id"], events[8]["request_id"]), ("turn-0001", "request-0001"), + "a delta's ids were taken for content") + self.assertRegex(events[8]["delta"], pack.STUB) + self.assertEqual([events[9]["delta"], events[10]["delta"]], ["", ""]) + self.assertEqual("".join(events[i]["delta"] for i in (19, 20, 21, 22)), events[23]["content"][0]["text"]) + + # ---- level two ------------------------------------------------------------ + + def test_a_named_unit_is_kept_wherever_it_occurs(self) -> None: + pack.build(self.export, self.out) + events = self.events() + result = self.unit_at(events[16]["results"][0]["result"]["content"]) + thought = self.unit_at(events[8]["delta"]) + self.decide(keep=[result, thought]) + pack.build(self.export, self.out) + events = self.events() + listing = "-rw-r--r-- 1 useru staff 12 MARK-RESULT notes.txt" + self.assertEqual(events[16]["results"][0]["result"]["content"], listing) + self.assertEqual(events[18]["request"]["messages"][4]["content"][0]["content"], listing) + thinking = events[14]["content"][0] + self.assertEqual("".join(events[i]["delta"] for i in (8, 9, 10)), thinking["thinking"]) + self.assertEqual(thinking["thinking"], "I should look at MARK-THINKING in /Users/useru/work first.") + self.assertEqual(thinking["signature"], pack.REMOVED, "keeping the thought kept the provider's blob") + self.assertEqual(events[18]["request"]["messages"][3]["content"][0]["thinking"], thinking["thinking"]) + packed = self.packed() + self.assertNotIn("alice", packed.lower()) + for mark in set(MARKS) - {"MARK-RESULT", "MARK-THINKING"}: + self.assertNotIn(mark, packed) + self.assertEqual(json.loads((self.out / "pack" / "pack.json").read_text())["level"], 2) + + def test_a_kept_subtree_has_its_identifiers_replaced(self) -> None: + pack.build(self.export, self.out) + arguments = self.unit_at(self.events()[12]["call"]["input"]["omitted"]) + self.decide(keep=[arguments]) + pack.build(self.export, self.out) + events = self.events() + self.assertEqual(events[12]["call"]["input"], {"command": "ls -l /Users/useru/work MARK-ARGS"}) + self.assertEqual(events[14]["content"][1]["input"], events[12]["call"]["input"]) + self.assertEqual(set(events[13]["call"]["input"]), {"omitted"}) + + def test_a_default_unit_can_be_left_out(self) -> None: + pack.build(self.export, self.out) + review = (self.out / "review.md").read_text() + question = next(line.split(":")[0].removeprefix("### ") for line in review.splitlines() + if line.startswith("### ") and "user-input" in line) + self.decide(omit=[question]) + pack.build(self.export, self.out) + self.assertRegex(self.events()[4]["user"]["content"][0]["text"], pack.STUB) + self.assertNotIn("wiki.internal", self.packed()) + + def test_the_submitters_own_terms_are_replaced(self) -> None: + self.decide(terms=["wiki.internal.example.net", "owners"]) + pack.build(self.export, self.out) + self.assertIn("See https://[term-1]/[term-2]", self.events()[4]["user"]["content"][0]["text"]) + + # ---- review and confirmation ---------------------------------------------- + + def test_the_review_shows_what_leaves_and_what_might_identify(self) -> None: + self.assertIsNone(pack.build(self.export, self.out)) + review = (self.out / "review.md").read_text() + self.assertIn("List /Users/useru/work and say who owns it.", review) + self.assertIn("| `/Users/alice` | `/Users/useru` |", review) + self.assertIn("- `wiki.internal.example.net`", review, "an unlisted host is a candidate, not a replacement") + self.assertIn("- `web_fetch`", review) + self.assertIn("pack/timeline.jsonl", review) + self.assertIn('"timeline_sha256"', review) + self.assertNotIn("MARK-RESULT", review, "the review printed content that was not kept") + self.assertIn("- `/Users/alice/.dimcode/output.txt`", review, "a file outside the export went unmentioned") + self.assertEqual(json.loads((self.out / "pack" / "pack.json").read_text())["files_not_packed"], 1) + + def test_a_folder_under_a_generic_home_is_suggested_not_automatically_replaced(self) -> None: + lines = export_lines(home="/home/ubuntu") + lines[5]["event"]["data"]["user"]["content"][0]["text"] = "Read /home/ubuntu/acme-customer/src" + export = self.write(lines) + pack.build(export, self.out) + self.assertIn("- `acme-customer`", (self.out / "review.md").read_text().splitlines()) + self.assertIn("/home/ubuntu/acme-customer/src", self.packed()) + self.decide(terms=["acme-customer"]) + pack.build(export, self.out) + self.assertNotIn("acme-customer", self.packed()) + self.assertIn("/home/ubuntu/[term-1]/src", self.packed()) + + def test_confirming_binds_the_digest_that_was_read(self) -> None: + consent = {"diagnosis": True, "regression": True, "providers": ["test"], "expires": date.max.isoformat()} + self.decide(consent=consent) + digest = pack.build(self.export, self.out) + result = self.unit_at(self.events()[16]["results"][0]["result"]["content"]) + for changes in ({"consent": {**consent, "providers": ["other"]}}, {"keep": [result]}, + {"pack_id": "0000000000000000"}): + with self.subTest(changes=changes): + self.decide(consent=consent, keep=[], pack_id="feedfacefeedface") + self.decide(**changes) + with self.assertRaisesRegex(pack.Refused, "confirm"): + pack.build(self.export, self.out, confirm=digest) + self.assertFalse((self.out / "pack").exists()) + + def test_a_second_build_cannot_replace_a_pack_being_confirmed(self) -> None: + self.decide(consent={"diagnosis": True, "regression": False, + "providers": [], "expires": date.max.isoformat()}) + digest = pack.build(self.export, self.out) + other = self.write(export_lines(turn="another-turn"), "other.jsonl") + entered, resume = Event(), Event() + write = pack.private + + def pause_at_manifest(path, body): + if path.name == "pack.json": + entered.set() + if not resume.wait(5): + raise TimeoutError("test did not resume the first build") + write(path, body) + + with patch.object(pack, "private", side_effect=pause_at_manifest), ThreadPoolExecutor(1) as runner: + first = runner.submit(pack.build, self.export, self.out, None, digest) + try: + self.assertTrue(entered.wait(5), "first build never reached the manifest write") + with self.assertRaisesRegex(pack.Refused, "another build owns"): + pack.build(other, self.out) + finally: + resume.set() + self.assertEqual(first.result(), digest) + final = self.out / "pack" + manifest = json.loads((final / "pack.json").read_bytes()) + self.assertEqual(manifest["timeline_sha256"], hashlib.sha256((final / "timeline.jsonl").read_bytes()).hexdigest()) + self.assertNotIn("another-turn", self.packed()) + self.assertFalse((self.out / ".pack.lock").exists()) + + def test_changing_replacements_requires_a_full_review_again(self) -> None: + self.decide(terms=["owners"], consent={"diagnosis": True, "regression": False, + "providers": [], "expires": date.max.isoformat()}) + digest = pack.build(self.export, self.out) + self.assertNotIn("/owners", self.packed()) + self.decide(terms=[]) + with self.assertRaisesRegex(pack.Refused, "confirm"): + pack.build(self.export, self.out, confirm=digest) + pack.build(self.export, self.out) + review = (self.out / "review.md").read_text() + self.assertIn("/owners", review) + self.assertIn("Read every unit on each pass", review) + + def test_a_confirmed_pack_carries_its_consent(self) -> None: + consent = {"diagnosis": True, "regression": False, "providers": [], "expires": date.max.isoformat()} + self.decide(consent={**consent, "given": "2000-01-01", "submitter": "PRIVATE-IDENTITY"}) + digest = pack.build(self.export, self.out) + manifest_path = self.out / "pack" / "pack.json" + self.assertNotIn("consent", json.loads(manifest_path.read_text()), + "an unconfirmed pack claims an authorization") + review = (self.out / "review.md").read_text() + self.assertIn(f"--confirm {digest}", review) + pack.build(self.export, self.out, confirm=digest) + manifest = json.loads(manifest_path.read_text()) + self.assertEqual(manifest["consent"], {**consent, "given": date.today().isoformat()}) + self.assertEqual(manifest["timeline_sha256"], hashlib.sha256(manifest_path.with_name("timeline.jsonl").read_bytes()).hexdigest()) + self.assertEqual(digest, hashlib.sha256(manifest_path.read_bytes()).hexdigest()) + self.assertIn(manifest_path.read_text().rstrip("\n"), review) + pack.build(self.export, self.out) + self.assertNotIn("consent", json.loads(manifest_path.read_text()), + "a preview inherited an earlier confirmation") + + def test_consent_can_be_confirmed_on_its_expiry_date_but_not_the_next_day(self) -> None: + expiry = date(2026, 11, 18) + self.decide(consent={"diagnosis": True, "regression": False, + "providers": [], "expires": expiry.isoformat()}) + with patch.object(pack, "date", wraps=date) as clock: + clock.today.return_value = expiry + digest = pack.build(self.export, self.out) + self.assertEqual(pack.build(self.export, self.out, confirm=digest), digest) + manifest = json.loads((self.out / "pack" / "pack.json").read_text()) + self.assertEqual(manifest["consent"]["given"], expiry.isoformat()) + clock.today.return_value = expiry + timedelta(days=1) + with self.assertRaisesRegex(pack.Refused, "^consent: .*already passed"): + pack.build(self.export, self.out, confirm=digest) + self.assertFalse((self.out / "pack").exists()) + self.assertFalse((self.out / "pack.tmp").exists()) + + def test_invalid_consent_does_not_leave_a_pack(self) -> None: + valid = {"diagnosis": True, "regression": True, "providers": ["test"], "expires": date.max.isoformat()} + for label, consent in ( + ("missing", None), + ("non-boolean diagnosis", {**valid, "diagnosis": "true"}), + ("no regression providers", {**valid, "providers": []}), + ("provider is not an ID", {**valid, "providers": [42]}), + ("provider has free text", {**valid, "providers": ["private customer name"]}), + ("credential in providers", {**valid, "providers": ["sk-" + "x" * 24]}), + ("missing expiry", {k: v for k, v in valid.items() if k != "expires"}), + ("wrong date format", {**valid, "expires": "16-05-2027"}), + ("impossible date", {**valid, "expires": "2027-02-30"}), + ): + with self.subTest(label=label): + self.decide(consent=valid) + digest = pack.build(self.export, self.out) + self.decide(consent=consent) + with self.assertRaisesRegex(pack.Refused, "^consent:"): + pack.build(self.export, self.out, confirm=digest) + self.refused("^consent:") + + def test_the_same_input_gives_the_same_bytes(self) -> None: + self.decide() + pack.build(self.export, self.out) + first = {p.name: p.read_bytes() for p in (self.out / "pack").iterdir()} + other = self.root / "again" + other.mkdir() + shutil.copy(self.out / "decisions.json", other / "decisions.json") + pack.build(self.export, other) + self.assertEqual(first, {p.name: p.read_bytes() for p in (other / "pack").iterdir()}) + + # ---- account names -------------------------------------------------------- + + def test_a_short_account_name_does_not_rewrite_the_conversation(self) -> None: + export = self.write(export_lines(home="/Users/me"), "short.jsonl") + pack.build(export, self.out) + question = self.events()[4]["user"]["content"][0]["text"] + self.assertTrue(question.startswith("List /Users/us/work and say who owns it."), question) + self.assertIn("- `me`", (self.out / "review.md").read_text()) + + def test_a_short_windows_account_is_removed_from_both_separator_styles(self) -> None: + lines = export_lines() + home = r"C:\Users\xy" + lines[4]["event"]["data"]["blocks"][0]["text"] = f"{home}" + paths = (home, "c:/users/XY", json.dumps(home)[1:-1], urllib.parse.quote(home, safe="")) + lines[5]["event"]["data"]["user"]["content"][0]["text"] = " | ".join(paths) + pack.build(self.write(lines, "windows.jsonl"), self.out) + text = self.events()[4]["user"]["content"][0]["text"] + for path in paths: + self.assertNotIn(path.lower(), text.lower()) + self.assertIn(r"C:\Users\us", text) + self.assertIn("C:/Users/us", text) + + def test_case_folded_reserved_path_cannot_delete_the_export(self) -> None: + self.out.mkdir() + actual = self.out / "pack" / "local-input.jsonl" + actual.parent.mkdir() + actual.write_text(self.export.read_text(encoding="utf-8"), encoding="utf-8") + alias = self.out / "PACK" / "local-input.jsonl" + with self.assertRaisesRegex(pack.Refused, "generated files"): + pack.build(alias, self.out) + self.assertTrue(actual.exists(), "input inside a reserved path was deleted") + + def test_input_overlap_is_checked_after_resolving_directory_links(self) -> None: + child = self.root / "child" + child.mkdir() + alias = self.root / "aliases" / "child" + alias.parent.mkdir() + alias.symlink_to(child, target_is_directory=True) + decisions = alias / ".." / self.export.name + self.assertTrue(decisions.samefile(self.export)) + before = self.export.read_bytes() + with self.assertRaisesRegex(pack.Refused, "separate from each other"): + pack.build(self.export, self.out, decisions) + self.assertEqual(self.export.read_bytes(), before) + self.assertFalse(self.out.exists()) + + def test_an_account_everyone_has_is_left_alone(self) -> None: + export = self.write(export_lines(home="/home/ubuntu"), "generic.jsonl") + pack.build(export, self.out) + self.assertIn("It is owned by ubuntu (", self.events()[23]["content"][0]["text"]) + + # ---- a name cut across deltas ---------------------------------------------- + + def streamed(self) -> list[str]: + lines = [json.loads(line) for line in self.packed().splitlines()] + return [line["event"]["data"]["delta"] for line in lines + if line["kind"] == "event" and line["event"]["name"] == "text"] + + def test_a_name_cut_across_deltas_is_replaced(self) -> None: + for interrupt in (False, True): + with self.subTest(interrupt=interrupt): + pack.build(self.write(split_export(interrupt), "split.jsonl"), self.out) + deltas = self.streamed() + self.assertEqual(len(deltas), len(SPLIT), "the pack has a different number of deltas") + self.assertEqual("".join(deltas), "我看完了 /Users/useruseru/Desktop 的文件,useruseru 说先别动") + for delta in deltas: + self.assertNotIn("jin", delta, "half of the name survived in one delta") + self.assertNotIn("yaxuan", delta, "half of the name survived in one delta") + + def test_halves_of_a_name_put_back_are_found(self) -> None: + def change(lines): + deltas = [line for line in lines if line["kind"] == "event" and line["event"]["name"] == "text"] + for line, part in zip(deltas, SPLIT): + line["event"]["data"]["delta"] = part + found = self.audit_of(change, self.write(split_export(True), "split.jsonl")) + self.assertTrue(any(f.startswith("content: the stream starting at") for f in found), found) + self.assertTrue(any(f.startswith("replacement: the stream starting at") for f in found), found) + + # ---- several branches ------------------------------------------------------- + + def test_level_one_keeps_the_dialogue_when_a_child_branch_comes_first(self) -> None: + pack.build(self.write(branched_export(), "branched.jsonl"), self.out) + lines = [json.loads(line) for line in self.packed().splitlines()] + self.assertEqual(lines[1]["info"]["id"], CHILD, "the fixture no longer puts the child first") + main = {line["event"]["sequence"]: line["event"]["data"] for line in lines + if line["kind"] == "event" and line["branch_id"] == "main"} + child = {line["event"]["sequence"]: line["event"]["data"] for line in lines + if line["kind"] == "event" and line["branch_id"] == CHILD} + question = main[4]["user"]["content"][0]["text"] + reply = main[23]["content"][0]["text"] + self.assertTrue(question.startswith("List /Users/useru/work"), "main's question became `other`") + self.assertTrue(reply.startswith("It is owned by useru"), "main's reply became `other`") + inherited = child[5]["request"]["messages"] + self.assertEqual(inherited[1]["content"], question) + self.assertEqual(inherited[2]["content"][0]["text"], reply) + self.assertEqual(child[3]["user"]["content"][0]["text"], "Now do the same for /Users/useru/play.") + self.assertEqual(child[7]["content"][0]["text"], "Done: /Users/useru/play is owned by useru too.") + self.assertRegex(inherited[0]["content"][0]["text"], pack.STUB, "the environment block was kept") + review = (self.out / "review.md").read_text() + self.assertNotIn("other, first", review, "a dialogue unit was reviewed as `other`") + self.assertIn("user-input, first at main#4", review, "the kind points at the request, not the event") + + def test_home_comes_from_dims_environment_block_only(self) -> None: + pack.build(self.write(branched_export(), "branched.jsonl"), self.out) + self.assertNotIn("alice", self.packed().lower()) + review = (self.out / "review.md").read_text() + self.assertIn("| `/Users/alice` | `/Users/useru` |", review) + self.assertNotIn("fixture", review.split("## 3.")[0], "a quoted home tag was taken for the home") + + def test_xml_escaped_home_is_replaced_in_both_forms(self) -> None: + home = "/Users/R&DTeam" + lines = export_lines(home=home) + escaped = home.replace("&", "&") + environment = lines[4]["event"]["data"]["blocks"][0] + environment["text"] = environment["text"].replace(home, escaped) + for index in (7, 19): + lines[index]["event"]["data"]["request"]["messages"][0]["content"][0]["text"] = environment["text"] + export = self.write(lines) + pack.build(export, self.out) + self.assertNotIn("R&DTeam", self.packed()) + self.assertNotIn("R&DTeam", self.packed()) + self.decide(keep=[self.unit_at(self.events()[3]["blocks"][0]["text"])]) + pack.build(export, self.out) + self.assertIn("/Users/useruse", self.events()[3]["blocks"][0]["text"]) + self.assertNotIn("R&DTeam", self.packed()) + self.assertNotIn("R&DTeam", self.packed()) + + def test_the_order_of_branches_does_not_change_what_is_kept(self) -> None: + manifests = [] + for name, main_first in (("child-first.jsonl", False), ("main-first.jsonl", True)): + out = self.root / name.removesuffix(".jsonl") + pack.build(self.write(branched_export(main_first), name), out) + manifests.append(json.loads((out / "pack" / "pack.json").read_text())) + self.assertEqual(manifests[0]["units"], manifests[1]["units"]) + self.assertEqual(manifests[0]["models"], ["test/model-1"]) + + # ---- refusals --------------------------------------------------------------- + + def refused(self, pattern, export=None) -> None: + with self.assertRaisesRegex(pack.Refused, pattern): + pack.build(export or self.export, self.out) + self.assert_no_output() + + def assert_no_output(self) -> None: + for name in ("pack", "pack.tmp", "review.md", ".pack.lock"): + self.assertFalse((self.out / name).exists(), f"a failed run left {name} behind") + + def test_a_non_object_timeline_line_is_refused(self) -> None: + pack.build(self.export, self.out) + lines = export_lines() + lines.insert(2, ["not a Timeline record"]) + self.refused("each Timeline line must be a JSON object", self.write(lines)) + + def test_a_term_in_manifest_consent_is_refused(self) -> None: + self.decide(terms=["private-customer"], consent={"diagnosis": False, "regression": True, + "providers": ["private-customer"], "expires": date.max.isoformat()}) + self.refused("^manifest: .* identifier marked for replacement") + + def test_invalid_pack_id_is_refused(self) -> None: + pack.build(self.export, self.out) + self.decide(pack_id="private-customer") + self.refused("^decisions: `pack_id`") + + def test_write_failure_leaves_no_pack_or_review(self) -> None: + pack.build(self.export, self.out) + decisions = self.out / "decisions.json" + original = decisions.read_bytes() + replace = Path.replace + + def fail_to_save(path, target): + if target == decisions: + raise OSError("injected decisions write failure") + return replace(path, target) + + with patch.object(Path, "replace", fail_to_save): + with self.assertRaisesRegex(OSError, "injected decisions write failure"): + pack.build(self.export, self.out) + self.assert_no_output() + self.assertEqual(decisions.read_bytes(), original) + self.assertEqual(list(self.out.iterdir()), [decisions]) + + def test_an_incomplete_export_is_refused(self) -> None: + pack.build(self.export, self.out) + self.refused("incomplete", self.write(export_lines(end=False), "cut.jsonl")) + lines = export_lines() + lines[-1]["events"] += 1 + self.refused("incomplete", self.write(lines, "miscounted.jsonl")) + + def test_an_unknown_unit_is_refused(self) -> None: + self.decide(keep=["u9999"]) + self.refused("no unit is named u9999") + + def test_a_term_that_survives_in_structure_is_refused(self) -> None: + self.decide(terms=["main"]) + self.refused("replacement: main#") + + def test_a_credential_outside_content_is_refused(self) -> None: + self.refused("secret: main#5", self.write(export_lines(turn="sk-" + "a" * 24), "secret.jsonl")) + + def test_a_credential_in_kept_content_is_replaced(self) -> None: + lines = export_lines() + token = "ghp_" + "b" * 36 + lines[5]["event"]["data"]["user"]["content"][0]["text"] += f" token {token}" + lines[7]["event"]["data"]["request"]["messages"][1]["content"] += f" token {token}" + pack.build(self.write(lines, "token.jsonl"), self.out) + self.assertTrue(self.events()[4]["user"]["content"][0]["text"].endswith(" token [secret-1]")) + self.assertNotIn(token, self.packed()) + + def audit_of(self, change, export=None) -> list[str]: + """What the checks say about a pack that `change` edited after it was written.""" + export = export or self.export + pack.build(export, self.out) + with pack.prepare(export, pack.load_decisions(self.out / "decisions.json")) as (scan, replacements): + lines = [json.loads(line) for line in self.packed().splitlines()] + change(lines) + return pack.audit(export, self.write(lines, "edited.jsonl"), scan, replacements) + + def test_the_written_pack_passes_its_own_checks(self) -> None: + self.assertEqual(self.audit_of(lambda lines: None), []) + + def test_content_put_back_is_found(self) -> None: + def change(lines): + lines[17]["event"]["data"]["results"][0]["result"]["content"] = "something that was never reviewed" + self.assertTrue(any(f.startswith("content: main#16") for f in self.audit_of(change))) + + def test_a_provider_blob_put_back_is_found(self) -> None: + def change(lines): + lines[15]["event"]["data"]["content"][0]["signature"] = "opaque bytes" + self.assertTrue(any(f.startswith("opaque: main#14") for f in self.audit_of(change))) + + def test_a_provider_identifier_put_back_is_found(self) -> None: + def change(lines): + lines[13]["event"]["data"]["call"]["id"] = "call_from_the_provider" + self.assertTrue(any(f.startswith("identifier: main#12") for f in self.audit_of(change))) + + def test_a_changed_line_is_found(self) -> None: + def reorder(lines): + lines[6]["event"]["sequence"] = 99 + + def drop(lines): + del lines[6] + self.assertTrue(any(f.startswith("structure: main#5") for f in self.audit_of(reorder))) + self.assertTrue(any(f.startswith("structure:") for f in self.audit_of(drop))) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/dim-cli/src/report.rs b/crates/dim-cli/src/report.rs index 9e2de72981..1232123214 100644 --- a/crates/dim-cli/src/report.rs +++ b/crates/dim-cli/src/report.rs @@ -1,7 +1,9 @@ +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_types::{BranchCreateFailedData, ModelId, ModelOutputOutcome}; use jiff::Timestamp; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use crate::wire::{Event, EventContent}; @@ -75,6 +77,7 @@ pub enum Action { Plan { draft: Draft, redact: bool, + include_conversation: bool, instructions: String, }, Generate(Draft), @@ -117,16 +120,52 @@ pub struct Plan { pub plan_id: String, pub evidence: Evidence, pub instructions_status: String, + pub files: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ReportFiles { + #[serde(rename = "report.md")] + pub report: String, + #[serde(rename = "diagnostics.json")] + pub diagnostics: String, +} + +impl ReportFiles { + pub fn preview(&self) -> String { + let mut text = String::new(); + for (name, content) in [ + ("report.md", &self.report), + ("diagnostics.json", &self.diagnostics), + ] { + text.push_str(&format!("--- {name} ---\n")); + for ch in content.chars() { + if ch != '\n' + && (ch.is_control() + || matches!(ch, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) + { + text.extend(ch.escape_debug()); + } else { + text.push(ch); + } + } + text.push_str("\n\n"); + } + text + } +} + +#[derive(Deserialize, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] -enum LocalGeneration { +pub(crate) enum LocalGeneration { Local, } #[derive(Deserialize)] pub struct Evidence { + #[serde(default)] + pub conversation: Vec, pub timeline: Option, pub unavailable: Option, } @@ -149,10 +188,74 @@ pub enum EvidenceUnavailable { #[derive(Deserialize)] pub struct GeneratedReport { pub title: String, + pub files: Option, pub archive: Archive, pub sharing: Sharing, } +impl GeneratedReport { + pub fn zip_bytes(&self) -> crate::Result> { + const LIMIT: usize = 64 * 1024; + if self.archive.base64.len() > LIMIT.div_ceil(3) * 4 { + return Err(crate::ui::i18n::t("Invalid report ZIP").into()); + } + let bytes = STANDARD.decode(&self.archive.base64)?; + if bytes.len() > LIMIT || !bytes.starts_with(b"PK\x03\x04") { + return Err(crate::ui::i18n::t("Invalid report ZIP").into()); + } + Ok(bytes) + } +} + +pub const EMAIL: &str = "feedback@arcships.ai"; +pub const EMAIL_SUBJECT: &str = "Dim report"; + +#[derive(Clone, Copy, Default)] +pub enum MailScope { + #[default] + ReportOnly, + InternalRegression, +} + +impl MailScope { + fn purpose(self) -> &'static str { + match self { + Self::ReportOnly => "Issue investigation only; no evaluation authorization.", + Self::InternalRegression => { + "Issue investigation and team-internal regression evaluation of this ZIP only. No external model providers, training, or publication." + } + } + } + + pub fn body(self, bytes: &[u8]) -> String { + format!( + "Purpose: {}\r\nSHA-256: {:x}", + self.purpose(), + Sha256::digest(bytes) + ) + } +} + +pub fn mailto(body: &str) -> String { + fn encode(text: &str) -> String { + use std::fmt::Write as _; + let mut encoded = String::new(); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + encoded.push(char::from(byte)); + } else { + write!(encoded, "%{byte:02X}").expect("writing to a string"); + } + } + encoded + } + format!( + "mailto:{EMAIL}?subject={}&body={}", + encode(EMAIL_SUBJECT), + encode(body) + ) +} + #[derive(Deserialize)] pub struct Archive { pub base64: String, diff --git a/crates/dim-cli/src/session_host/report.rs b/crates/dim-cli/src/session_host/report.rs index c9cd79a62d..573c0187d8 100644 --- a/crates/dim-cli/src/session_host/report.rs +++ b/crates/dim-cli/src/session_host/report.rs @@ -1,8 +1,22 @@ use super::Worker; use crate::model::session::Update; -use crate::report::{Action, Captured, Draft, Reply, Request, Target, session_admission_failed}; +use crate::report::{ + Action, Captured, Draft, LocalGeneration, Reply, Request, Target, session_admission_failed, +}; +use serde::Serialize; use serde_json::{Value, json}; +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct PlanParams<'a> { + report_id: &'a str, + generation: LocalGeneration, + redact: bool, + #[serde(skip_serializing_if = "Option::is_none")] + include_conversation: Option, + instructions: &'a str, +} + impl Worker { pub(super) fn report_available(&self) -> bool { self.client.offers("report.prepare") || self.methods.contains("session.report.prepare") @@ -23,17 +37,25 @@ impl Worker { Action::Plan { draft, redact, + include_conversation, instructions, } => { - let (method, params) = report_call( - &draft, - "plan", - json!({ - "reportId": draft.report_id, "generation": {"kind":"local"}, - "redact": redact, "instructions": instructions, - }), - ); - self.client.typed(&method, params).await.map(Reply::Plan) + let params = PlanParams { + report_id: &draft.report_id, + generation: LocalGeneration::Local, + redact, + include_conversation: (include_conversation + || (!redact && draft.session.is_some())) + .then_some(include_conversation), + instructions: &instructions, + }; + match serde_json::to_value(params) { + Ok(params) => { + let (method, params) = report_call(&draft, "plan", params); + self.client.typed(&method, params).await.map(Reply::Plan) + } + Err(error) => Err(error.into()), + } } Action::Generate(draft) => { let (method, params) = report_call( @@ -196,6 +218,34 @@ mod tests { ) .await; assert_eq!(params, json!({"sessionId":"shown"})); + let plan = json!({"result":{ + "planId":"p2", "generation":{"kind":"local"}, + "evidence":{"timeline":{"recent":[]}}, "instructionsStatus":"none" + }}); + for (method, redact, flag) in [ + ("session.report.plan", true, None), + ("session.report.plan", false, Some(false)), + ("session.report.plan", true, Some(true)), + ("report.plan", false, None), + ] { + let result = if flag == Some(false) { + json!({"error":{"code":-32602,"message":"unknown field includeConversation"}}) + } else { + plan.clone() + }; + let params = exchange(method, result).await; + let mut expected = json!({ + "reportId":"r1", "generation":{"kind":"local"}, + "redact":redact, "instructions":"" + }); + if method == "session.report.plan" { + expected["sessionId"] = json!("shown"); + } + if let Some(flag) = flag { + expected["includeConversation"] = json!(flag); + } + assert_eq!(params, expected); + } // A classified refusal, the shape `session.attach` answers with // for a branch that still needs the explicit prompt migration // (recovery.rs): a producer's message under its own code. @@ -288,6 +338,36 @@ mod tests { assert!( matches!(receiver.try_recv().unwrap(), Update::ReportReply { panel: 2, reply: Reply::Prepared(Some(session), _) } if session == "shown") ); + for (session, redact, include_conversation) in [ + (Some("shown"), true, false), + (Some("shown"), false, false), + (Some("shown"), true, true), + (None, false, false), + ] { + worker + .report_request(Request { + panel: 2, + action: Action::Plan { + draft: Draft { + session: session.map(String::from), + report_id: "r1".into(), + plan_id: "p1".into(), + }, + redact, + include_conversation, + instructions: String::new(), + }, + }) + .await; + let Update::ReportReply { panel: 2, reply } = receiver.try_recv().unwrap() else { + panic!("expected report plan reply"); + }; + if session.is_some() && !redact && !include_conversation { + assert!(matches!(reply, Reply::Failed { .. })); + } else { + assert!(matches!(reply, Reply::Plan(plan) if plan.plan_id == "p2")); + } + } // The classified refusal does not route into the report flow: the // report's fallback is for an unclassified internal fault, and a // message the user can act on is not that. It reaches the caller with diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index e5e8df9abb..8f89cb8bcb 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -804,6 +804,67 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "Läuft…", "Save ZIP" => "ZIP speichern", "Saved ZIP" => "ZIP gespeichert", + "Diagnostics only; no conversation." => "Nur Diagnosedaten; kein Gespräch.", + "No conversation excerpts in this plan." => "Dieser Plan enthält keine Gesprächsauszüge.", + "Conversation included; redaction does not remove all sensitive text." => { + "Gespräch einbezogen; Schwärzen entfernt nicht den gesamten sensiblen Text." + } + "Conversation included without redaction." => "Gespräch ohne Schwärzung einbezogen.", + "Conversation requested; check the updated preview." => { + "Gespräch angefordert; prüfe die aktualisierte Vorschau." + } + "Report plan included conversation without permission." => { + "Der Berichtsplan enthielt ein Gespräch ohne Berechtigung." + } + "[ ] Include conversation" => "[ ] Gespräch einbeziehen", + "[x] Include conversation" => "[x] Gespräch einbeziehen", + "Check the preview for sensitive text before sharing." => { + "Prüfe vor dem Teilen die Vorschau auf sensiblen Text." + } + "Preview ZIP files" => "ZIP-Dateien anzeigen", + "Preview pending" => "Vorschau wird vorbereitet", + "Preview unavailable" => "Vorschau nicht verfügbar", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn scrollen · Esc zurück", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn Details · ↑↓ bewegen · Enter auswählen · Esc schließen" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "Erzeugte Dateien weichen von der Planvorschau ab. E-Mail ist nicht verfügbar." + } + "Email unavailable without matching plan and ZIP previews." => { + "E-Mail ist ohne übereinstimmende Plan- und ZIP-Vorschauen nicht verfügbar." + } + "(o) Investigation only" => "(o) Nur zur Fehlersuche", + "( ) Investigation only" => "( ) Nur zur Fehlersuche", + "(o) Team-internal regression of this ZIP only" => { + "(o) Nur teaminterne Regression dieses ZIPs" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Nur teaminterne Regression dieses ZIPs" + } + "Local attachment preview" => "Lokale Anhangsvorschau", + "Email is for investigating this report only, not evaluation." => { + "E-Mail dient nur der Untersuchung dieses Berichts, nicht der Evaluierung." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Nur teaminterne Regression dieses ZIPs. Keine externen Anbieter, kein Training, keine Veröffentlichung." + } + "Open email draft" => "E-Mail-Entwurf öffnen", + "Email details" => "E-Mail-Angaben", + "To: {email}" => "An: {email}", + "Subject: {subject}" => "Betreff: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Hänge das gespeicherte ZIP manuell an. Wenn kein Entwurf geöffnet wird, nutze diese Angaben. Es wurde nichts gesendet." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "E-Mail konnte nicht geöffnet werden. Verfasse die Nachricht manuell und hänge das gespeicherte ZIP an." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Verfasse die Nachricht manuell und hänge das gespeicherte ZIP an. Es wurde nichts gesendet." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "Gespeichertes ZIP fehlt, ist nicht lesbar oder wurde geändert. Speichere eine neue Kopie." + } "Session model" => "Sitzungsmodell", "Skills instructions" => "Skills-Anweisungen", "Some options were unsupported." => "Einige Optionen werden nicht unterstützt.", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index b4ceda7854..b503ad0e3b 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -808,6 +808,69 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "En curso…", "Save ZIP" => "Guardar ZIP", "Saved ZIP" => "ZIP guardado", + "Diagnostics only; no conversation." => "Solo diagnóstico; sin conversación.", + "No conversation excerpts in this plan." => { + "Este plan no incluye fragmentos de conversación." + } + "Conversation included; redaction does not remove all sensitive text." => { + "Conversación incluida; Ocultar no elimina todo el texto sensible." + } + "Conversation included without redaction." => "Conversación incluida sin Ocultar.", + "Conversation requested; check the updated preview." => { + "Conversación solicitada; revisa la vista previa actualizada." + } + "Report plan included conversation without permission." => { + "El plan del informe incluyó conversación sin permiso." + } + "[ ] Include conversation" => "[ ] Incluir conversación", + "[x] Include conversation" => "[x] Incluir conversación", + "Check the preview for sensitive text before sharing." => { + "Revisa la vista previa en busca de texto sensible antes de compartir." + } + "Preview ZIP files" => "Previsualizar archivos del ZIP", + "Preview pending" => "Vista previa pendiente", + "Preview unavailable" => "Vista previa no disponible", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn desplazar · Esc volver", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn detalles · ↑↓ mover · Enter seleccionar · Esc cerrar" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "Los archivos generados difieren de la vista previa del plan. El correo no está disponible." + } + "Email unavailable without matching plan and ZIP previews." => { + "El correo no está disponible sin vistas previas coincidentes del plan y del ZIP." + } + "(o) Investigation only" => "(o) Solo investigación", + "( ) Investigation only" => "( ) Solo investigación", + "(o) Team-internal regression of this ZIP only" => { + "(o) Solo regresión interna del equipo de este ZIP" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Solo regresión interna del equipo de este ZIP" + } + "Local attachment preview" => "Vista previa del archivo adjunto local", + "Email is for investigating this report only, not evaluation." => { + "El correo es solo para investigar este informe, no para evaluación." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Solo regresión interna del equipo de este ZIP. Sin proveedores externos, entrenamiento ni publicación." + } + "Open email draft" => "Abrir borrador de correo", + "Email details" => "Datos del correo", + "To: {email}" => "Para: {email}", + "Subject: {subject}" => "Asunto: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Adjunta el ZIP guardado manualmente. Si no se abre un borrador, usa estos datos. No se envió nada." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "No se pudo abrir el correo. Redacta el mensaje manualmente y adjunta el ZIP guardado." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Redacta el mensaje manualmente y adjunta el ZIP guardado. No se envió nada." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "El ZIP guardado falta, no se puede leer o ha cambiado. Guarda una copia nueva." + } "Session model" => "Modelo de la sesión", "Skills instructions" => "Instrucciones de skills", "Some options were unsupported." => "Algunas opciones no son compatibles.", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index 6a94c257f1..023f501803 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -798,6 +798,67 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "En cours…", "Save ZIP" => "Enregistrer le ZIP", "Saved ZIP" => "ZIP enregistré", + "Diagnostics only; no conversation." => "Diagnostic uniquement ; aucune conversation.", + "No conversation excerpts in this plan." => "Aucun extrait de conversation dans ce plan.", + "Conversation included; redaction does not remove all sensitive text." => { + "Conversation incluse ; le masquage ne supprime pas tout le texte sensible." + } + "Conversation included without redaction." => "Conversation incluse sans masquage.", + "Conversation requested; check the updated preview." => { + "Conversation demandée ; vérifiez l'aperçu mis à jour." + } + "Report plan included conversation without permission." => { + "Le plan du rapport a inclus une conversation sans autorisation." + } + "[ ] Include conversation" => "[ ] Inclure la conversation", + "[x] Include conversation" => "[x] Inclure la conversation", + "Check the preview for sensitive text before sharing." => { + "Vérifiez l'aperçu avant de partager afin de repérer tout texte sensible." + } + "Preview ZIP files" => "Prévisualiser les fichiers ZIP", + "Preview pending" => "Aperçu en attente", + "Preview unavailable" => "Aperçu indisponible", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn défiler · Esc revenir", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn détails · ↑↓ déplacer · Enter sélectionner · Esc fermer" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "Les fichiers générés diffèrent de l'aperçu du plan. L'e-mail n'est pas disponible." + } + "Email unavailable without matching plan and ZIP previews." => { + "L'e-mail n'est pas disponible sans aperçus concordants du plan et du ZIP." + } + "(o) Investigation only" => "(o) Enquête uniquement", + "( ) Investigation only" => "( ) Enquête uniquement", + "(o) Team-internal regression of this ZIP only" => { + "(o) Régression interne de l'équipe pour ce ZIP uniquement" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Régression interne de l'équipe pour ce ZIP uniquement" + } + "Local attachment preview" => "Aperçu de la pièce jointe locale", + "Email is for investigating this report only, not evaluation." => { + "L'e-mail sert uniquement à enquêter sur ce rapport, pas à l'évaluation." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Régression interne de l'équipe pour ce ZIP uniquement. Aucun fournisseur externe, entraînement ni publication." + } + "Open email draft" => "Ouvrir le brouillon d'e-mail", + "Email details" => "Détails de l'e-mail", + "To: {email}" => "À : {email}", + "Subject: {subject}" => "Objet : {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Joignez le ZIP enregistré manuellement. Si aucun brouillon ne s'ouvre, utilisez ces détails. Rien n'a été envoyé." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "Impossible d'ouvrir l'e-mail. Rédigez le message manuellement et joignez le ZIP enregistré." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Rédigez le message manuellement et joignez le ZIP enregistré. Rien n'a été envoyé." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "Le ZIP enregistré est absent, illisible ou a changé. Enregistrez une nouvelle copie." + } "Session model" => "Modèle de session", "Skills instructions" => "Instructions des skills", "Some options were unsupported." => "Certaines options ne sont pas prises en charge.", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 19b455aa0c..7bee7fc764 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -784,6 +784,69 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "Berjalan…", "Save ZIP" => "Simpan ZIP", "Saved ZIP" => "ZIP tersimpan", + "Diagnostics only; no conversation." => "Hanya diagnostik; tanpa percakapan.", + "No conversation excerpts in this plan." => { + "Tidak ada kutipan percakapan dalam rencana ini." + } + "Conversation included; redaction does not remove all sensitive text." => { + "Percakapan disertakan; penyamaran tidak menghapus semua teks sensitif." + } + "Conversation included without redaction." => "Percakapan disertakan tanpa penyamaran.", + "Conversation requested; check the updated preview." => { + "Percakapan diminta; periksa pratinjau yang diperbarui." + } + "Report plan included conversation without permission." => { + "Rencana laporan menyertakan percakapan tanpa izin." + } + "[ ] Include conversation" => "[ ] Sertakan percakapan", + "[x] Include conversation" => "[x] Sertakan percakapan", + "Check the preview for sensitive text before sharing." => { + "Periksa pratinjau untuk teks sensitif sebelum membagikan." + } + "Preview ZIP files" => "Pratinjau file ZIP", + "Preview pending" => "Pratinjau tertunda", + "Preview unavailable" => "Pratinjau tidak tersedia", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn gulir · Esc kembali", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn detail · ↑↓ pindah · Enter pilih · Esc tutup" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "File yang dihasilkan berbeda dari pratinjau rencana. Email tidak tersedia." + } + "Email unavailable without matching plan and ZIP previews." => { + "Email tidak tersedia tanpa pratinjau rencana dan ZIP yang cocok." + } + "(o) Investigation only" => "(o) Hanya investigasi", + "( ) Investigation only" => "( ) Hanya investigasi", + "(o) Team-internal regression of this ZIP only" => { + "(o) Hanya regresi internal tim untuk ZIP ini" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Hanya regresi internal tim untuk ZIP ini" + } + "Local attachment preview" => "Pratinjau lampiran lokal", + "Email is for investigating this report only, not evaluation." => { + "Email hanya untuk menyelidiki laporan ini, bukan untuk evaluasi." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Hanya regresi internal tim untuk ZIP ini. Tanpa penyedia eksternal, pelatihan, atau publikasi." + } + "Open email draft" => "Buka draf email", + "Email details" => "Detail email", + "To: {email}" => "Kepada: {email}", + "Subject: {subject}" => "Subjek: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Lampirkan ZIP yang tersimpan secara manual. Jika draf tidak terbuka, gunakan detail ini. Tidak ada yang dikirim." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "Tidak dapat membuka email. Tulis pesan secara manual dan lampirkan ZIP yang tersimpan." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Tulis pesan secara manual dan lampirkan ZIP yang tersimpan. Tidak ada yang dikirim." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "ZIP yang tersimpan hilang, tidak dapat dibaca, atau berubah. Simpan salinan baru." + } "Session model" => "Model sesi", "Skills instructions" => "Instruksi skill", "Some options were unsupported." => "Sebagian opsi tidak didukung.", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index 674b577d3a..54fedd8d75 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -766,6 +766,63 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "実行中…", "Save ZIP" => "ZIP を保存", "Saved ZIP" => "ZIP を保存しました", + "Diagnostics only; no conversation." => "診断情報のみ。会話は含まれません。", + "No conversation excerpts in this plan." => "このレポート計画に会話の抜粋はありません。", + "Conversation included; redaction does not remove all sensitive text." => { + "会話を含みます。秘匿してもすべての機密テキストは除去されません。" + } + "Conversation included without redaction." => "会話を秘匿なしで含みます。", + "Conversation requested; check the updated preview." => { + "会話が要求されました。更新されたプレビューを確認してください。" + } + "Report plan included conversation without permission." => { + "レポート計画に許可なく会話が含まれていました。" + } + "[ ] Include conversation" => "[ ] 会話を含める", + "[x] Include conversation" => "[x] 会話を含める", + "Check the preview for sensitive text before sharing." => { + "共有する前にプレビューで機密テキストを確認してください。" + } + "Preview ZIP files" => "ZIP 内のファイルをプレビュー", + "Preview pending" => "プレビュー待機中", + "Preview unavailable" => "プレビューを利用できません", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn スクロール · Esc 戻る", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn 詳細 · ↑↓ 移動 · Enter 選択 · Esc 閉じる" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "生成されたファイルがレポート計画のプレビューと一致しません。メールは利用できません。" + } + "Email unavailable without matching plan and ZIP previews." => { + "レポート計画と ZIP のプレビューが一致しないとメールを利用できません。" + } + "(o) Investigation only" => "(o) 調査のみ", + "( ) Investigation only" => "( ) 調査のみ", + "(o) Team-internal regression of this ZIP only" => "(o) この ZIP のチーム内部回帰のみ", + "( ) Team-internal regression of this ZIP only" => "( ) この ZIP のチーム内部回帰のみ", + "Local attachment preview" => "ローカル添付ファイルのプレビュー", + "Email is for investigating this report only, not evaluation." => { + "メールはこのレポートの調査専用で、評価には使用しません。" + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "この ZIP のチーム内部回帰のみ。外部プロバイダー、トレーニング、公開には使用しません。" + } + "Open email draft" => "メールの下書きを開く", + "Email details" => "メールの詳細", + "To: {email}" => "宛先: {email}", + "Subject: {subject}" => "件名: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "保存した ZIP を手動で添付してください。下書きが開かない場合は、この詳細を使用してください。何も送信されていません。" + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "メールを開けませんでした。手動で作成し、保存した ZIP を添付してください。" + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "手動で作成し、保存した ZIP を添付してください。何も送信されていません。" + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "保存した ZIP が見つからないか、読み取れないか、変更されています。新しいコピーを保存してください。" + } "Session model" => "セッションモデル", "Skills instructions" => "スキル指示", "Some options were unsupported." => "一部のオプションはサポートされていません。", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index bd2f160088..78f0513627 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -746,6 +746,63 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "실행 중…", "Save ZIP" => "ZIP 저장", "Saved ZIP" => "ZIP 저장됨", + "Diagnostics only; no conversation." => "진단 정보만 포함되며 대화는 없습니다.", + "No conversation excerpts in this plan." => "이 보고서 계획에는 대화 발췌가 없습니다.", + "Conversation included; redaction does not remove all sensitive text." => { + "대화가 포함되었습니다. 가리기를 해도 모든 민감한 텍스트가 제거되지는 않습니다." + } + "Conversation included without redaction." => "대화가 가리기 없이 포함되었습니다.", + "Conversation requested; check the updated preview." => { + "대화가 요청되었습니다. 업데이트된 미리보기를 확인하세요." + } + "Report plan included conversation without permission." => { + "보고서 계획에 권한 없이 대화가 포함되었습니다." + } + "[ ] Include conversation" => "[ ] 대화 포함", + "[x] Include conversation" => "[x] 대화 포함", + "Check the preview for sensitive text before sharing." => { + "공유하기 전에 미리보기에서 민감한 텍스트를 확인하세요." + } + "Preview ZIP files" => "ZIP 파일 미리보기", + "Preview pending" => "미리보기 대기 중", + "Preview unavailable" => "미리보기를 사용할 수 없음", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn 스크롤 · Esc 뒤로", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn 세부 정보 · ↑↓ 이동 · Enter 선택 · Esc 닫기" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "생성된 파일이 보고서 계획 미리보기와 다릅니다. 이메일을 사용할 수 없습니다." + } + "Email unavailable without matching plan and ZIP previews." => { + "보고서 계획과 ZIP 미리보기가 일치해야 이메일을 사용할 수 있습니다." + } + "(o) Investigation only" => "(o) 조사 전용", + "( ) Investigation only" => "( ) 조사 전용", + "(o) Team-internal regression of this ZIP only" => "(o) 이 ZIP의 팀 내부 회귀 전용", + "( ) Team-internal regression of this ZIP only" => "( ) 이 ZIP의 팀 내부 회귀 전용", + "Local attachment preview" => "로컬 첨부 파일 미리보기", + "Email is for investigating this report only, not evaluation." => { + "이메일은 이 보고서 조사용이며 평가용이 아닙니다." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "이 ZIP의 팀 내부 회귀 전용입니다. 외부 제공자, 학습, 공개에 사용하지 마세요." + } + "Open email draft" => "이메일 초안 열기", + "Email details" => "이메일 세부 정보", + "To: {email}" => "받는 사람: {email}", + "Subject: {subject}" => "제목: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "저장한 ZIP을 직접 첨부하세요. 초안이 열리지 않으면 이 세부 정보를 사용하세요. 아무것도 전송되지 않았습니다." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "이메일을 열지 못했습니다. 직접 작성하고 저장한 ZIP을 첨부하세요." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "직접 작성하고 저장한 ZIP을 첨부하세요. 아무것도 전송되지 않았습니다." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "저장한 ZIP이 없거나, 읽을 수 없거나, 변경되었습니다. 새 복사본을 저장하세요." + } "Session model" => "세션 모델", "Skills instructions" => "스킬 지침", "Some options were unsupported." => "일부 옵션은 지원되지 않습니다.", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index 3cf390a549..463461ac8a 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -796,6 +796,67 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "Executando…", "Save ZIP" => "Salvar ZIP", "Saved ZIP" => "ZIP salvo", + "Diagnostics only; no conversation." => "Somente diagnóstico; sem conversa.", + "No conversation excerpts in this plan." => "Este plano não inclui trechos de conversa.", + "Conversation included; redaction does not remove all sensitive text." => { + "Conversa incluída; Ocultar não remove todo o texto sensível." + } + "Conversation included without redaction." => "Conversa incluída sem Ocultar.", + "Conversation requested; check the updated preview." => { + "Conversa solicitada; confira a prévia atualizada." + } + "Report plan included conversation without permission." => { + "O plano do relatório incluiu conversa sem permissão." + } + "[ ] Include conversation" => "[ ] Incluir conversa", + "[x] Include conversation" => "[x] Incluir conversa", + "Check the preview for sensitive text before sharing." => { + "Confira a prévia em busca de texto sensível antes de compartilhar." + } + "Preview ZIP files" => "Pré-visualizar arquivos do ZIP", + "Preview pending" => "Prévia pendente", + "Preview unavailable" => "Prévia indisponível", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn rolar · Esc voltar", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn detalhes · ↑↓ mover · Enter selecionar · Esc fechar" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "Os arquivos gerados diferem da prévia do plano. O e-mail não está disponível." + } + "Email unavailable without matching plan and ZIP previews." => { + "O e-mail não está disponível sem prévias correspondentes do plano e do ZIP." + } + "(o) Investigation only" => "(o) Somente investigação", + "( ) Investigation only" => "( ) Somente investigação", + "(o) Team-internal regression of this ZIP only" => { + "(o) Somente regressão interna da equipe deste ZIP" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Somente regressão interna da equipe deste ZIP" + } + "Local attachment preview" => "Prévia do anexo local", + "Email is for investigating this report only, not evaluation." => { + "O e-mail serve apenas para investigar este relatório, não para avaliação." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Somente regressão interna da equipe deste ZIP. Sem provedores externos, treinamento ou publicação." + } + "Open email draft" => "Abrir rascunho de e-mail", + "Email details" => "Detalhes do e-mail", + "To: {email}" => "Para: {email}", + "Subject: {subject}" => "Assunto: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Anexe o ZIP salvo manualmente. Se nenhum rascunho abrir, use estes detalhes. Nada foi enviado." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "Não foi possível abrir o e-mail. Escreva a mensagem manualmente e anexe o ZIP salvo." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Escreva a mensagem manualmente e anexe o ZIP salvo. Nada foi enviado." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "O ZIP salvo está ausente, ilegível ou foi alterado. Salve uma nova cópia." + } "Session model" => "Modelo da sessão", "Skills instructions" => "Instruções de skills", "Some options were unsupported." => "Algumas opções não são suportadas.", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 24b373f078..45535823d1 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -804,6 +804,67 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "Em execução…", "Save ZIP" => "Guardar ZIP", "Saved ZIP" => "ZIP guardado", + "Diagnostics only; no conversation." => "Apenas diagnóstico; sem conversa.", + "No conversation excerpts in this plan." => "Este plano não inclui excertos de conversa.", + "Conversation included; redaction does not remove all sensitive text." => { + "Conversa incluída; Ocultar não remove todo o texto sensível." + } + "Conversation included without redaction." => "Conversa incluída sem Ocultar.", + "Conversation requested; check the updated preview." => { + "Conversa pedida; verifique a pré-visualização atualizada." + } + "Report plan included conversation without permission." => { + "O plano do relatório incluiu conversa sem autorização." + } + "[ ] Include conversation" => "[ ] Incluir conversa", + "[x] Include conversation" => "[x] Incluir conversa", + "Check the preview for sensitive text before sharing." => { + "Verifique a pré-visualização para detetar texto sensível antes de partilhar." + } + "Preview ZIP files" => "Pré-visualizar ficheiros do ZIP", + "Preview pending" => "Pré-visualização pendente", + "Preview unavailable" => "Pré-visualização indisponível", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn deslocar · Esc voltar", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn detalhes · ↑↓ mover · Enter selecionar · Esc fechar" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "Os ficheiros gerados diferem da pré-visualização do plano. O e-mail não está disponível." + } + "Email unavailable without matching plan and ZIP previews." => { + "O e-mail não está disponível sem pré-visualizações correspondentes do plano e do ZIP." + } + "(o) Investigation only" => "(o) Apenas investigação", + "( ) Investigation only" => "( ) Apenas investigação", + "(o) Team-internal regression of this ZIP only" => { + "(o) Apenas regressão interna da equipa deste ZIP" + } + "( ) Team-internal regression of this ZIP only" => { + "( ) Apenas regressão interna da equipa deste ZIP" + } + "Local attachment preview" => "Pré-visualização do anexo local", + "Email is for investigating this report only, not evaluation." => { + "O e-mail serve apenas para investigar este relatório, não para avaliação." + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "Apenas regressão interna da equipa deste ZIP. Sem fornecedores externos, treino ou publicação." + } + "Open email draft" => "Abrir rascunho de e-mail", + "Email details" => "Detalhes do e-mail", + "To: {email}" => "Para: {email}", + "Subject: {subject}" => "Assunto: {subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "Anexe o ZIP guardado manualmente. Se nenhum rascunho abrir, use estes detalhes. Nada foi enviado." + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "Não foi possível abrir o e-mail. Escreva a mensagem manualmente e anexe o ZIP guardado." + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "Escreva a mensagem manualmente e anexe o ZIP guardado. Nada foi enviado." + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "O ZIP guardado está ausente, ilegível ou foi alterado. Guarde uma nova cópia." + } "Session model" => "Modelo da sessão", "Skills instructions" => "Instruções de competências", "Some options were unsupported." => "Algumas opções não são suportadas.", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index 978b8472fd..83ecaabfaf 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -370,12 +370,30 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Model · Generate locally" => "模型 · 本地生成", "Local generation makes zero model requests." => "本地生成不会调用模型。", "Default: current-session diagnostics only." => "默认只打包当前会话的诊断信息。", + "Email the ZIP to {email}" => "可将 ZIP 作为附件发送至 {email}", "Redact is off. The ZIP may contain sensitive text from recent messages." => { "脱敏已关闭。ZIP 可能包含近期对话中的敏感内容。" } "Turn Redact off to attach recent user/assistant text to ZIP; it may contain sensitive data." => { "只有主动关闭脱敏,才会将近期用户和助手正文附加到 ZIP;可能含敏感信息。" } + "Diagnostics only; no conversation." => "仅包含诊断信息,不包含对话。", + "No conversation excerpts in this plan." => "此报告计划没有对话片段。", + "Conversation included; redaction does not remove all sensitive text." => { + "已包含对话片段;脱敏无法去除所有敏感内容。" + } + "Conversation included without redaction." => "已包含对话片段,未开启脱敏。", + "Conversation requested; check the updated preview." => { + "已选择包含对话,请检查更新后的预览。" + } + "Report plan included conversation without permission." => { + "报告计划未经允许包含了对话,已拒绝。" + } + "[ ] Include conversation" => "[ ] 包含对话", + "[x] Include conversation" => "[x] 包含对话", + "Check the preview for sensitive text before sharing." => { + "分享前请检查预览中是否仍有敏感内容。" + } "Error diagnostics only; no session text is available." => { "仅打包错误诊断信息;没有可收集的会话正文。" } @@ -403,7 +421,46 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter apply · Esc back" => "Enter 应用 · Esc 返回", "Save ZIP" => "保存 ZIP", "Saved ZIP" => "ZIP 已保存至", - "Email the ZIP to {email}" => "可将 ZIP 作为附件发送至 {email}", + "Preview ZIP files" => "预览 ZIP 内的文件", + "Preview pending" => "正在准备预览", + "Preview unavailable" => "当前无法预览", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn 滚动 · Esc 返回", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn 详情 · ↑↓ 切换 · Enter 选择 · Esc 关闭" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "生成的文件与计划预览不一致,无法起草邮件。" + } + "Email unavailable without matching plan and ZIP previews." => { + "计划与 ZIP 的预览必须一致,才能起草邮件。" + } + "(o) Investigation only" => "(o) 仅排查问题", + "( ) Investigation only" => "( ) 仅排查问题", + "(o) Team-internal regression of this ZIP only" => "(o) 本附件仅限团队内部回归", + "( ) Team-internal regression of this ZIP only" => "( ) 本附件仅限团队内部回归", + "Local attachment preview" => "本机附件预览", + "Email is for investigating this report only, not evaluation." => { + "仅排查本报告所述问题,不授权评测。" + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "仅限团队内部使用此 ZIP 做回归评测;不允许交给外部模型供应商、用于训练或公开。" + } + "Open email draft" => "打开邮件草稿", + "Email details" => "邮件信息", + "To: {email}" => "收件人:{email}", + "Subject: {subject}" => "主题:{subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "请手动附上已保存的 ZIP。若未打开草稿,请按下方信息手动撰写。未发送任何内容。" + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "未能打开邮件应用。请按下方信息撰写邮件并手动附上已保存的 ZIP。" + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "请手动撰写邮件并附上已保存的 ZIP。未发送任何内容。" + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "已保存的 ZIP 不存在、无法读取或已被修改。请重新保存一份。" + } "Draft a GitHub issue" => "在 GitHub 起草 Issue", "Give feedback on Discord" => "去 Discord 反馈", "Could not save ZIP" => "无法保存 ZIP", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 2a891140df..4687bf03cd 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -712,6 +712,63 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Running…" => "執行中…", "Save ZIP" => "儲存 ZIP", "Saved ZIP" => "ZIP 已儲存至", + "Diagnostics only; no conversation." => "僅包含診斷資訊,不包含對話。", + "No conversation excerpts in this plan." => "此報告計畫沒有對話片段。", + "Conversation included; redaction does not remove all sensitive text." => { + "已包含對話片段;遮蔽無法去除所有敏感內容。" + } + "Conversation included without redaction." => "已包含對話片段,未開啟遮蔽。", + "Conversation requested; check the updated preview." => { + "已選擇包含對話,請檢查更新後的預覽。" + } + "Report plan included conversation without permission." => { + "報告計畫未經允許包含了對話,已拒絕。" + } + "[ ] Include conversation" => "[ ] 包含對話", + "[x] Include conversation" => "[x] 包含對話", + "Check the preview for sensitive text before sharing." => { + "分享前請檢查預覽中是否仍有敏感內容。" + } + "Preview ZIP files" => "預覽 ZIP 內的檔案", + "Preview pending" => "正在準備預覽", + "Preview unavailable" => "目前無法預覽", + "↑↓/PgUp/PgDn scroll · Esc back" => "↑↓/PgUp/PgDn 捲動 · Esc 返回", + "PgUp/PgDn details · ↑↓ move · Enter select · Esc close" => { + "PgUp/PgDn 詳情 · ↑↓ 切換 · Enter 選擇 · Esc 關閉" + } + "Generated files differ from the plan preview. Email is unavailable." => { + "產生的檔案與計畫預覽不一致,無法起草郵件。" + } + "Email unavailable without matching plan and ZIP previews." => { + "計畫與 ZIP 的預覽必須一致,才能起草郵件。" + } + "(o) Investigation only" => "(o) 僅排查問題", + "( ) Investigation only" => "( ) 僅排查問題", + "(o) Team-internal regression of this ZIP only" => "(o) 本附件僅限團隊內部回歸", + "( ) Team-internal regression of this ZIP only" => "( ) 本附件僅限團隊內部回歸", + "Local attachment preview" => "本機附件預覽", + "Email is for investigating this report only, not evaluation." => { + "僅排查本報告所述問題,不授權評測。" + } + "Team-internal regression of this ZIP only. No external providers, training, or publication." => { + "僅限團隊內部使用此 ZIP 做回歸評測;不允許交給外部模型供應商、用於訓練或公開。" + } + "Open email draft" => "開啟郵件草稿", + "Email details" => "郵件資訊", + "To: {email}" => "收件者:{email}", + "Subject: {subject}" => "主旨:{subject}", + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent." => { + "請手動附上已儲存的 ZIP。若未開啟草稿,請按下方資訊手動撰寫。未傳送任何內容。" + } + "Could not launch email. Compose manually and attach the saved ZIP." => { + "未能開啟郵件應用程式。請按下方資訊撰寫郵件並手動附上已儲存的 ZIP。" + } + "Compose manually and attach the saved ZIP. Nothing was sent." => { + "請手動撰寫郵件並附上已儲存的 ZIP。未傳送任何內容。" + } + "Saved ZIP missing, unreadable, or changed. Save a new copy." => { + "已儲存的 ZIP 不存在、無法讀取或已被修改。請重新儲存一份。" + } "Session model" => "工作階段模型", "Skills instructions" => "技能說明", "Some options were unsupported." => "部分選項不受支援。", diff --git a/crates/dim-cli/src/ui/report_panel.rs b/crates/dim-cli/src/ui/report_panel.rs index 1bf2144d5d..8cfc432d84 100644 --- a/crates/dim-cli/src/ui/report_panel.rs +++ b/crates/dim-cli/src/ui/report_panel.rs @@ -1,11 +1,12 @@ use std::cell::Cell; use std::fs::OpenOptions; -use std::io::Write as _; +use std::io::{Read as _, Write as _}; use std::path::{Path, PathBuf}; -use base64::{Engine, engine::general_purpose::STANDARD}; - -use crate::report::{Action, Draft, EvidenceUnavailable, GeneratedReport, Plan, Reply, Target}; +use crate::report::{ + Action, Draft, EMAIL, EMAIL_SUBJECT, EvidenceUnavailable, GeneratedReport, MailScope, Plan, + Reply, ReportFiles, Target, mailto, +}; use crate::ui::i18n::{t, tf}; use crate::ui::line_input::LineInput; use crate::ui::render::panel::{bordered, follow_window, wrap}; @@ -20,6 +21,35 @@ enum Busy { Generate, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum ResultControl { + Save, + Preview, + Email, + MailDetails, + GitHub, + Discord, + Close, +} + +#[derive(Clone, Copy)] +enum DraftControl { + Preview, + Redact, + Conversation, + Scope(MailScope), + Email, + Options, + Generate, + Cancel, +} + +#[derive(Clone, Copy)] +enum View { + Preview, + MailDetails, +} + pub struct Panel { pub id: u64, pub draft: Option, @@ -30,12 +60,21 @@ pub struct Panel { busy: Option, note: String, redact: bool, + include_conversation: bool, editing: bool, options: LineInput, instructions: String, focus: usize, caret: Cell>, saved: Option, + planned_files: Option, + files_match: bool, + email_pending: bool, + scope: MailScope, + view: Option, + scroll: Cell, + page: Cell, + mail_details: String, } pub enum Input { @@ -56,16 +95,31 @@ impl Panel { busy: Some(Busy::Prepare), note: String::new(), redact: true, + include_conversation: false, editing: false, options: LineInput::new(""), instructions: String::new(), focus: 0, caret: Cell::new(None), saved: None, + planned_files: None, + files_match: false, + email_pending: false, + scope: MailScope::default(), + view: None, + scroll: Cell::new(0), + page: Cell::new(1), + mail_details: String::new(), } } - pub fn reply(&mut self, reply: Reply) -> Option { + pub fn reply( + &mut self, + reply: Reply, + workspace: &Path, + open: impl FnOnce(&str) -> bool, + ) -> Option { + let email = std::mem::take(&mut self.email_pending) && self.busy == Some(Busy::Generate); self.busy = None; self.note.clear(); match reply { @@ -76,21 +130,31 @@ impl Panel { report_id: prepared.report_id, plan_id: prepared.plan.plan_id.clone(), }); - if !self.redact || !self.instructions.is_empty() { + if !self.redact || self.include_conversation || !self.instructions.is_empty() { return self.replan(); } - self.plan = Some(prepared.plan); + self.accept_plan(prepared.plan); } Reply::Plan(plan) => { if let Some(draft) = &mut self.draft { draft.plan_id.clone_from(&plan.plan_id); } - self.plan = Some(plan); + self.accept_plan(plan); } Reply::Generated(report) => { self.draft = None; + let planned = self.planned_files.take(); + self.files_match = planned.is_some() && planned.as_ref() == report.files.as_ref(); + if planned.is_some() && !self.files_match { + self.note = + t("Generated files differ from the plan preview. Email is unavailable.") + .into(); + } self.generated = Some(report); self.focus = 0; + if email && self.files_match { + self.email(workspace, |uri| Some(open(uri))); + } } Reply::Failed { message, @@ -99,7 +163,7 @@ impl Panel { if draft_missing { self.draft = None; } - self.plan = None; + self.clear_plan(); self.note = crate::sanitize::safe_line(&message); } } @@ -112,6 +176,7 @@ impl Panel { self.busy = None; self.editing = false; if self.generated.is_none() { + self.clear_plan(); self.focus = 0; } self.note = crate::sanitize::safe_line(message); @@ -130,18 +195,83 @@ impl Panel { Action::Plan { draft, redact: self.redact, + include_conversation: self.include_conversation, instructions: self.instructions.clone(), }, ), None => (Busy::Prepare, Action::Prepare(self.target.clone()?)), }; self.busy = Some(busy); - self.plan = None; + self.clear_plan(); self.note.clear(); + self.scroll.set(0); Some(action) } + fn accept_plan(&mut self, plan: Plan) { + if !self.include_conversation && !plan.evidence.conversation.is_empty() { + self.note = t("Report plan included conversation without permission.").into(); + } else { + self.plan = Some(plan); + } + } + + fn clear_plan(&mut self) { + self.plan = None; + self.planned_files = None; + self.files_match = false; + self.email_pending = false; + self.view = None; + } + + fn preview_files(&self) -> Option<&ReportFiles> { + if let Some(report) = &self.generated { + report.files.as_ref() + } else { + self.plan.as_ref()?.files.as_ref() + } + } + + fn show(&mut self, view: View) { + self.scroll.set(0); + self.page.set(1); + self.view = Some(view); + } + + fn preview(&mut self) { + if self.preview_files().is_some() { + self.show(View::Preview); + } + } + pub fn key(&mut self, key: KeyEvent, workspace: &Path) -> Input { + self.key_with_opener(key, workspace, crate::browser::open) + } + + pub(super) fn key_with_opener( + &mut self, + key: KeyEvent, + workspace: &Path, + open: impl FnOnce(&str) -> bool, + ) -> Input { + if self.view.is_some() { + let row = self.scroll.get(); + let page = self.page.get(); + match key.code { + KeyCode::Esc | KeyCode::Enter => { + self.view = None; + self.scroll.set(0); + } + KeyCode::Up => self.scroll.set(row.saturating_sub(1)), + KeyCode::Down => self.scroll.set(row.saturating_add(1)), + KeyCode::PageUp => self.scroll.set(row.saturating_sub(page)), + KeyCode::PageDown => self.scroll.set(row.saturating_add(page)), + KeyCode::Home => self.scroll.set(0), + KeyCode::End => self.scroll.set(usize::MAX), + _ => {} + } + return Input::None; + } if key.code == KeyCode::Esc { if self.editing { self.editing = false; @@ -150,6 +280,7 @@ impl Panel { if self.busy == Some(Busy::Generate) && let Some(draft) = self.draft.clone() { + self.email_pending = false; self.note = t("Cancelling generation…").into(); return Input::Send(Action::Cancel { draft, @@ -171,37 +302,65 @@ impl Panel { self.options.handle_key(key); return Input::None; } - let count = self.controls().len(); + let (count, draft_control) = if self.generated.is_some() { + (self.result_controls().len(), None) + } else { + let controls = self.draft_controls(); + (controls.len(), Some(controls[self.focus])) + }; match key.code { + KeyCode::PageDown => self + .scroll + .set(self.scroll.get().saturating_add(self.page.get())), + KeyCode::PageUp => self + .scroll + .set(self.scroll.get().saturating_sub(self.page.get())), KeyCode::Tab => self.focus = (self.focus + 1) % count, KeyCode::BackTab => self.focus = (self.focus + count - 1) % count, KeyCode::Up => self.focus = self.focus.saturating_sub(1), KeyCode::Down => self.focus = (self.focus + 1).min(count - 1), - KeyCode::Enter if self.generated.is_some() => return self.generated_key(workspace), - KeyCode::Enter if self.focus == 4 || self.target.is_none() => { + KeyCode::Enter if self.generated.is_some() => { + return self.generated_key(workspace, open); + } + KeyCode::Enter if matches!(draft_control, Some(DraftControl::Cancel)) => { return Input::Close; } - KeyCode::Enter if self.busy.is_none() => match self.focus { - 0 => self.note = t("Local generation makes zero model requests.").into(), - 1 => { - self.redact.toggle(); - return self.replan().map_or(Input::None, Input::Send); - } - 2 => { - self.options = LineInput::new(&self.instructions); - self.editing = true; - } - 3 if self.plan.is_none() => return self.replan().map_or(Input::None, Input::Send), - 3 => { - if let Some(draft) = self.draft.clone() { - self.busy = Some(Busy::Generate); - self.plan = None; - self.note.clear(); - return Input::Send(Action::Generate(draft)); + KeyCode::Enter if self.busy.is_none() => { + use DraftControl::*; + let control = draft_control.expect("draft control"); + match control { + Preview => self.preview(), + Redact => { + self.redact.toggle(); + return self.replan().map_or(Input::None, Input::Send); + } + Conversation => { + self.include_conversation.toggle(); + return self.replan().map_or(Input::None, Input::Send); + } + Scope(scope) => self.scope = scope, + Options => { + self.options = LineInput::new(&self.instructions); + self.editing = true; + } + Generate if self.plan.is_none() => { + return self.replan().map_or(Input::None, Input::Send); } + Email if self.preview_files().is_none() => { + self.note = t("Preview unavailable").into(); + } + Email | Generate => { + if let Some(draft) = self.draft.clone() { + self.email_pending = matches!(control, Email); + self.busy = Some(Busy::Generate); + self.planned_files = self.plan.take().and_then(|plan| plan.files); + self.note.clear(); + return Input::Send(Action::Generate(draft)); + } + } + Cancel => unreachable!("handled even while busy"), } - _ => {} - }, + } _ => {} } Input::None @@ -211,22 +370,40 @@ impl Panel { self.saved.as_deref() } - fn generated_key(&mut self, workspace: &Path) -> Input { - let report = self.generated.as_ref().expect("generated report"); - match self.focus { - 0 => { + fn result_controls(&self) -> Vec { + use ResultControl::*; + let mut controls = vec![Save]; + if self.preview_files().is_some() { + controls.push(Preview); + } + if self.files_match { + controls.push(Email); + if self.saved.is_some() { + controls.push(MailDetails); + } + } + if self.saved.is_some() { + controls.extend([GitHub, Discord]); + } + controls.push(Close); + controls + } + + fn generated_key(&mut self, workspace: &Path, open: impl FnOnce(&str) -> bool) -> Input { + use ResultControl::*; + let control = self.result_controls()[self.focus]; + match control { + Save => { if self.saved.is_none() { - match save_zip(workspace, report) { - Ok(path) => { - self.saved = Some(path); - self.note.clear(); - } - Err(error) => self.note = format!("{} {error}", t("Could not save ZIP")), - } + self.save(workspace); } } - 1 | 2 if self.saved.is_some() => { - let (url, host, path) = if self.focus == 1 { + Preview => self.preview(), + Email => self.email(workspace, |uri| Some(open(uri))), + MailDetails => self.email(workspace, |_| None), + GitHub | Discord => { + let report = self.generated.as_ref().expect("generated report"); + let (url, host, path) = if control == GitHub { ( &report.sharing.github_issue_url, "github.com", @@ -243,8 +420,8 @@ impl Panel { && url.password().is_none() && url.port().is_none() }); - self.note = if valid.is_some_and(|url| crate::browser::open(url.as_str())) { - if self.focus == 2 { + self.note = if valid.is_some_and(|url| open(url.as_str())) { + if control == Discord { crate::clipboard::copy_local(&report.sharing.description); t("Opened Discord") } else { @@ -255,43 +432,144 @@ impl Panel { } .into(); } - _ => return Input::Close, + Close => return Input::Close, } Input::None } + fn save(&mut self, workspace: &Path) { + self.note = match self + .generated + .as_ref() + .expect("generated report") + .zip_bytes() + .and_then(|bytes| save_zip(workspace, &bytes)) + { + Ok(path) => { + self.saved = Some(path); + String::new() + } + Err(error) => format!("{} {error}", t("Could not save ZIP")), + }; + } + + fn email(&mut self, workspace: &Path, open: impl FnOnce(&str) -> Option) { + if self.saved.is_none() { + self.save(workspace); + } + let Some(path) = &self.saved else { + return; + }; + let Ok(bytes) = self + .generated + .as_ref() + .expect("generated report") + .zip_bytes() + else { + self.note = t("Invalid report ZIP").into(); + return; + }; + let verified = (|| -> std::io::Result { + if !std::fs::symlink_metadata(path)?.is_file() { + return Ok(false); + } + let file = std::fs::File::open(path)?; + let mut saved = Vec::with_capacity(bytes.len()); + file.take(bytes.len() as u64 + 1).read_to_end(&mut saved)?; + Ok(saved == bytes) + })(); + if !matches!(verified, Ok(true)) { + self.saved = None; + self.focus = 0; + self.note = t("Saved ZIP missing, unreadable, or changed. Save a new copy.").into(); + self.scroll.set(0); + return; + } + self.note.clear(); + let body = self.scope.body(&bytes); + let instruction = match open(&mailto(&body)) { + Some(true) => t( + "Attach the saved ZIP manually. If no draft opens, use these details. Nothing was sent.", + ), + Some(false) => t("Could not launch email. Compose manually and attach the saved ZIP."), + None => t("Compose manually and attach the saved ZIP. Nothing was sent."), + }; + self.mail_details = format!( + "{instruction}\n{} {}\n{}\n{}\n{}", + t("Saved ZIP"), + crate::sanitize::safe_line(&path.display().to_string()), + tf("To: {email}", &[("email", EMAIL)]), + tf("Subject: {subject}", &[("subject", EMAIL_SUBJECT)]), + body.replace("\r\n", "\n"), + ); + self.show(View::MailDetails); + } + + fn draft_controls(&self) -> Vec { + use DraftControl::*; + if self.target.is_none() { + return vec![Cancel]; + } + let mut controls = vec![Preview, Redact]; + if matches!(&self.target, Some(Target::Session(_))) { + controls.push(Conversation); + } + controls.extend([ + Scope(MailScope::ReportOnly), + Scope(MailScope::InternalRegression), + Email, + Options, + Generate, + Cancel, + ]); + controls + } + fn controls(&self) -> Vec<&str> { if self.generated.is_some() { - if self.saved.is_some() { - vec![ - t("Save ZIP"), - t("Draft a GitHub issue"), - t("Give feedback on Discord"), - t("Close"), - ] - } else { - vec![t("Save ZIP"), t("Close")] - } - } else if self.target.is_none() { - vec![t("Close")] + self.result_controls() + .into_iter() + .map(|control| match control { + ResultControl::Save => t("Save ZIP"), + ResultControl::Preview => t("Preview ZIP files"), + ResultControl::Email => t("Open email draft"), + ResultControl::MailDetails => t("Email details"), + ResultControl::GitHub => t("Draft a GitHub issue"), + ResultControl::Discord => t("Give feedback on Discord"), + ResultControl::Close => t("Close"), + }) + .collect() } else { - vec![ - t("Model · Generate locally"), - if self.redact { - t("Redact [x]") - } else { - t("Redact [ ]") - }, - t("Options"), - if self.busy.is_some() || self.plan.is_some() { - t("Generate report") - } else if self.draft.is_some() { - t("Refresh report plan") - } else { - t("Prepare report again") - }, - t("Cancel"), - ] + use DraftControl::*; + self.draft_controls() + .into_iter() + .map(|control| match control { + Preview if self.preview_files().is_some() => t("Local attachment preview"), + Preview if self.busy.is_some() => t("Preview pending"), + Preview => t("Preview unavailable"), + Redact if self.redact => t("Redact [x]"), + Redact => t("Redact [ ]"), + Conversation if self.include_conversation => t("[x] Include conversation"), + Conversation => t("[ ] Include conversation"), + Scope(MailScope::ReportOnly) => match self.scope { + MailScope::ReportOnly => t("(o) Investigation only"), + MailScope::InternalRegression => t("( ) Investigation only"), + }, + Scope(MailScope::InternalRegression) => match self.scope { + MailScope::ReportOnly => t("( ) Team-internal regression of this ZIP only"), + MailScope::InternalRegression => { + t("(o) Team-internal regression of this ZIP only") + } + }, + Email => t("Open email draft"), + Options => t("Options"), + Generate if self.busy.is_some() || self.plan.is_some() => t("Generate report"), + Generate if self.draft.is_some() => t("Refresh report plan"), + Generate => t("Prepare report again"), + Cancel if self.target.is_none() => t("Close"), + Cancel => t("Cancel"), + }) + .collect() } } @@ -316,6 +594,27 @@ impl Panel { let inner = width - 4; let height = budget - 2; let mut rows = Vec::new(); + if let Some(view) = self.view { + let (title, text) = match view { + View::Preview => ( + t("Preview ZIP files"), + self.preview_files() + .map(ReportFiles::preview) + .unwrap_or_default(), + ), + View::MailDetails => (t("Email details"), self.mail_details.clone()), + }; + let content: Vec<_> = text + .split('\n') + .flat_map(|line| wrap(line, inner)) + .collect(); + let start = self.scroll.get().min(content.len().saturating_sub(height)); + self.scroll.set(start); + self.page.set(height); + rows.extend(content.into_iter().skip(start).take(height)); + let hint = truncate_cells(t("↑↓/PgUp/PgDn scroll · Esc back"), inner.saturating_sub(2)); + return bordered(&rows, width, None, &p.border, Some(title), Some(&hint)); + } if self.editing { rows.push(truncate_cells( t("Options · for example: omit timeline, keep error codes"), @@ -337,21 +636,31 @@ impl Panel { if let Some(path) = &self.saved { let path = crate::sanitize::safe_line(&path.display().to_string()); rows.extend(wrap(&format!("{} {path}", t("Saved ZIP")), inner)); - rows.extend(crate::ui::render::panel::wrap_words( - &tf( - "Email the ZIP to {email}", - &[("email", "feedback@arcships.ai")], - ), - inner, - )); + } + if let Some(files) = self.plan.as_ref().and_then(|plan| plan.files.as_ref()) { + for (name, content) in [ + ("report.md", &files.report), + ("diagnostics.json", &files.diagnostics), + ] { + let excerpt = content + .lines() + .find(|s| !s.trim().is_empty() && !matches!(s.trim(), "{" | "[")) + .unwrap_or(content); + rows.push(truncate_cells( + &format!("{name}: {}", crate::sanitize::safe_line(excerpt)), + inner, + )); + } } rows.extend( crate::sanitize::safe(&self.summary()) .lines() - .flat_map(|line| crate::ui::render::panel::wrap_words(line, inner)) - .take(body_rows.saturating_sub(rows.len())), + .flat_map(|line| crate::ui::render::panel::wrap_words(line, inner)), ); - rows.truncate(body_rows); + let start = self.scroll.get().min(rows.len().saturating_sub(body_rows)); + self.scroll.set(start); + self.page.set(body_rows.max(1)); + rows = rows.into_iter().skip(start).take(body_rows).collect(); for (index, label) in controls.into_iter().enumerate().skip(first).take(visible) { let selected = self.focus == index; let line = truncate_cells( @@ -364,32 +673,49 @@ impl Panel { let hint = if self.editing { t("Enter apply · Esc back") } else { - t("↑↓/Tab move · Enter select · Esc close") + t("PgUp/PgDn details · ↑↓ move · Enter select · Esc close") }; bordered(&rows, width, None, &p.border, Some(title), Some(hint)) } fn summary(&self) -> String { let mut body = if let Some(report) = &self.generated { + let guidance = if !self.files_match { + t("Email unavailable without matching plan and ZIP previews.") + } else if matches!(self.scope, MailScope::InternalRegression) { + t( + "Team-internal regression of this ZIP only. No external providers, training, or publication.", + ) + } else { + t("Email is for investigating this report only, not evaluation.") + }; format!( - "{}\n{}\n{}", + "{guidance}\n{}\n{}\n{}", t("Generate/save never uploads. Share manually after saving."), crate::sanitize::safe_line(&report.title), t("ZIP contents: report.md, diagnostics.json") ) } else { let mut body = match &self.target { - Some(Target::Session(_)) if !self.redact => format!( - "{}\n", - t("Redact is off. The ZIP may contain sensitive text from recent messages.") - ), - Some(Target::Session(_)) => format!( - "{}\n{}\n", - t("Default: current-session diagnostics only."), - t( - "Turn Redact off to attach recent user/assistant text to ZIP; it may contain sensitive data." + Some(Target::Session(_)) if !self.include_conversation => { + format!("{}\n", t("Diagnostics only; no conversation.")) + } + Some(Target::Session(_)) => { + let status = match &self.plan { + Some(plan) if plan.evidence.conversation.is_empty() => { + t("No conversation excerpts in this plan.") + } + Some(_) if self.redact => t( + "Conversation included; redaction does not remove all sensitive text.", + ), + Some(_) => t("Conversation included without redaction."), + None => t("Conversation requested; check the updated preview."), + }; + format!( + "{status}\n{}\n", + t("Check the preview for sensitive text before sharing.") ) - ), + } Some(Target::Error(_)) => { format!( "{}\n", @@ -398,6 +724,10 @@ impl Panel { } None => String::new(), }; + if matches!(self.scope, MailScope::InternalRegression) { + body.push_str(t("Team-internal regression of this ZIP only. No external providers, training, or publication.")); + body.push('\n'); + } body.push_str(t( "Generate/save never uploads. Share manually after saving.", )); @@ -460,11 +790,7 @@ impl Panel { } } -fn save_zip(workspace: &Path, report: &GeneratedReport) -> crate::Result { - let bytes = STANDARD.decode(&report.archive.base64)?; - if bytes.len() > 64 * 1024 || !bytes.starts_with(b"PK\x03\x04") { - return Err(t("Invalid report ZIP").into()); - } +fn save_zip(workspace: &Path, bytes: &[u8]) -> crate::Result { let path = workspace.join(format!("dim-report-{}.zip", uuid::Uuid::new_v4())); let mut options = OpenOptions::new(); options.write(true).create_new(true); @@ -474,7 +800,7 @@ fn save_zip(workspace: &Path, report: &GeneratedReport) -> crate::Result bool, + ) { + let action = if let Some(Prompt::Report(report)) = &mut self.prompt + && report.id == panel + { + report.reply(reply, std::path::Path::new(&self.cwd_key), open) + } else if let crate::report::Reply::Prepared(session, prepared) = reply { + Some(crate::report::Action::Cancel { + draft: crate::report::Draft { + session, + report_id: prepared.report_id, + plan_id: prepared.plan.plan_id, + }, + generation: false, + }) + } else { + None + }; + if let Some(action) = action { + self.host + .send(Command::Report(crate::report::Request { panel, action })); + } + } + fn apply(&mut self, update: Update) { match update { Update::Withdrawn(input) => { @@ -2752,26 +2780,7 @@ impl App { } } Update::ReportReply { panel, reply } => { - if let Some(Prompt::Report(report)) = &mut self.prompt - && report.id == panel - { - if let Some(action) = report.reply(reply) { - self.host - .send(Command::Report(crate::report::Request { panel, action })); - } - } else if let crate::report::Reply::Prepared(session, prepared) = reply { - self.host.send(Command::Report(crate::report::Request { - panel, - action: crate::report::Action::Cancel { - draft: crate::report::Draft { - session, - report_id: prepared.report_id, - plan_id: prepared.plan.plan_id, - }, - generation: false, - }, - })); - } + self.report_reply(panel, reply, crate::browser::open) } Update::Report { text, warning } => self.reports.push(Block::Status { text, @@ -21555,9 +21564,9 @@ mod tests { }; let screen = report.render(110, 20, &app.palette).join("\n"); assert!(screen.contains(t("Error diagnostics only; no session text is available."))); - assert!(!screen.contains(t("Default: current-session diagnostics only."))); - assert!(!screen.contains(t("Turn Redact off to attach recent user/assistant text to ZIP; it may contain sensitive data."))); - for _ in 0..3 { + assert!(!screen.contains(t("[ ] Include conversation"))); + assert!(!screen.contains(t("Check the preview for sensitive text before sharing."))); + for _ in 0..6 { press(&mut app, KeyCode::Down); } press(&mut app, KeyCode::Enter); @@ -21619,8 +21628,8 @@ mod tests { }) .collect(); for notice in [ - "Default: current-session diagnostics only.", - "Turn Redact off to attach recent user/assistant text to ZIP; it may contain sensitive data.", + "Diagnostics only; no conversation.", + "[ ] Include conversation", "Generate/save never uploads. Share manually after saving.", ] { let notice: String = t(notice).chars().filter(|c| !c.is_whitespace()).collect(); @@ -21630,7 +21639,7 @@ mod tests { ); } } - for _ in 0..3 { + for _ in 0..7 { press(&mut app, KeyCode::Down); } let Some(Prompt::Report(report)) = &app.prompt else { @@ -21722,7 +21731,11 @@ mod tests { assert!(matches!( sent.borrow().last(), Some(Command::Report(Request { - action: Action::Plan { redact: false, .. }, + action: Action::Plan { + redact: false, + include_conversation: false, + .. + }, .. })) )); @@ -21731,16 +21744,33 @@ mod tests { }; let notice = report.render(110, 20, &app.palette).join("\n"); assert!(notice.contains(t("Redact [ ]"))); - assert!(notice.contains(t( - "Redact is off. The ZIP may contain sensitive text from recent messages." - ))); - assert!(!notice.contains(t("Default: current-session diagnostics only."))); + assert!(notice.contains(t("Diagnostics only; no conversation."))); + assert!(notice.contains(t("[ ] Include conversation"))); app.apply(Update::ReportReply { panel, reply: Reply::Plan(prepared_report("r1", "p2").plan), }); press(&mut app, KeyCode::Down); press(&mut app, KeyCode::Enter); + assert!(matches!( + sent.borrow().last(), + Some(Command::Report(Request { + action: Action::Plan { + redact: false, + include_conversation: true, + .. + }, + .. + })) + )); + app.apply(Update::ReportReply { + panel, + reply: Reply::Plan(prepared_report("r1", "p2b").plan), + }); + for _ in 0..4 { + press(&mut app, KeyCode::Down); + } + press(&mut app, KeyCode::Enter); typed(&mut app, "omit timeline"); press(&mut app, KeyCode::Enter); let mut plan = prepared_report("r1", "p3").plan; @@ -21780,6 +21810,7 @@ mod tests { action: Action::Plan { draft, redact: false, + include_conversation: true, instructions, }, .. @@ -21813,6 +21844,7 @@ mod tests { action: Action::Plan { draft, redact: false, + include_conversation: true, instructions, }, .. @@ -21822,6 +21854,502 @@ mod tests { )); } + #[test] + fn report_previews_both_complete_files_and_replaces_stale_redaction_preview() { + use crate::report::{Reply, ReportFiles}; + + for fullscreen in [false, true] { + let (mut app, _sent, _home) = asked(); + app.fullscreen = fullscreen; + app.session_id = "s1".into(); + let panel = open_test_report(&mut app); + let make_plan = |id, report| { + let mut prepared = prepared_report("r1", id); + prepared.plan.files = Some(ReportFiles { + report, + diagnostics: "diagnostic line\n".repeat(60) + "last-diagnostic", + }); + prepared + }; + let prepared = make_plan( + "p1", + "report line\n".repeat(60) + "last-report\x1b]52;terminal\x07", + ); + app.apply(Update::ReportReply { + panel, + reply: Reply::Prepared(Some("s1".into()), prepared), + }); + press(&mut app, KeyCode::Enter); + let screen = |app: &App| { + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected report") + }; + crate::ui::render::panel::strip_escapes( + &report.render(100, 8, &app.palette).join("\n"), + ) + }; + assert!(screen(&app).contains("--- report.md ---")); + assert!(!screen(&app).contains("last-diagnostic")); + let mut both = String::new(); + for _ in 0..25 { + both.push_str(&screen(&app)); + press(&mut app, KeyCode::PageDown); + } + assert!(both.contains("last-report\\u{1b}]52;terminal\\u{7}")); + assert!(both.contains("--- diagnostics.json ---")); + assert!(both.contains("last-diagnostic")); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Enter); + app.apply(Update::ReportReply { + panel, + reply: Reply::Plan(make_plan("p2", "unredacted-marker".into()).plan), + }); + press(&mut app, KeyCode::Up); + press(&mut app, KeyCode::Enter); + assert!(screen(&app).contains("unredacted-marker")); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Enter); + press(&mut app, KeyCode::Up); + press(&mut app, KeyCode::Enter); + assert!(screen(&app).contains(t("Preview pending"))); + assert!(!screen(&app).contains("unredacted-marker")); + app.apply(Update::ReportReply { + panel, + reply: Reply::Failed { + message: "offline".into(), + draft_missing: false, + }, + }); + press(&mut app, KeyCode::Enter); + assert!(screen(&app).contains(t("Preview unavailable"))); + assert!(!screen(&app).contains("unredacted-marker")); + } + } + + #[test] + fn report_conversation_opt_in_replaces_preview_and_hides_it_again_when_unchecked() { + use crate::report::{Action, Reply, ReportFiles, Request}; + + for fullscreen in [false, true] { + let (mut app, sent, _home) = asked(); + app.fullscreen = fullscreen; + app.session_id = "s1".into(); + let panel = open_test_report(&mut app); + let mut prepared = prepared_report("r1", "p1"); + prepared.plan.files = Some(ReportFiles { + report: "diagnostics-only-marker".into(), + diagnostics: "{}".into(), + }); + app.apply(Update::ReportReply { + panel, + reply: Reply::Prepared(Some("s1".into()), prepared), + }); + let render = |app: &App, width, height| { + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected report panel") + }; + let rows = report.render(width, height, &app.palette); + assert!(rows.len() <= height); + assert!( + rows.iter() + .all(|line| crate::ui::render::panel::visible_width(line) <= width) + ); + rows.join("\n") + }; + press(&mut app, KeyCode::Enter); + assert!(render(&app, 60, 8).contains("diagnostics-only-marker")); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Down); + assert!(render(&app, 32, 6).contains(t("[ ] Include conversation"))); + press(&mut app, KeyCode::Enter); + assert!(matches!( + sent.borrow().last(), + Some(Command::Report(Request { + action: Action::Plan { + redact: true, + include_conversation: true, + .. + }, + .. + })) + )); + assert!(!render(&app, 90, 20).contains("diagnostics-only-marker")); + let mut plan = prepared_report("r1", "p2").plan; + plan.evidence.conversation = serde_json::from_value(serde_json::json!([{}])).unwrap(); + plan.files = Some(ReportFiles { + report: "redacted-excerpt-marker".into(), + diagnostics: "{}".into(), + }); + app.apply(Update::ReportReply { + panel, + reply: Reply::Plan(plan), + }); + let screen = render(&app, 90, 20); + assert!(screen.contains(t("[x] Include conversation"))); + assert!(screen.contains(t( + "Conversation included; redaction does not remove all sensitive text." + ))); + press(&mut app, KeyCode::Enter); + assert!(matches!( + sent.borrow().last(), + Some(Command::Report(Request { + action: Action::Plan { + redact: true, + include_conversation: false, + .. + }, + .. + })) + )); + let screen = render(&app, 90, 20); + assert!(screen.contains(t("Diagnostics only; no conversation."))); + assert!(!screen.contains("redacted-excerpt-marker")); + } + } + + #[test] + fn report_email_saves_exact_bytes_and_keeps_scope_out_of_public_sharing() { + use crate::report::{GeneratedReport, Reply}; + use base64::{Engine, engine::general_purpose::STANDARD}; + use sha2::{Digest, Sha256}; + + let archive = concat!( + "UEsDBBQAAAAAAAAAIQBDv6ajAgAAAAIAAAAQAAAAZGlhZ25vc3RpY3MuanNvbnt9", + "UEsDBBQAAAAAAAAAIQAdZACtFQAAABUAAAAJAAAAcmVwb3J0Lm1kc2VjcmV0LXNlc3Npb24tbWFya2Vy", + "UEsBAhQDFAAAAAAAAAAhAEO/pqMCAAAAAgAAABAAAAAAAAAAAAAAAIABAAAAAGRpYWdub3N0aWNzLmpzb24", + "QSwECFAMUAAAAAAAAACEAHWQArRUAAAAVAAAACQAAAAAAAAAAAAAAgAEwAAAAcmVwb3J0Lm1kUEsFBgAAAAACAAIAdQAAAGwAAAAAAA==", + ); + let bytes = STANDARD.decode(archive).unwrap(); + let digest = format!("{:x}", Sha256::digest(&bytes)); + for fullscreen in [false, true] { + for (regression, outcome) in [ + (false, "match"), + (true, "match"), + (true, "mismatch"), + (true, "stale"), + (true, "close"), + (true, "cancel"), + (true, "failure"), + (true, "old"), + ] { + let (mut app, sent, home) = asked(); + app.fullscreen = fullscreen; + app.session_id = "s1".into(); + app.cwd_key = home.path().display().to_string(); + let panel = open_test_report(&mut app); + let files = serde_json::json!({"report.md":"secret-session-marker", "diagnostics.json":"{}"}); + let mut prepared = prepared_report("r1", "p1"); + let planned = if outcome != "mismatch" { + files.clone() + } else { + serde_json::json!({"report.md":"different", "diagnostics.json":"{}"}) + }; + prepared.plan.files = + (outcome != "old").then(|| serde_json::from_value(planned).unwrap()); + app.apply(Update::ReportReply { + panel, + reply: Reply::Prepared(Some("s1".into()), prepared), + }); + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected panel") + }; + let screen = report.render(100, 20, &app.palette).join("\n"); + assert!( + screen.contains(t("(o) Investigation only")) + && screen.contains(t("( ) Team-internal regression of this ZIP only")) + && screen.contains(t("Open email draft")) + ); + if outcome == "match" { + assert!( + screen.contains("report.md: secret-session-marker") + && screen.contains("diagnostics.json: {}") + ); + } + let before = sent.borrow().len(); + for _ in 0..4 { + press(&mut app, KeyCode::Down); + } + if regression { + press(&mut app, KeyCode::Enter); + } + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Enter); + press(&mut app, KeyCode::Enter); + if outcome == "old" { + assert_eq!(sent.borrow().len(), before); + continue; + } + assert_eq!(sent.borrow().len(), before + 1); + assert!( + matches!(sent.borrow().last(),Some(Command::Report(crate::report::Request {action:crate::report::Action::Generate(draft),..})) if draft.plan_id == "p1") + ); + let generated: GeneratedReport = serde_json::from_value(serde_json::json!({ + "title":"private-subject-marker", "files": files, + "archive":{"base64":archive}, + "sharing":{"githubIssueUrl":"https://github.com/arcships/dim/issues/new?title=Diagnostic", "discordUrl":"https://discord.gg/ds35K3TadP", "description":"Diagnostic"} + })).unwrap(); + if outcome == "cancel" { + press(&mut app, KeyCode::Esc); + } + if outcome == "close" { + for _ in 0..3 { + press(&mut app, KeyCode::Down); + } + press(&mut app, KeyCode::Enter); + assert!(!matches!(app.prompt, Some(Prompt::Report(_)))); + } + if outcome == "failure" { + app.report_reply( + panel, + Reply::Failed { + message: "offline".into(), + draft_missing: false, + }, + |_| panic!("failed generation opened mail"), + ); + } + let mut mail = String::new(); + app.report_reply( + if outcome == "stale" { panel + 1 } else { panel }, + Reply::Generated(generated), + |uri| { + mail = uri.to_owned(); + false + }, + ); + if outcome != "match" { + assert!(mail.is_empty(), "{outcome}"); + assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 0); + if outcome == "mismatch" { + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected result") + }; + let screen = report.render(110, 20, &app.palette).join("\n"); + assert!(screen.contains(t( + "Email unavailable without matching plan and ZIP previews." + ))); + assert!(!screen.contains(t("Open email draft"))); + assert!(!screen.contains(t("Email details"))); + } + continue; + } + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected report") + }; + let enter = || crate::ui::terminal::KeyEvent::new(KeyCode::Enter, Modifiers::NONE); + let path = report.saved_path().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), bytes); + assert!(mail.starts_with("mailto:feedback@arcships.ai?subject=Dim%20report&body=")); + assert!(mail.contains(&format!("%0D%0ASHA-256%3A%20{digest}"))); + assert_eq!( + mail.contains( + "team-internal%20regression%20evaluation%20of%20this%20ZIP%20only" + ), + regression + ); + assert_eq!( + mail.contains( + "No%20external%20model%20providers%2C%20training%2C%20or%20publication." + ), + regression + ); + assert_eq!( + mail.contains("no%20evaluation%20authorization"), + !regression + ); + for forbidden in [ + "secret-session-marker", + "private-subject-marker", + "dim-report-", + "+", + ] { + assert!(!mail.contains(forbidden), "{mail}"); + } + let manual = report.render(160, 20, &app.palette).join("\n"); + assert!(manual.contains(t( + "Could not launch email. Compose manually and attach the saved ZIP." + ))); + assert!(manual.contains(&path.display().to_string())); + assert!(manual.contains(&digest)); + assert!(manual.contains("feedback@arcships.ai")); + report.key_with_opener(enter(), home.path(), |_| { + panic!("returning from details must not reopen mail") + }); + for _ in 0..4 { + press(&mut app, KeyCode::Down); + } + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected report") + }; + let mut public = String::new(); + report.key_with_opener(enter(), home.path(), |uri| { + public = uri.to_owned(); + false + }); + assert_eq!( + public, + "https://github.com/arcships/dim/issues/new?title=Diagnostic" + ); + } + } + } + + #[test] + fn report_result_email_reuses_zip_after_preview_save_or_save_retry() { + use crate::report::{Archive, GeneratedReport, Reply, ReportFiles, Sharing}; + use base64::{Engine, engine::general_purpose::STANDARD}; + use sha2::{Digest, Sha256}; + + let bytes = b"PK\x03\x04fixture"; + let digest = format!("{:x}", Sha256::digest(bytes)); + for fullscreen in [false, true] { + for retry in [false, true] { + let (mut app, _sent, home) = asked(); + app.fullscreen = fullscreen; + app.session_id = "s1".into(); + let workspace = home.path().join("report-workspace"); + if !retry { + std::fs::create_dir(&workspace).unwrap(); + } + app.cwd_key = workspace.display().to_string(); + let panel = open_test_report(&mut app); + let files = || ReportFiles { + report: "reviewed diagnostic".into(), + diagnostics: "{}".into(), + }; + let mut prepared = prepared_report("r1", "p1"); + prepared.plan.files = Some(files()); + app.apply(Update::ReportReply { + panel, + reply: Reply::Prepared(Some("s1".into()), prepared), + }); + for _ in 0..if retry { 5 } else { 7 } { + press(&mut app, KeyCode::Down); + } + press(&mut app, KeyCode::Enter); + app.report_reply( + panel, + Reply::Generated(GeneratedReport { + title: "Test report".into(), + files: Some(files()), + archive: Archive { + base64: STANDARD.encode(bytes), + }, + sharing: Sharing { + github_issue_url: String::new(), + discord_url: String::new(), + description: String::new(), + }, + }), + |_| panic!("mail must not launch on Generate or on a failed save"), + ); + let render = |app: &App, width, height| { + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected result") + }; + report.render(width, height, &app.palette).join("\n") + }; + if retry { + assert!(render(&app, 100, 16).contains(t("Could not save ZIP"))); + std::fs::create_dir(&workspace).unwrap(); + } + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Enter); + assert!(render(&app, 64, 8).contains("reviewed diagnostic")); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Up); + press(&mut app, KeyCode::Enter); + let path = std::fs::read_dir(&workspace) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Down); + assert!(render(&app, 32, 6).contains(t("Open email draft"))); + let enter = || crate::ui::terminal::KeyEvent::new(KeyCode::Enter, Modifiers::NONE); + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected result") + }; + let mut opened = false; + report.key_with_opener(enter(), &workspace, |uri| { + opened = true; + assert!(uri.contains(&format!("%0D%0ASHA-256%3A%20{digest}"))); + assert!(!uri.contains("reviewed")); + false + }); + assert!(opened); + assert_eq!(report.saved_path(), Some(path.as_path())); + assert_eq!(std::fs::read_dir(&workspace).unwrap().count(), 1); + assert!(render(&app, 140, 14).contains(t( + "Could not launch email. Compose manually and attach the saved ZIP." + ))); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Down); + assert!(render(&app, 32, 6).contains(t("Email details"))); + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected result") + }; + report.key_with_opener(enter(), &workspace, |_| { + panic!("manual details must not open mail") + }); + let details = render(&app, 160, 14); + assert!(details.contains(&path.display().to_string())); + assert!(details.contains(&digest)); + press(&mut app, KeyCode::Esc); + std::fs::write(&path, b"changed archive").unwrap(); + press(&mut app, KeyCode::Up); + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected result") + }; + report.key_with_opener(enter(), &workspace, |_| { + panic!("changed ZIP must not open mail") + }); + let screen = render(&app, 140, 14); + assert!(screen.contains(t( + "Saved ZIP missing, unreadable, or changed. Save a new copy." + ))); + assert!(!screen.contains(&digest)); + assert_eq!(std::fs::read_dir(&workspace).unwrap().count(), 1); + + press(&mut app, KeyCode::Enter); + let Some(Prompt::Report(report)) = &app.prompt else { + panic!("expected result") + }; + let copy = report.saved_path().unwrap().to_owned(); + assert_ne!(copy, path); + assert_eq!(std::fs::read(©).unwrap(), bytes); + assert_eq!(std::fs::read(&path).unwrap(), b"changed archive"); + press(&mut app, KeyCode::Down); + press(&mut app, KeyCode::Down); + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected result") + }; + let mut launched = false; + report.key_with_opener(enter(), &workspace, |uri| { + launched = true; + assert!(uri.contains(&format!("%0D%0ASHA-256%3A%20{digest}"))); + true + }); + assert!(launched); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Down); + let Some(Prompt::Report(report)) = &mut app.prompt else { + panic!("expected result") + }; + report.key_with_opener(enter(), &workspace, |_| panic!("manual details")); + let details = render(&app, 160, 14); + assert!(details.contains(©.display().to_string())); + assert!(details.contains(&digest)); + } + } + } + #[test] fn report_close_before_save_never_activates_a_share_destination() { use crate::report::{Archive, GeneratedReport, Reply, Sharing}; @@ -21837,6 +22365,7 @@ mod tests { panel, reply: Reply::Generated(GeneratedReport { title: "Test report".into(), + files: None, archive: Archive { base64: STANDARD.encode(b"PK\x03\x04fixture"), }, @@ -21883,6 +22412,7 @@ mod tests { panel, reply: Reply::Generated(GeneratedReport { title: "Test report".into(), + files: None, archive: Archive { base64: STANDARD.encode(&bytes), }, @@ -21909,7 +22439,7 @@ mod tests { }; assert_eq!(report.saved_path().is_some(), should_save); let screen = report.render(36, 20, &app.palette).join("\n"); - assert_eq!(screen.contains("feedback@arcships.ai"), should_save); + assert!(!screen.contains(t("Open email draft"))); assert_eq!(screen.contains(t("Draft a GitHub issue")), should_save); assert_eq!(screen.contains(t("Give feedback on Discord")), should_save); if !should_save { diff --git a/crates/dim-report/Cargo.toml b/crates/dim-report/Cargo.toml index d0aad0a372..bfd736b97f 100644 --- a/crates/dim-report/Cargo.toml +++ b/crates/dim-report/Cargo.toml @@ -19,6 +19,8 @@ tokio-util.workspace = true uuid = { workspace = true, features = ["serde"] } base64 = "0.22" jiff.workspace = true +regex = "1" +regex-syntax = "0.8" url = "2" zip = { version = "9.1", default-features = false } diff --git a/crates/dim-report/src/conversation.rs b/crates/dim-report/src/conversation.rs new file mode 100644 index 0000000000..19387fa948 --- /dev/null +++ b/crates/dim-report/src/conversation.rs @@ -0,0 +1,299 @@ +use crate::{ + evidence::ConversationExcerpt, + redaction::{Facts, Replacements, mask_credentials}, +}; +use dim_agent_runtime::QueryEvent; +use dim_agent_types::{ + ContentBlock, ContentMetadata, EventKind, FinishReason, MessagePart, ModelOutputOutcome, + markup::runtime_context, +}; +use regex::Regex; +use std::{collections::HashMap, path::Path, sync::LazyLock}; + +const MAX_SOURCE: usize = 64 * 1024; +const EXCERPT_LIMIT: usize = 2048; +const TOTAL_LIMIT: usize = 8 * 1024; +const WITHHELD: &str = "[excerpt withheld]"; +static CREDENTIAL_FIELD: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r#"(?i)(?:^|[^a-z0-9_-]|\\[rn])"#, + r#"(?:[a-z0-9]+[_-])*"#, + r#"(?:cookie|authorization|api[_-]?key|private[_-]?key|signing[_-]?key"#, + r#"|[a-z0-9_-]*(?:password|passwd|credential|secret|token))"#, + r#"(?:[_-][a-z0-9]+)*(?:\\?["'`])?[ \t]*[:=]"#, + )) + .expect("static credential field pattern") +}); +static COOKIE_FIELD: LazyLock = LazyLock::new(|| { + Regex::new(r#"(?i)(?:^|[^a-z0-9_-]|\\[rn])(?:set-)?cookie(?:\\?["'`])?[ \t]*[:=]"#) + .expect("static cookie field pattern") +}); +static URL_USERINFO: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)[a-z][a-z0-9+.-]*://[^/\s:@]+:[^/\s@]+@").expect("static URL userinfo pattern") +}); +static BEARER_TOKEN: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)(?:^|[^a-z0-9_-])bearer[ \t]+[a-z0-9._~+/-]{20,}={0,2}") + .expect("static bearer token pattern") +}); + +#[derive(Default)] +pub(super) struct Conversation { + redacted: Vec, + unredacted: Vec, +} + +impl Conversation { + pub(super) fn excerpts(&self, redact: bool) -> &[ConversationExcerpt] { + if redact { + &self.redacted + } else { + &self.unredacted + } + } +} + +fn append(text: &mut Option, value: &str) { + if let Some(current) = text { + if value.len() > MAX_SOURCE - current.len() { + *text = None; + } else { + current.push_str(value); + } + } +} + +fn number(facts: &mut Facts, value: &str, kind: &str) -> Option<()> { + if value.len() > 1024 { + return None; + } + if !facts.identifiers.iter().any(|(id, _)| id == value) { + if facts.identifiers.len() >= 64 { + return None; + } + let n = 1 + facts + .identifiers + .iter() + .filter(|(_, label)| label.starts_with(kind)) + .count(); + facts + .identifiers + .push((value.to_owned(), format!("{kind}-{n}"))); + } + Some(()) +} + +pub(super) fn select(events: &[QueryEvent], session: &str, home: &Path) -> Conversation { + let mut facts = Facts { + homes: home.to_str().map(String::from).into_iter().collect(), + session: session.into(), + ..Default::default() + }; + let mut pending = HashMap::new(); + let mut output = None; + let mut excerpts = Vec::new(); + let mut ids_complete = true; + for row in events { + let event = &row.event; + if event.parent_call_id.is_some() { + continue; + } + let selected = match &event.kind { + EventKind::InputMessage(input) => { + if let Some(user) = &input.user { + let mut text = Some(String::new()); + for (index, block) in user.content.iter().enumerate() { + if let ContentBlock::Text { text: value } = block + && !runtime_context(index, value) + { + if text.as_ref().is_some_and(|s| !s.is_empty()) { + append(&mut text, "\n"); + } + append(&mut text, value); + } + } + if let Some(text) = text { + pending.insert(&event.id, text); + } + } + None + } + EventKind::InputConsumed(data) => { + pending.remove(&data.input_id).map(|text| ("user", text)) + } + EventKind::ToolStart(data) => { + ids_complete &= number(&mut facts, &data.call_id, "call").is_some(); + None + } + EventKind::ToolCompleted(data) => { + ids_complete &= number(&mut facts, &data.call_id, "call").is_some(); + None + } + EventKind::ModelStart(data) => { + output = Some((&data.request_id, Some(String::new()))); + None + } + EventKind::Text(data) => { + if let Some((request, text)) = &mut output + && **request == data.request_id + { + append(text, &data.delta); + } + None + } + EventKind::ModelContent(data) => { + let mut text = Some(String::new()); + for part in &data.content { + let metadata = match part { + MessagePart::Text { + text: value, + provider_metadata, + .. + } => { + append(&mut text, value); + provider_metadata + } + MessagePart::ToolUse { + id, + name, + provider_metadata, + .. + } => { + ids_complete &= number(&mut facts, id, "call").is_some(); + ids_complete &= number(&mut facts, name, "tool").is_some(); + provider_metadata + } + MessagePart::Thinking { + provider_metadata, .. + } => provider_metadata, + _ => continue, + }; + if let Some( + ContentMetadata::OpenaiResponses { item_id, .. } + | ContentMetadata::XaiResponses { item_id, .. }, + ) = metadata + { + ids_complete &= number(&mut facts, item_id, "item").is_some(); + } + } + output = Some((&data.request_id, text)); + None + } + EventKind::ModelOutputEnd(data) => output.take().and_then(|(request, text)| { + (*request == data.request_id + && matches!( + data.outcome, + ModelOutputOutcome::Completed { + finish_reason: FinishReason::EndTurn | FinishReason::StopSequence + } + )) + .then_some(text) + .flatten() + .map(|text| ("assistant", text)) + }), + _ => None, + }; + if let Some((role, text)) = selected + && !text.trim().is_empty() + { + excerpts.push((role, event.sequence, text)); + } + } + let selected: Vec<_> = excerpts.into_iter().rev().take(6).collect(); + let kept = selected + .iter() + .map(|(_, _, text)| text.clone()) + .collect::>(); + let rules = ids_complete + .then(|| Replacements::new(&facts, &kept).ok()) + .flatten(); + let mut result = Conversation::default(); + let mut remaining = TOTAL_LIMIT; + for (role, sequence, text) in selected { + if remaining == 0 { + break; + } + let mut raw = guarded(&text); + let mut checked = rules + .as_ref() + .map(|rules| { + let value = rules.text(&raw); + if rules.has_residue(&value) { + WITHHELD.into() + } else { + value + } + }) + .unwrap_or_else(|| WITHHELD.into()); + for text in [&mut raw, &mut checked] { + let cap = text.floor_char_boundary(remaining.min(EXCERPT_LIMIT)); + text.truncate(cap); + } + remaining -= raw.len().max(checked.len()); + result.redacted.push(ConversationExcerpt { + role, + sequence, + text: checked, + }); + result.unredacted.push(ConversationExcerpt { + role, + sequence, + text: raw, + }); + } + result.redacted.reverse(); + result.unredacted.reverse(); + result +} + +fn guarded(value: &str) -> String { + let masked = mask_credentials(value); + let normalized = masked.replace("\r\n", "\n").replace('\r', "\n"); + let mut lines = Vec::new(); + let mut credential_continuation = None; + let mut value_pending = false; + for line in normalized.lines() { + let lower = line.to_ascii_lowercase(); + let field = CREDENTIAL_FIELD.find(&lower); + let indentation = line + .chars() + .take_while(|character| matches!(character, ' ' | '\t')) + .count(); + let continuation = credential_continuation + .is_some_and(|base| !line.trim().is_empty() && indentation > base); + let quoted_continuation = value_pending && line.trim_start().starts_with(['"', '\'', '`']); + let field_value_is_pending = field.is_some_and(|field| { + let value = line[field.end()..].trim(); + value.is_empty() + || matches!(value, "'" | "\"" | "`") + || value.eq_ignore_ascii_case("bearer") + }); + let folded_header = COOKIE_FIELD.is_match(&lower); + if lower.contains("-----begin") && lower.contains("private key") { + lines.push(WITHHELD); + break; + } + let withheld = field.is_some() + || continuation + || quoted_continuation + || URL_USERINFO.is_match(line) + || BEARER_TOKEN.is_match(line) + || lower.contains("-----begin") + || lower.contains("akia") + || lower.contains("eyj"); + if withheld { + lines.push(WITHHELD); + } else { + lines.push(line); + } + + credential_continuation = if field_value_is_pending || folded_header { + Some(indentation) + } else if continuation { + credential_continuation + } else { + None + }; + value_pending = field_value_is_pending; + } + lines.join("\n") +} diff --git a/crates/dim-report/src/draft.rs b/crates/dim-report/src/draft.rs index ad8d9efbfc..67ba2e51fc 100644 --- a/crates/dim-report/src/draft.rs +++ b/crates/dim-report/src/draft.rs @@ -29,6 +29,8 @@ const DRAFT_LIMIT: usize = 16; const INPUT_LIMIT: usize = 1024; pub(super) struct Session { + pub(super) identity: Arc, + pub(super) home: std::path::PathBuf, pub(super) lifecycle: Arc, pub(super) tree: Arc, } @@ -134,6 +136,8 @@ struct PlanRequest { report_id: Uuid, generation: Generation, redact: bool, + #[serde(default)] + include_conversation: bool, instructions: Option, } @@ -144,17 +148,23 @@ struct Plan { evidence: Reviewed, instructions_status: InstructionsStatus, generation: Generation, + #[serde(flatten)] + rendered: render::Rendered, } impl Plan { - fn local(snapshot: &Snapshot, redact: bool, instructions: &str) -> Self { - let (evidence, instructions_status) = render::review(snapshot, redact, instructions); - Self { + fn local( + evidence: Reviewed, + instructions_status: InstructionsStatus, + ) -> Result { + let rendered = evidence.render()?; + Ok(Self { plan_id: Uuid::new_v4(), evidence, instructions_status, generation: Generation::Local, - } + rendered, + }) } } @@ -200,7 +210,7 @@ impl Reports { match method.rsplit('.').next() { Some("prepare") => self.prepare(caller, value).await, - Some("plan") => self.plan(caller.id(), value).await, + Some("plan") => self.plan(caller.id(), value), Some("generate") => self.generate(caller.id(), params(value)?), Some("cancel") => self.cancel(caller.id(), params(value)?), _ => unreachable!("registered report method"), @@ -217,13 +227,13 @@ impl Reports { return Err(RpcError::invalid("Observed error exceeds 1 KiB")); } let Prepare { error } = params(value)?; - let tree = self.session.as_ref().map(|session| &*session.tree); - let (snapshot, default_model) = match (tree, error) { - (_, Some(error)) => error.capture(tree).await?, - (Some(tree), None) => Snapshot::capture_session(tree).await, + let (snapshot, default_model) = match (&self.session, error) { + (session, Some(error)) => error.capture(session.as_ref().map(|s| &*s.tree)).await?, + (Some(session), None) => Snapshot::capture_session(session).await, (None, None) => return Err(RpcError::invalid("Expected an observed error")), }; - let plan = Plan::local(&snapshot, true, ""); + let (evidence, status) = render::review(&snapshot, true, false, ""); + let plan = Plan::local(evidence, status)?; let id = Uuid::new_v4(); let mut answer = json!({"reportId": id, "plan": plan}); if let Some(default_model) = default_model { @@ -279,7 +289,7 @@ impl Reports { Ok(answer) } - async fn plan(&self, caller: &str, value: Value) -> Result { + fn plan(&self, caller: &str, value: Value) -> Result { if let Some(model) = value .pointer("/generation/model") .and_then(Value::as_object) @@ -301,37 +311,18 @@ impl Reports { "Model-assisted reports are unavailable", )); } - let (mut plan, through, branch, previous) = { - let mut drafts = self.drafts.lock().unwrap(); - let draft = get(&mut drafts, caller, request.report_id)?; - if draft.running.is_some() { - return Err(busy()); - } - ( - Plan::local(&draft.snapshot, request.redact, instructions), - draft.snapshot.conversation_through, - draft.snapshot.branch.clone(), - draft.plan.as_ref().map(|plan| plan.plan_id), - ) - }; - if !request.redact - && plan.evidence.includes_timeline() - && let (Some(session), Some(through), Some(branch)) = (&self.session, through, branch) - { - plan.evidence.conversation = - crate::evidence::capture_conversation(&session.tree, &branch, through).await; - } let mut drafts = self.drafts.lock().unwrap(); let draft = get(&mut drafts, caller, request.report_id)?; if draft.running.is_some() { return Err(busy()); } - if draft.plan.as_ref().map(|plan| plan.plan_id) != previous { - return Err(RpcError::service( - "report_plan_stale", - "The report plan has changed or was consumed", - )); - } + let (evidence, status) = render::review( + &draft.snapshot, + request.redact, + request.include_conversation, + instructions, + ); + let plan = Plan::local(evidence, status)?; let response = reply(&plan)?; draft.plan = Some(plan); Ok(response) @@ -359,7 +350,7 @@ impl Reports { }); plan }; - let response = plan.evidence.generate(); + let response = plan.rendered.generate(); let mut drafts = self.drafts.lock().unwrap(); let draft = get(&mut drafts, caller, request.report_id)?; let run = draft diff --git a/crates/dim-report/src/evidence.rs b/crates/dim-report/src/evidence.rs index 1a0f6d914a..2e5b420639 100644 --- a/crates/dim-report/src/evidence.rs +++ b/crates/dim-report/src/evidence.rs @@ -6,9 +6,8 @@ use dim_agent_runtime::{ QuerySpec, TimelineQuery, TimelineQueryScope, }; use dim_agent_types::{ - AgentEvent, BranchCreateFailedData, ContentBlock, DEFAULT_BRANCH_ID, EventKind, FinishReason, - MessagePart, ModelId, ModelOutputOutcome, TimelinePosition, TurnOutcome, - markup::runtime_context, + AgentEvent, BranchCreateFailedData, DEFAULT_BRANCH_ID, EventKind, ModelId, ModelOutputOutcome, + TimelinePosition, TurnOutcome, }; use jiff::Timestamp; use serde::{Deserialize, Serialize}; @@ -89,8 +88,7 @@ impl ErrorReference { error: Some(observed.into()), timeline, client_version, - branch: None, - conversation_through: None, + conversation: Default::default(), }, default_model, )) @@ -192,26 +190,44 @@ pub(super) struct Snapshot { /// The label the reporting client sent for itself, when it sent one: a /// comparison with the daemon's own label is what a report shows. pub(super) client_version: Option, - /// The line the snapshot's conversation was read from, and its cutoff: a - /// report's evidence stays on the line the Session's conversation was on - /// when it was prepared (design §9, §15). - pub(super) branch: Option, - pub(super) conversation_through: Option, + pub(super) conversation: crate::conversation::Conversation, } impl Snapshot { - pub(super) async fn capture_session(tree: &TreeCommands) -> (Self, Option) { + pub(super) async fn capture_session( + session: &crate::draft::Session, + ) -> (Self, Option) { + let tree = &session.tree; let default = tree.default_branch().ok(); let branch = default.as_deref().and_then(|id| tree.get(id).ok()); let conversation_through = branch.as_ref().map(Branch::sequence); + let mut conversation = Default::default(); let timeline = match (default.as_deref(), conversation_through) { - (Some(id), Some(through)) => read_window(tree, id, through, ACTIVITY_KINDS) - .await - .map(|(events, truncated)| { - let (recent, truncated) = excerpt(&events, truncated, true); - TimelineEvidence::Recent { recent, truncated } - }) - .map_err(|_| Missing::ReadFailed), + (Some(id), Some(through)) => read_window( + tree, + id, + through, + &[ + "step/model-start", + "step/tool-start", + "step/tool-completed", + "input/message", + "input/consumed", + "step/text", + "step/model-content", + ], + ) + .await + .map(|(events, truncated)| { + let (recent, truncated) = excerpt(&events, truncated, true); + conversation = crate::conversation::select( + &events, + &session.identity.session_id, + &session.home, + ); + TimelineEvidence::Recent { recent, truncated } + }) + .map_err(|_| Missing::ReadFailed), _ => Err(Missing::ReadFailed), }; let model = branch.as_ref().and_then(adopted_model); @@ -220,8 +236,7 @@ impl Snapshot { error: None, timeline, client_version: None, - branch: default, - conversation_through, + conversation, }, model, ) @@ -236,168 +251,6 @@ pub(super) struct ConversationExcerpt { pub(super) text: String, } -pub(super) async fn capture_conversation( - tree: &TreeCommands, - branch: &str, - through: u64, -) -> Vec { - let Ok((events, _)) = read_window( - tree, - branch, - through, - &[ - "input/message", - "input/consumed", - "step/model-start", - "step/text", - "step/model-content", - ], - ) - .await - else { - return Vec::new(); - }; - let mut excerpts = Vec::new(); - let mut pending = std::collections::HashMap::new(); - let mut output: Option<(String, String)> = None; - for row in events { - let event = row.event; - if event.parent_call_id.is_some() { - continue; - } - let selected = match &event.kind { - EventKind::InputMessage(input) => { - if let Some(user) = &input.user { - let mut text = String::new(); - for (index, block) in user.content.iter().enumerate() { - if let ContentBlock::Text { text: value } = block - && !runtime_context(index, value) - { - append_visible(&mut text, value); - } - if text.len() == 2048 { - break; - } - } - pending.insert(event.id.clone(), text); - } - None - } - EventKind::InputConsumed(data) => { - pending.remove(&data.input_id).map(|text| ("user", text)) - } - EventKind::ModelStart(data) => { - output = Some((data.request_id.clone(), String::new())); - None - } - EventKind::Text(data) => { - if let Some((request, text)) = &mut output - && *request == data.request_id - { - append_bounded(text, &data.delta, 2048); - } - None - } - EventKind::ModelContent(data) => { - let mut text = String::new(); - for part in &data.content { - if let MessagePart::Text { text: value, .. } = part { - append_bounded(&mut text, value, 2048); - } - } - output = Some((data.request_id.clone(), text)); - None - } - EventKind::ModelOutputEnd(data) => output.take().and_then(|(request, text)| { - (request == data.request_id - && matches!( - data.outcome, - ModelOutputOutcome::Completed { - finish_reason: FinishReason::EndTurn | FinishReason::StopSequence - } - )) - .then_some(("assistant", text)) - }), - _ => None, - }; - if let Some((role, text)) = selected { - let mut selected = String::new(); - append_visible(&mut selected, &text); - if !selected.trim().is_empty() { - excerpts.push(ConversationExcerpt { - role, - sequence: event.sequence, - text: selected, - }); - } - } - } - let mut budget = 8 * 1024; - let mut recent = Vec::new(); - for mut excerpt in excerpts.into_iter().rev().take(6) { - if budget == 0 { - break; - } - let mut text = String::new(); - append_bounded(&mut text, &excerpt.text, budget); - excerpt.text = text; - budget -= excerpt.text.len(); - recent.push(excerpt); - } - recent.reverse(); - recent -} - -fn append_bounded(target: &mut String, text: &str, limit: usize) { - let mut end = text.len().min(limit.saturating_sub(target.len())); - while !text.is_char_boundary(end) { - end -= 1; - } - target.push_str(&text[..end]); -} - -fn append_visible(target: &mut String, mut text: &str) { - while !text.is_empty() && target.len() < 2048 { - let end = text.find(['\r', '\n']).unwrap_or(text.len()); - let (line, rest) = text.split_at(end); - let rest = rest.strip_prefix('\r').unwrap_or(rest); - text = rest.strip_prefix('\n').unwrap_or(rest); - let mut bounded = String::new(); - append_bounded(&mut bounded, line, 2048); - if eligible_line(&bounded) { - if !target.is_empty() { - append_bounded(target, "\n", 2048); - } - append_bounded(target, &bounded, 2048); - } - } -} - -fn eligible_line(line: &str) -> bool { - let lower = line.to_ascii_lowercase(); - ![ - "bearer ", - "authorization", - "api_key", - "api-key", - "apikey", - "password", - "secret", - "token=", - "token:", - "sk-", - "ghp_", - "github_pat_", - "xoxb-", - "xoxp-", - "-----begin", - "akia", - "eyj", - ] - .iter() - .any(|pattern| lower.contains(pattern)) -} - fn adopted_model(branch: &Branch) -> Option { let configuration = branch.get::()?.configuration?; Some(ModelId { diff --git a/crates/dim-report/src/lib.rs b/crates/dim-report/src/lib.rs index d956188b05..e51c1e65ba 100644 --- a/crates/dim-report/src/lib.rs +++ b/crates/dim-report/src/lib.rs @@ -1,7 +1,9 @@ //! Connection-bound reports for the App Server's product profiles. +mod conversation; mod draft; mod evidence; +pub mod redaction; mod render; use dim_agent_capabilities::{methods::SessionMethods, timeline_tree::TreeCommands}; @@ -48,6 +50,8 @@ impl DynPlugin for Report { } struct ReportSession { + identity: Key, + platform: Key, methods: Key, lifecycle: Key, tree: Key, @@ -58,6 +62,8 @@ impl ReportSession { Ok(Self { methods: names.key()?, lifecycle: names.key()?, + identity: names.key()?, + platform: names.key()?, tree: names.key()?, }) } @@ -73,6 +79,8 @@ impl DynPlugin for ReportSession { self.methods.erase(), self.lifecycle.erase(), self.tree.erase(), + self.identity.erase(), + self.platform.erase(), ] } @@ -81,6 +89,8 @@ impl DynPlugin for ReportSession { let methods = ctx.require_at(&self.methods)?; let session = draft::Session { lifecycle: ctx.require_at(&self.lifecycle)?, + identity: ctx.require_at(&self.identity)?, + home: ctx.require_at(&self.platform)?.home.clone(), tree: ctx.require_at(&self.tree)?, }; draft::register(ctx, &methods, "session.report", Some(session))?; diff --git a/crates/dim-report/src/redaction.rs b/crates/dim-report/src/redaction.rs new file mode 100644 index 0000000000..4b60e858a9 --- /dev/null +++ b/crates/dim-report/src/redaction.rs @@ -0,0 +1,440 @@ +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt::Write as _; +use std::hash::{BuildHasher, RandomState}; +use std::io::{self, BufRead, Write}; +use std::sync::LazyLock; + +use regex::Regex; +use regex_syntax::hir::{ClassUnicode, ClassUnicodeRange}; +use serde::Deserialize; +use serde_json::json; + +const SESSION: &str = "00000000-0000-4000-8000-000000000000"; +static SECRET: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r"(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{20,}", + r"|AIza[0-9A-Za-z_-]{30,}|gh[pousr]_[A-Za-z0-9]{36,}", + r"|github_pat_[A-Za-z0-9_]{22,}|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}", + r"|xox[baprs]-[A-Za-z0-9-]{10,}", + r"|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}", + r"|-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----" + )) + .expect("static credential pattern") +}); + +pub fn has_secret(value: &str) -> bool { + SECRET.is_match(value) +} + +pub(super) fn mask_credentials(text: &str) -> Cow<'_, str> { + SECRET.replace_all(text, "[credential omitted]") +} + +#[derive(Default, Deserialize)] +pub struct Facts { + pub homes: Vec, + pub session: String, + #[serde(default)] + pub member_sessions: Vec<(String, String)>, + pub identifiers: Vec<(String, String)>, + pub terms: Vec, +} + +fn forms(term: &str) -> [String; 6] { + let quoted = serde_json::to_string(term).expect("JSON string"); + let body = "ed[1..quoted.len() - 1]; + let mut ascii = String::new(); + for c in body.chars() { + if c < '\u{7f}' { + ascii.push(c); + } else { + for unit in c.encode_utf16(&mut [0; 2]) { + write!(ascii, "\\u{unit:04x}").unwrap(); + } + } + } + let mut url = String::new(); + for b in term.bytes() { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { + url.push(char::from(b)); + } else { + write!(url, "%{b:02X}").unwrap(); + } + } + [ + term.into(), + body.into(), + ascii, + term.replace('/', "\\/"), + url, + term.replace('&', "&") + .replace('<', "<") + .replace('>', ">"), + ] +} + +fn encoded_scalar(text: &str) -> Option<(char, usize)> { + if text.starts_with("\\u") { + let unit = |at| { + let digits = text.get(at..at + 4)?; + digits + .bytes() + .all(|b| b.is_ascii_hexdigit()) + .then_some(())?; + u16::from_str_radix(digits, 16).ok() + }; + let first = unit(2)?; + let (scalar, len) = if (0xd800..=0xdbff).contains(&first) { + if text.get(6..8)? != "\\u" { + return None; + } + let second = unit(8)?; + if !(0xdc00..=0xdfff).contains(&second) { + return None; + } + ( + 0x10000 + ((u32::from(first) - 0xd800) << 10) + u32::from(second) - 0xdc00, + 12, + ) + } else { + (u32::from(first), 6) + }; + return Some((char::from_u32(scalar)?, len)); + } + if text.starts_with('%') { + let byte = |at| { + if text.as_bytes().get(at) != Some(&b'%') { + return None; + } + let digits = text.get(at + 1..at + 3)?; + digits + .bytes() + .all(|b| b.is_ascii_hexdigit()) + .then_some(())?; + u8::from_str_radix(digits, 16).ok() + }; + let first = byte(0)?; + let len = match first { + 0x00..=0x7f => return Some((char::from(first), 3)), + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => return None, + }; + let mut bytes = [0; 4]; + bytes[0] = first; + for (i, b) in bytes.iter_mut().enumerate().take(len).skip(1) { + *b = byte(i * 3)?; + } + let c = std::str::from_utf8(&bytes[..len]).ok()?.chars().next()?; + return Some((c, len * 3)); + } + None +} + +fn scalars(text: &str) -> impl Iterator + '_ { + let mut at = 0; + let mut escaped_backslash = false; + std::iter::from_fn(move || { + let tail = &text[at..]; + let (c, len) = if escaped_backslash { + escaped_backslash = false; + ('\\', 1) + } else if tail.starts_with("\\\\") { + escaped_backslash = true; + ('\\', 1) + } else { + encoded_scalar(tail).or_else(|| tail.chars().next().map(|c| (c, c.len_utf8())))? + }; + let start = at; + at += len; + Some((start, c)) + }) +} + +struct Literal { + folded: Box, + rule: usize, + left: bool, + right: bool, +} + +#[derive(Default)] +struct ByLength { + power: u64, + literals: HashMap>, +} + +fn step(hash: u64, base: u64, c: char) -> u64 { + hash.wrapping_mul(base).wrapping_add(c as u64 + 1) +} + +fn boundary_char(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, 'ı' | 'İ' | 'ſ' | 'K') +} + +pub struct Replacements { + lengths: BTreeMap, + base: u64, + starts: HashMap, + fold: HashMap, + rules: Vec<(String, String)>, + homes: Vec, + unreplaced_accounts: BTreeSet, +} + +impl Replacements { + pub fn new(facts: &Facts, kept: &[String]) -> Result { + let mut r = Self { + lengths: BTreeMap::new(), + starts: HashMap::new(), + base: RandomState::new().hash_one(0u8) | 257, + fold: HashMap::new(), + rules: Vec::new(), + homes: Vec::new(), + unreplaced_accounts: BTreeSet::new(), + }; + for home in facts.homes.iter().collect::>() { + let drive = home.as_bytes().get(1) == Some(&b':'); + let windows = drive || home.contains('\\') || home.starts_with("//"); + let separator = |c| c == '/' || (windows && c == '\\'); + let path = home.trim_end_matches(separator); + let tail = if drive { &path[2..] } else { path }; + if windows + && tail.starts_with(['/', '\\']) + && tail.chars().nth(1).is_some_and(separator) + && tail.split(separator).filter(|s| !s.is_empty()).count() <= 2 + { + continue; + } + let user = tail.rsplit(separator).next().unwrap_or(""); + if matches!( + user.to_lowercase().as_str(), + "" | "root" + | "user" + | "admin" + | "ubuntu" + | "debian" + | "ec2-user" + | "runner" + | "vscode" + | "codespace" + | "node" + ) { + continue; + } + let n = user.chars().count(); + let account: String = "user".chars().cycle().take(n).collect(); + let standin = format!("{}{account}", &path[..path.len() - user.len()]); + r.add(path, &standin); + if windows { + r.add(&path.replace('\\', "/"), &standin.replace('\\', "/")); + r.add(&path.replace('/', "\\"), &standin.replace('/', "\\")); + } + r.homes.push(standin); + if n >= 4 { + r.add(user, &account); + } else { + r.unreplaced_accounts.insert(user.into()); + } + } + r.add(&facts.session, SESSION); + for (original, label) in &facts.member_sessions { + r.add(original, label); + } + for (original, label) in &facts.identifiers { + if original.chars().count() >= 8 { + r.add(original, label); + } + } + let secrets: BTreeSet<_> = kept + .iter() + .flat_map(|s| SECRET.find_iter(s).map(|m| m.as_str())) + .collect(); + for (i, s) in secrets.into_iter().enumerate() { + r.add(s, &format!("[secret-{}]", i + 1)); + } + for (i, s) in facts.terms.iter().enumerate() { + r.add(s, &format!("[term-{}]", i + 1)); + } + Ok(r) + } + + fn fold_key(&mut self, c: char) -> char { + if let Some(&key) = self.fold.get(&c) { + return key; + } + if matches!(c, 'I' | 'i' | 'ı' | 'İ') { + self.fold + .extend(['I', 'i', 'ı', 'İ'].map(|variant| (variant, 'i'))); + return 'i'; + } + let mut class = ClassUnicode::new([ClassUnicodeRange::new(c, c)]); + class.case_fold_simple(); + let key = class.ranges()[0].start(); + for range in class.ranges() { + for variant in range.start()..=range.end() { + self.fold.insert(variant, key); + } + } + key + } + + fn add(&mut self, original: &str, label: &str) { + if original.is_empty() || original.to_lowercase() == label.to_lowercase() { + return; + } + let id = self.rules.len(); + self.rules.push((original.into(), label.into())); + let forms = forms(original); + for (i, form) in forms.iter().enumerate() { + if forms[..i].contains(form) { + continue; + } + let mut folded = String::with_capacity(form.len()); + let (mut hash, mut power, mut len) = (0, 1u64, 0); + for (_, c) in scalars(form) { + let key = self.fold_key(c); + folded.push(key); + hash = step(hash, self.base, key); + power = power.wrapping_mul(self.base); + len += 1; + } + let left = folded.starts_with(boundary_char); + if let Some(first) = folded.chars().next() { + *self.starts.entry(first).or_insert(true) &= left; + } + let group = self.lengths.entry(len).or_insert_with(|| ByLength { + power, + ..ByLength::default() + }); + let bucket = group.literals.entry(hash).or_default(); + if !bucket.iter().any(|p| p.folded.as_ref() == folded) { + bucket.push(Literal { + right: folded.ends_with(boundary_char), + folded: folded.into(), + rule: id, + left, + }); + } + } + } + + fn matches<'a>( + &'a self, + text: &'a str, + ) -> impl Iterator { + let mut index = Vec::new(); + let mut folded = String::new(); + let mut hash = 0; + if !self.lengths.is_empty() { + for (at, c) in scalars(text) { + index.push((at, folded.len(), hash)); + let key = self.fold.get(&c).copied().unwrap_or(c); + folded.push(key); + hash = step(hash, self.base, key); + } + } + let count = index.len(); + index.push((text.len(), folded.len(), hash)); + let mut pos = 0; + std::iter::from_fn(move || { + while pos < count { + let start = pos; + pos += 1; + let (at, a, prefix) = index[start]; + let Some(left) = folded[a..].chars().next().and_then(|c| self.starts.get(&c)) + else { + continue; + }; + if *left && folded[..a].ends_with(boundary_char) { + continue; + } + for (&len, group) in self.lengths.range(..=count - start).rev() { + let (end, b, suffix) = index[start + len]; + let hash = suffix.wrapping_sub(prefix.wrapping_mul(group.power)); + if let Some(bucket) = group.literals.get(&hash) { + for p in bucket { + if !(p.left && folded[..a].ends_with(boundary_char) + || p.right && folded[b..].starts_with(boundary_char)) + && *p.folded == folded[a..b] + { + pos = start + len; + let (original, label) = &self.rules[p.rule]; + return Some((at, end, original.as_str(), label.as_str())); + } + } + } + } + } + None + }) + } + + pub fn text(&self, value: &str) -> String { + self.replace(value, |_, _, _, _| {}) + } + + fn replace(&self, value: &str, mut span: impl FnMut(usize, usize, &str, &str)) -> String { + let mut result = String::new(); + let mut at = 0; + for (start, end, original, label) in self.matches(value) { + span(start, end, original, label); + result.push_str(&value[at..start]); + result.push_str(label); + at = end; + } + result.push_str(&value[at..]); + result + } + + pub fn has_residue(&self, value: &str) -> bool { + self.matches(value).next().is_some() || has_secret(value) + } +} + +#[derive(Deserialize)] +struct Init { + facts: Facts, + kept: Vec, +} + +/// Serves a local JSONL pipe. Errors never contain request data. +pub fn serve(input: impl BufRead, mut output: impl Write) -> io::Result<()> { + let mut lines = input.lines(); + let invalid = || io::Error::other("invalid evidence-redact request"); + let Some(line) = lines.next() else { + return Ok(()); + }; + let init: Init = serde_json::from_str(&line?).map_err(|_| invalid())?; + let r = Replacements::new(&init.facts, &init.kept).map_err(|_| invalid())?; + let mut labels = BTreeMap::new(); + for (original, label) in &r.rules { + labels.entry(original).or_insert(label); + } + writeln!( + output, + "{}", + json!({"labels":labels,"homes":r.homes,"unreplaced_accounts":r.unreplaced_accounts,"session":SESSION}) + )?; + output.flush()?; + for line in lines { + let value: String = serde_json::from_str(&line?).map_err(|_| invalid())?; + let mut spans = Vec::new(); + let (mut byte, mut cp) = (0, 0); + let text = r.replace(&value, |start, end, original, label| { + let a = cp + value[byte..start].chars().count(); + cp = a + value[start..end].chars().count(); + byte = end; + spans.push((a, cp, original.to_owned(), label.to_owned())); + }); + writeln!( + output, + "{}", + json!({"text":text,"spans":spans,"secret":has_secret(&value)}) + )?; + output.flush()?; + } + Ok(()) +} diff --git a/crates/dim-report/src/render.rs b/crates/dim-report/src/render.rs index 021a9fd553..416133f2d0 100644 --- a/crates/dim-report/src/render.rs +++ b/crates/dim-report/src/render.rs @@ -77,6 +77,7 @@ pub(super) enum InstructionsStatus { pub(super) fn review( snapshot: &Snapshot, redact: bool, + include_conversation: bool, instructions: &str, ) -> (Reviewed, InstructionsStatus) { let (mut timeline, mut code, mut correlation) = (true, true, true); @@ -128,6 +129,11 @@ pub(super) fn review( .client_version .clone() .filter(|client| *client != identity); + let conversation = if include_conversation && timeline.is_some() { + snapshot.conversation.excerpts(redact).to_vec() + } else { + Vec::new() + }; ( Reviewed { evidence: Evidence { @@ -141,18 +147,23 @@ pub(super) fn review( }, }, unavailable, - conversation: Vec::new(), + conversation, }, status, ) } -impl Reviewed { - pub(super) fn includes_timeline(&self) -> bool { - self.evidence.timeline.is_some() - } +#[derive(Serialize)] +pub(super) struct Rendered { + #[serde(skip)] + title: &'static str, + #[serde(skip)] + body: String, + files: std::collections::BTreeMap<&'static str, String>, +} - pub(super) fn generate(self) -> Result { +impl Reviewed { + pub(super) fn render(&self) -> Result { let (title, version, mut body) = match &self.evidence.captured_error { Some(error) => ( error.summary, @@ -221,7 +232,7 @@ impl Reviewed { } let mut report = format!("# {title}\n\n{body}"); if !self.conversation.is_empty() { - report.push_str("\n## Conversation excerpts\n\nExplicitly included with redaction off. Bounded excerpts; not guaranteed to be sanitized.\n"); + report.push_str("\n## Conversation excerpts\n\nReview these recent messages for private details before sharing.\n"); for excerpt in &self.conversation { writeln!( report, @@ -240,7 +251,20 @@ impl Reviewed { "unavailable": self.unavailable, })) .map_err(|_| failed())?; - let files = [("report.md", report), ("diagnostics.json", diagnostics)]; + Ok(Rendered { + title, + body, + files: std::collections::BTreeMap::from([ + ("report.md", report), + ("diagnostics.json", diagnostics), + ]), + }) + } +} + +impl Rendered { + pub(super) fn generate(self) -> Result { + let Self { title, body, files } = self; let mut zip = ZipWriter::new(Cursor::new(Vec::new())); for (name, content) in &files { zip.start_file(*name, SimpleFileOptions::default()) @@ -260,7 +284,7 @@ impl Reviewed { reply(json!({ "title": title, "body": body, - "files": std::collections::BTreeMap::from(files), + "files": files, "archive": {"filename": "dim-report.zip", "base64": STANDARD.encode(archive)}, "sharing": { "githubIssueUrl": github.as_str(), diff --git a/crates/dim-report/tests/report_flow.rs b/crates/dim-report/tests/report_flow.rs index 8b6a03b57e..219a67f6a9 100644 --- a/crates/dim-report/tests/report_flow.rs +++ b/crates/dim-report/tests/report_flow.rs @@ -30,6 +30,202 @@ use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest}; use tokio_util::sync::CancellationToken; const SECRET: &str = "private-fixture-content"; +const USER_PROMPT: &str = "What happened during this turn?"; + +#[test] +fn evidence_redact_pipe_matches_unicode_variants_at_source_offsets() { + let home = "/Users/İsmail"; + let account = "İsmail"; + let init = json!({ + "facts": {"homes":[home], "session":"", "identifiers":[], "terms":["ısland", "ΟΣ"]}, + "kept": [], + }); + let input = "🧪 /Users/İsmail /users/ismail İsmail ISMAIL ısmail ISLAND ος οσ \\u0130smail \\u0131smail %c4%b0smail %c4%b1smail!"; + let expected = "🧪 /Users/userus /Users/userus userus userus userus [term-1] [term-2] [term-2] userus userus userus userus!"; + let requests = format!("{init}\n{}\n{}\n", json!(input), json!(expected)); + let mut response = Vec::new(); + dim_report::redaction::serve(Cursor::new(requests.as_bytes()), &mut response).unwrap(); + let response: Vec = std::str::from_utf8(&response) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(response.len(), 3); + assert_eq!(response[1]["text"], expected); + let spans = response[1]["spans"].as_array().unwrap(); + let expected_spans = [ + ("/Users/İsmail", home, "/Users/userus"), + ("/users/ismail", home, "/Users/userus"), + ("İsmail", account, "userus"), + ("ISMAIL", account, "userus"), + ("ısmail", account, "userus"), + ("ISLAND", "ısland", "[term-1]"), + ("ος", "ΟΣ", "[term-2]"), + ("οσ", "ΟΣ", "[term-2]"), + ("\\u0130smail", account, "userus"), + ("\\u0131smail", account, "userus"), + ("%c4%b0smail", account, "userus"), + ("%c4%b1smail", account, "userus"), + ]; + assert_eq!(spans.len(), expected_spans.len()); + let mut byte_offset = 0; + for (span, (source, original, replacement)) in spans.iter().zip(expected_spans) { + let start = byte_offset + input[byte_offset..].find(source).unwrap(); + byte_offset = start + source.len(); + let cp_start = input[..start].chars().count(); + let cp_end = cp_start + source.chars().count(); + assert_eq!(*span, json!([cp_start, cp_end, original, replacement])); + } + assert_eq!(response[2]["spans"], json!([])); + + let replacements = dim_report::redaction::Replacements::new( + &dim_report::redaction::Facts { + homes: vec![home.into()], + session: String::new(), + member_sessions: Vec::new(), + identifiers: Vec::new(), + terms: Vec::new(), + }, + &[], + ) + .unwrap(); + for variant in ["\\u0130smail", "\\u0131smail", "%c4%b0smail", "%c4%b1smail"] { + assert!( + replacements.has_residue(variant), + "residue missed: {variant}" + ); + } +} + +#[test] +fn evidence_redact_pipe_bounds_unicode_forms_and_preserves_encoded_spans() { + let long = "IΣKſ".repeat(64); + let mixed = "\\u0130%cf%82Ks".repeat(64); + let punctuation = "I/\\\"\\\nΣ"; + let home = "/Users/İ<&>name"; + let account = "İ<&>name"; + let quoted = serde_json::to_string(punctuation).unwrap(); + let json_body = "ed[1..quoted.len() - 1]; + let sources = [ + mixed, + "ISLAND".into(), + "\\u0131sland".into(), + "%C4%B0SLAND".into(), + "\\uD801\\uDC28".into(), + "%f0%90%90%a8".into(), + punctuation.into(), + json_body.into(), + json_body.replace('Σ', "\\u03c2"), + "I\\/\\\"\\\nΣ".into(), + "%c4%b1%2f%5c%22%5c%0a%cf%82".into(), + "/Users/\\u0131<&>name".into(), + "%c4%b0<&>name".into(), + "\\u0049s%6c%41nd".into(), + "%2FUsers\\u002F%69%3c%26%3ename".into(), + ]; + let labels = [ + "[term-1]", + "[term-2]", + "[term-2]", + "[term-2]", + "[term-3]", + "[term-3]", + "[term-4]", + "[term-4]", + "[term-4]", + "[term-4]", + "[term-4]", + "/Users/useruser", + "useruser", + "[term-2]", + "/Users/useruser", + ]; + let facts = dim_report::redaction::Facts { + homes: vec![home.into()], + session: String::new(), + member_sessions: Vec::new(), + identifiers: Vec::new(), + terms: vec![ + long.clone(), + "island".into(), + "𐐀".into(), + punctuation.into(), + "IΣ".into(), + ], + }; + let replacements = dim_report::redaction::Replacements::new(&facts, &[]).unwrap(); + for source in &sources { + assert!(replacements.has_residue(source), "residue missed: {source}"); + } + let blocked = [ + "xisland", + "islandx", + "\\u0130island", + "island%c4%b1", + "%78island", + "island\\u0078", + "%2569sland", + "\\u005cu0069sland", + r"\\u0069sland", + "\\uD800", + "\\uDC00", + "%c0%af", + "%ed%a0%80", + "%f4%90%80%80", + "%c4%", + ] + .join(" | "); + assert_eq!(replacements.text(&blocked), blocked); + assert!(!replacements.has_residue(&blocked)); + assert_eq!( + replacements.text(r"%28\u0049s%6c%41nd\u0029"), + r"%28[term-2]\u0029" + ); + let input = format!("🧪 {} | {blocked}", sources.join(" | ")); + let expected = format!("🧪 {} | {blocked}", labels.join(" | ")); + let init = json!({ + "facts": {"homes":[home], "session":"", "identifiers":[], "terms":facts.terms}, + "kept": [], + }); + let requests = format!("{init}\n{}\n{}\n", json!(input), json!(expected)); + let mut response = Vec::new(); + dim_report::redaction::serve(Cursor::new(requests.as_bytes()), &mut response).unwrap(); + let response: Vec = std::str::from_utf8(&response) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(response[1]["text"], expected); + let originals = [ + long.as_str(), + "island", + "island", + "island", + "𐐀", + "𐐀", + punctuation, + punctuation, + punctuation, + punctuation, + punctuation, + home, + account, + "island", + home, + ]; + let spans = response[1]["spans"].as_array().unwrap(); + assert_eq!(spans.len(), sources.len()); + let mut at = "🧪 ".len(); + for (((source, label), original), span) in sources.iter().zip(labels).zip(originals).zip(spans) + { + let start = input[..at].chars().count(); + let end = start + source.chars().count(); + assert_eq!(*span, json!([start, end, original, label])); + at += source.len() + " | ".len(); + } + assert_eq!(response[2]["spans"], json!([])); + assert!(!replacements.has_residue(&expected)); +} #[derive(Default)] struct FailedModel(AtomicUsize); @@ -96,8 +292,16 @@ fn report_home() -> tempfile::TempDir { home } -fn report_builder() -> AgentBuilder { +fn report_builder(home: &std::path::Path) -> AgentBuilder { + use dim_agent_capabilities::host_platform::{HostPlatform, ShellStatus}; let mut builder = AgentBuilder::new(AgentConfig::default()); + let mut platform = HostPlatform::current(ShellStatus::Unavailable { + code: "fixture", + reason: "No shell in the report fixture".into(), + }) + .unwrap(); + platform.home = home.to_owned(); + builder.process_value(Arc::new(platform)); defaults::install_with_prompt( &mut builder, Arc::new(EmptyPromptHost), @@ -119,7 +323,7 @@ fn report_builder() -> AgentBuilder { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_report_names_the_daemons_build_and_a_client_of_another_one() { let home = report_home(); - let mut builder = report_builder(); + let mut builder = report_builder(home.path()); defaults::mock_hosts(&mut builder); let server = serve( builder, @@ -206,7 +410,7 @@ async fn a_report_names_the_daemons_build_and_a_client_of_another_one() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn report_rpc_captures_a_session_without_an_error_at_a_fixed_cutoff() { let home = report_home(); - let mut builder = report_builder(); + let mut builder = report_builder(home.path()); defaults::mock_hosts(&mut builder); let server = serve( builder, @@ -249,7 +453,7 @@ async fn report_rpc_captures_a_session_without_an_error_at_a_fixed_cutoff() { owner .rpc( "session.submit", - json!({"sessionId":id,"branchId":"main","text":SECRET}), + json!({"sessionId":id,"branchId":"main","text":USER_PROMPT}), ) .await .unwrap(); @@ -333,7 +537,7 @@ async fn report_rpc_keeps_evidence_private_and_returns_the_reviewed_zip() { r#"{"version":"0.0.1","protocolVersion":4,"sourceCommit":"test"}"#, ) .unwrap(); - let mut builder = report_builder(); + let mut builder = report_builder(home.path()); let model = Arc::new(FailedModel::default()); defaults::mock_hosts_with_model(&mut builder, HistoryRenderer::default(), model.clone()); let server = serve( @@ -374,7 +578,7 @@ async fn report_rpc_keeps_evidence_private_and_returns_the_reviewed_zip() { owner .rpc( "session.submit", - json!({"sessionId":id, "branchId":"main", "text":SECRET}), + json!({"sessionId":id, "branchId":"main", "text":USER_PROMPT}), ) .await .unwrap(); @@ -415,6 +619,8 @@ async fn report_rpc_keeps_evidence_private_and_returns_the_reviewed_zip() { ); assert!(evidence["timeline"].get("correlation").is_none()); assert!(!prepared.to_string().contains(SECRET)); + assert!(!prepared.to_string().contains(USER_PROMPT)); + assert!(evidence.get("conversation").is_none()); let report_id = &prepared["reportId"]; let original = json!({"sessionId":id,"reportId":report_id,"planId":prepared["plan"]["planId"]}); @@ -632,7 +838,7 @@ async fn report_rpc_keeps_evidence_private_and_returns_the_reviewed_zip() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_excludes_unconsumed_inputs_and_multiline_runtime_context() { let home = report_home(); - let mut builder = report_builder(); + let mut builder = report_builder(home.path()); defaults::mock_hosts_with_model( &mut builder, HistoryRenderer::default(), @@ -693,7 +899,7 @@ async fn conversation_excludes_unconsumed_inputs_and_multiline_runtime_context() .rpc("session.report.prepare", json!({"sessionId":id})) .await .unwrap(); - let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false})).await.unwrap(); + let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); let excerpts = plan["evidence"]["conversation"].as_array().unwrap(); assert!( excerpts @@ -734,9 +940,11 @@ async fn conversation_excludes_unconsumed_inputs_and_multiline_runtime_context() } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { +async fn conversation_modes_share_a_cutoff_and_only_attach_text_to_the_report_member() { let home = report_home(); - let mut builder = report_builder(); + let synthetic_home = std::path::Path::new("/Users/İsmail"); + let host_home = synthetic_home.to_str().unwrap(); + let mut builder = report_builder(synthetic_home); defaults::mock_hosts(&mut builder); let server = serve( builder, @@ -767,15 +975,21 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { .await .unwrap(); }; - let prompt = "Explain why the sky is blue in one sentence."; + let prompt = "Confidential fixture: the unreleased project is called Blue Sky."; submit(&mut owner, prompt).await; let prepared = owner .rpc("session.report.prepare", json!({"sessionId":id})) .await .unwrap(); - assert!(!prepared.to_string().contains(prompt)); + let diagnostics_only = |plan: &Value| { + assert!(plan["evidence"].get("conversation").is_none()); + assert!(!plan.to_string().contains(prompt)); + }; + diagnostics_only(&prepared["plan"]); let default = owner.rpc("session.report.generate", json!({"sessionId":id,"reportId":prepared["reportId"],"planId":prepared["plan"]["planId"]})).await.unwrap(); - archive(&default); + let diagnostics = archive(&default); + assert!(diagnostics["evidence"]["timeline"].is_object()); + assert_eq!(prepared["plan"]["files"], default["files"]); assert!(!default.to_string().contains(prompt)); let prepared = owner @@ -783,7 +997,34 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { .await .unwrap(); submit(&mut owner, "LATER-BEFORE-PLAN").await; - let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false})).await.unwrap(); + let plan = async |owner: &mut Client, options: Value| { + let mut request = + json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"}}); + request + .as_object_mut() + .unwrap() + .extend(options.as_object().unwrap().clone()); + owner.rpc("session.report.plan", request).await.unwrap() + }; + let included = plan( + &mut owner, + json!({"redact":true,"includeConversation":true}), + ) + .await; + assert!(included.to_string().contains(prompt)); + for options in [ + json!({"redact":true}), + json!({"redact":false}), + json!({"redact":false,"instructions":"keep timeline, keep conversation"}), + json!({"redact":true,"includeConversation":false}), + ] { + diagnostics_only(&plan(&mut owner, options).await); + } + let plan = plan( + &mut owner, + json!({"redact":false,"includeConversation":true}), + ) + .await; let excerpts = plan["evidence"]["conversation"].as_array().unwrap(); assert!( excerpts @@ -792,6 +1033,12 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { ); assert!(excerpts.iter().any(|entry| entry["role"] == "assistant" && entry["text"] == format!("Echo: {prompt}"))); assert!(!plan.to_string().contains("LATER-BEFORE-PLAN")); + assert!( + plan["files"]["report.md"] + .as_str() + .unwrap() + .contains(prompt) + ); submit(&mut owner, "LATER-BEFORE-GENERATE").await; let generated = owner .rpc( @@ -801,6 +1048,7 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { .await .unwrap(); archive(&generated); + assert_eq!(plan["files"], generated["files"]); let report = generated["files"]["report.md"].as_str().unwrap(); assert!(report.contains(prompt)); assert!(report.contains(&format!("Echo: {prompt}"))); @@ -814,21 +1062,177 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { assert!(!value.to_string().contains("Echo:")); } - submit(&mut owner, "Why did /report return 2/3?\nAuthorization: Bearer fixture-not-a-real-credential\napi_key=fixture-value").await; + let marker = "Why did /report return 2/3?"; + let session_id = id.as_str().unwrap(); + let fake_key = format!("sk-{}", "A".repeat(32)); + let encoded_home = r"%2FUs%65rs\u002F%49sma\u0069l"; + let discussion = + "Discuss Cookie and Set-Cookie handling; the x-cookie header is not a credential field"; + let cookie_fixtures = [ + "fixture-cookie-value", + "fixture-cookie-folded", + "fixture-set-cookie-value", + "fixture-cookie-json", + "fixture-cookie-escaped-header", + "fixture-cookie-next-line-json", + ]; + let folded_fixtures = [ + "fixture-authorization-folded", + "fixture-x-api-key-folded", + "fixture-json-authorization-folded", + ]; + let message = format!( + "{marker} {session_id} at {host_home}/sample.txt; /USERS/ISMAIL/other.txt; owner İsmail, ISMAIL, ısmail; {encoded_home}/mixed.txt\n\ + {fake_key}\nAuthorization: Bearer fixture-not-a-real-credential\nAuthorization: configured\n inline_description: visible-inline-description\nservice_credential = fixture-value\naccess_token = fixture-spaced-value\n\"token\": \"fixture-json-value\"\n\ + Authorization: Bearer\n {}\nX-Api-Key:\n {}\n{{\n \"Authorization\":\n \"{}\",\n \"visible_sibling\": \"visible-sibling\"\n}}\npassword: configured\n description: visible-nested-sibling\nThe authorization flow is documented below.\n\ + cOoKiE: sid={};\r\n\tother={}\n\ + curl -H 'Set-Cookie: sid={}; HttpOnly'\n\ + {{\"Cookie\": \"sid={}\"}}\n\ + HTTP/1.1 200 OK\\r\\nSet-Cookie: sid={}\n\ + {{\"Cookie\":\n\"sid={}\"}}\n{discussion}", + folded_fixtures[0], + folded_fixtures[1], + folded_fixtures[2], + cookie_fixtures[0], + cookie_fixtures[1], + cookie_fixtures[2], + cookie_fixtures[3], + cookie_fixtures[4], + cookie_fixtures[5], + ); + submit(&mut owner, &message).await; let prepared = owner .rpc("session.report.prepare", json!({"sessionId":id})) .await .unwrap(); - let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false})).await.unwrap(); - let preview = plan.to_string(); - assert!(preview.contains("Why did /report return 2/3?")); - for forbidden in ["fixture-not-a-real-credential", "fixture-value"] { - assert!(!preview.contains(forbidden)); + let visible = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); + let checked = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":true,"includeConversation":true})).await.unwrap(); + let selection = |plan: &Value| { + plan["evidence"]["conversation"] + .as_array() + .unwrap() + .iter() + .map(|e| { + ( + e["role"].as_str().unwrap().to_owned(), + e["sequence"].as_u64().unwrap(), + ) + }) + .collect::>() + }; + let no_credentials = |value: &Value| { + let value = value.to_string(); + for forbidden in [ + "fixture-not-a-real-credential", + "service_credential", + "fixture-value", + "fixture-spaced-value", + "fixture-json-value", + fake_key.as_str(), + ] + .into_iter() + .chain(cookie_fixtures) + .chain(folded_fixtures) + { + assert!(!value.contains(forbidden), "fixture leaked: {forbidden}"); + } + }; + for (plan, redact) in [(&visible, false), (&checked, true)] { + no_credentials(plan); + assert_eq!(selection(plan), selection(&visible)); + let conversation = plan["evidence"]["conversation"].as_array().unwrap(); + let report = plan["files"]["report.md"].as_str().unwrap(); + for role in ["user", "assistant"] { + let text = conversation + .iter() + .find(|e| e["role"] == role && e["text"].as_str().unwrap().contains(marker)) + .unwrap()["text"] + .as_str() + .unwrap(); + let line = text.lines().find(|line| line.contains(marker)).unwrap(); + assert!(report.contains(line)); + assert!(line.contains("/sample.txt")); + assert!(text.lines().any(|line| line == discussion)); + assert!(report.contains(discussion)); + assert!(text.contains("visible_sibling")); + assert!(text.contains("visible-nested-sibling")); + assert!(text.contains("visible-inline-description")); + assert!(text.contains("The authorization flow is documented below.")); + assert_eq!(line.contains(encoded_home), !redact); + assert_eq!(line.contains("/Users/userus/mixed.txt"), redact); + assert_eq!(line.contains(session_id), !redact); + assert_eq!(line.contains(host_home), !redact); + for original in ["İsmail", "ISMAIL", "ısmail"] { + assert_eq!(line.contains(original), !redact); + } + if redact { + assert!(line.contains("00000000-0000-4000-8000-000000000000")); + assert!(line.contains("/Users/userus/sample.txt; /Users/userus/other.txt")); + assert!(line.contains("owner userus, userus, userus")); + } + } + assert!( + !plan["files"]["diagnostics.json"] + .as_str() + .unwrap() + .contains(marker) + ); + } + let stale = owner + .rpc( + "session.report.generate", + json!({"sessionId":id,"reportId":prepared["reportId"],"planId":visible["planId"]}), + ) + .await + .unwrap_err(); + assert_eq!(app_error(&stale), Some("report_plan_stale")); + let generated = owner + .rpc( + "session.report.generate", + json!({"sessionId":id,"reportId":prepared["reportId"],"planId":checked["planId"]}), + ) + .await + .unwrap(); + archive(&generated); + no_credentials(&generated); + assert_eq!(checked["files"], generated["files"]); + for surface in [ + &generated["files"]["diagnostics.json"], + &generated["body"], + &generated["sharing"], + ] { + assert!(!surface.to_string().contains(marker)); + assert!(!surface.to_string().contains("Echo:")); + } + let prepared = owner + .rpc("session.report.prepare", json!({"sessionId":id})) + .await + .unwrap(); + let unchecked = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); + let raw_zip = owner + .rpc( + "session.report.generate", + json!({"sessionId":id,"reportId":prepared["reportId"],"planId":unchecked["planId"]}), + ) + .await + .unwrap(); + archive(&raw_zip); + no_credentials(&raw_zip); + assert_eq!(raw_zip["files"], visible["files"]); + assert_eq!( + raw_zip["files"]["diagnostics.json"], + generated["files"]["diagnostics.json"] + ); + let prepared = owner + .rpc("session.report.prepare", json!({"sessionId":id})) + .await + .unwrap(); + for redact in [true, false] { + let omitted = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":redact,"includeConversation":true,"instructions":"omit timeline"})).await.unwrap(); + assert!(omitted["evidence"].get("conversation").is_none()); + assert!(omitted["evidence"].get("timeline").is_none()); + assert!(!omitted["files"].to_string().contains(marker)); } - let hidden = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":true})).await.unwrap(); - assert!(hidden["evidence"].get("conversation").is_none()); - let omitted = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"instructions":"omit timeline"})).await.unwrap(); - assert!(omitted["evidence"].get("conversation").is_none()); for (label, eol) in [("LF", "\n"), ("CRLF", "\r\n"), ("CR", "\r")] { let message = format!("Example {label}{eol}{eol}# Literal heading"); submit(&mut owner, &message).await; @@ -836,7 +1240,7 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { .rpc("session.report.prepare", json!({"sessionId":id})) .await .unwrap(); - let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false})).await.unwrap(); + let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); let generated = owner .rpc( "session.report.generate", @@ -855,7 +1259,33 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { } assert!(!report.contains('\r')); } - let long = "合成可见文本".repeat(3000); + for sensitive in [ + format!("{}sk-{}", "x ".repeat(1006), "B".repeat(40)), + format!( + "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----", + "BOUNDARYKEYDATA".repeat(160) + ), + ] { + submit(&mut owner, &format!("Boundary example\n{sensitive}")).await; + let prepared = owner + .rpc("session.report.prepare", json!({"sessionId":id})) + .await + .unwrap(); + let unchecked = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); + let checked = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":true,"includeConversation":true})).await.unwrap(); + for plan in [&checked, &unchecked] { + let conversation = plan["evidence"]["conversation"].as_array().unwrap(); + assert!( + conversation + .iter() + .any(|e| e["text"].as_str().unwrap().contains("Boundary example")) + ); + for forbidden in ["sk-B", "BOUNDARYKEYDATA", "END PRIVATE KEY"] { + assert!(!plan.to_string().contains(forbidden)); + } + } + } + let long = "合成可见文本".repeat(300); for _ in 0..4 { submit(&mut owner, &long).await; } @@ -863,8 +1293,9 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { .rpc("session.report.prepare", json!({"sessionId":id})) .await .unwrap(); - let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false})).await.unwrap(); + let plan = owner.rpc("session.report.plan", json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":false,"includeConversation":true})).await.unwrap(); let excerpts = plan["evidence"]["conversation"].as_array().unwrap(); + assert!(prepared["plan"]["evidence"].get("conversation").is_none()); assert!(!excerpts.is_empty()); assert!(excerpts.len() <= 6); let mut total = 0; @@ -896,3 +1327,164 @@ async fn conversation_text_is_opt_in_anchored_and_only_in_the_report_member() { server.shutdown(); server.join().await.unwrap(); } + +#[tokio::test] +async fn recognized_credentials_are_withheld_from_both_conversation_modes() { + let home = report_home(); + let synthetic_home = std::path::Path::new("/Users/İsmail"); + let mut builder = report_builder(synthetic_home); + defaults::mock_hosts(&mut builder); + let server = serve( + builder, + ServerConfig { + platform_home: Some(home.path().into()), + unix_path: Some(home.path().join("server.sock")), + ..Default::default() + }, + ) + .await + .unwrap(); + let mut owner = connect(&server).await; + let created = owner + .rpc("session.create", json!({"cwd":home.path(),"tools":[]})) + .await + .unwrap(); + let id = &created["sessionId"]; + let marker = "recognized-credential-fixture"; + let stripe = "sk_live_51abcdefghijklmnopqrstuv"; + let google = "AIzaSyA1234567890abcdefghijklmnopqrstu"; + let asia = "ASIA1234567890ABCDEF"; + let userinfo = "https://alice:pw123@internal.example/api"; + let bearer = "Bearer abcdefghijklmnopqrstuvwxyz"; + let aws = "aws-secret-fixture"; + let aws_json = "json-secret-fixture"; + let secret_key = "secret-key-fixture"; + let private_key = "private-key-fixture"; + let signing_key = "signing-key-fixture"; + let groq = "gsk_fixture"; + let proxy = "cHJveHk6cHc="; + let access = "compact-access-fixture"; + let client = "compact-client-fixture"; + let refresh = "compact-refresh-fixture"; + let prose = "Secretary: available"; + let visible = "credential-fixture-visible-tail"; + let message = format!( + "{marker}\n{stripe}\n{google}\n{asia}\n{userinfo}\n{bearer}\n\ + aws_secret_access_key = {aws}\n\"aws_secret_access_key\": \"{aws_json}\"\n\ + secret_key = {secret_key}\nprivate_key = {private_key}\n\ + signing_key = {signing_key}\nGROQ_API_KEY={groq}\n\ + Proxy-Authorization: Basic {proxy}\n\"accessToken\": \"{access}\"\n\ + clientSecret: {client}\nrefreshToken = {refresh}\n{prose}\n{visible}" + ); + owner + .rpc( + "session.submit", + json!({"sessionId":id,"branchId":"main","text":message}), + ) + .await + .unwrap(); + owner + .rpc("session.idle", json!({"sessionId":id,"branchId":"main"})) + .await + .unwrap(); + for redact in [false, true] { + let prepared = owner + .rpc("session.report.prepare", json!({"sessionId":id})) + .await + .unwrap(); + let plan = owner + .rpc( + "session.report.plan", + json!({"sessionId":id,"reportId":prepared["reportId"],"generation":{"kind":"local"},"redact":redact,"includeConversation":true}), + ) + .await + .unwrap(); + let text = plan.to_string(); + for secret in [ + stripe, + google, + asia, + userinfo, + bearer, + aws, + aws_json, + secret_key, + private_key, + signing_key, + groq, + proxy, + access, + client, + refresh, + ] { + assert!( + !text.contains(secret), + "plan leaked {secret} with redact={redact}" + ); + } + assert!(text.contains(marker), "marker missing with redact={redact}"); + assert!( + text.contains(prose), + "ordinary prose missing with redact={redact}" + ); + assert!( + text.contains(visible), + "visible tail missing with redact={redact}" + ); + assert!( + text.contains("[credential omitted]"), + "mask missing with redact={redact}" + ); + assert!( + text.contains("[excerpt withheld]"), + "withheld line missing with redact={redact}" + ); + let generated = owner + .rpc( + "session.report.generate", + json!({"sessionId":id,"reportId":prepared["reportId"],"planId":plan["planId"]}), + ) + .await + .unwrap(); + archive(&generated); + assert_eq!(plan["files"], generated["files"]); + let text = generated.to_string(); + for secret in [ + stripe, + google, + asia, + userinfo, + bearer, + aws, + aws_json, + secret_key, + private_key, + signing_key, + groq, + proxy, + access, + client, + refresh, + ] { + assert!( + !text.contains(secret), + "ZIP leaked {secret} with redact={redact}" + ); + } + assert!( + generated["files"]["report.md"] + .as_str() + .unwrap() + .contains(marker) + ); + assert!( + generated["files"]["report.md"] + .as_str() + .unwrap() + .contains(prose) + ); + } + drop(owner); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/crates/dimcode/src/main.rs b/crates/dimcode/src/main.rs index addb811e02..7f19b49826 100644 --- a/crates/dimcode/src/main.rs +++ b/crates/dimcode/src/main.rs @@ -83,6 +83,13 @@ fn main() { mallopt(-3, 64 * 1024); mallopt(-8, 1); } + if std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new("evidence-redact")) { + if dim_report::redaction::serve(std::io::stdin().lock(), std::io::stdout().lock()).is_err() + { + std::process::exit(1); + } + return; + } if std::env::args().nth(1).as_deref() == Some("ocr-helper") { let mut stdout = std::io::stdout(); let mut stderr = std::io::stderr(); diff --git a/docs/INDEX.md b/docs/INDEX.md index 13b16e09be..734197b165 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -134,6 +134,8 @@ This index is navigation. Delivery status lives in issues, not here. - [Idle Session unload](design/appserver/idle-unload.md) (#126, #331)([中文](zh/design/appserver/idle-unload.md)) - [Request delta storage](design/appserver/request-delta-storage.md) (#193)([中文](zh/design/appserver/request-delta-storage.md)) - [Timeline export](design/appserver/timeline-export.md) (ADR 005 D3, #275)([中文](zh/design/appserver/timeline-export.md)) +- [Badcase 评测流水线](eval/usercases-pipeline.md)(中文,#1701):用户提交、dogfood 与公开 issue 三个来源的证据包与授权、分诊去向、区分度证明、按根案例读结果、闭环与撤回 +- [证据包打包](eval/evidence-pack.md)(中文,#1701):Timeline 进证据包之前在本机的分级披露、标识替换与输出校验 - [Release packaging and self-hosted workflows](release/README.md) - [Container image release](release/docker-image.md) (Draft): the proposed ghcr.io image for the Linux executable, its volumes, clients, build from original release archives and security boundary - [Tool origin read](design/tool-origin-read.md) — point lookup for tool arguments outside a transcript window. diff --git a/docs/design/plugins/Report.md b/docs/design/plugins/Report.md index 456b8e3be9..393c833f3c 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -36,40 +36,41 @@ Both modes show `Run /report to create a report.` below reportable errors. When +-- Report this session ---------------------------------------+ | Session model provider/model | | Local ZIP. Nothing is uploaded. | -| Diagnostics only. Uncheck Redact to include recent messages. | -| > Model: Generate locally | +| Diagnostics only unless you include conversation. | +| report.md: | +| diagnostics.json: | +| > Local attachment preview (Enter to read both files) | | Redact [x] | -| Options | -| Generate report | -| Close | +| [ ] Include conversation | +| Mail purpose: (*) This issue only | +| ( ) This issue + internal regression | +| Open email draft | +| Options / Generate report / Close | +--------------------------------------------------------------+ -+-- Report ready ----------------------------------------------+ -| Saved ZIP | -| Email the ZIP to feedback@arcships.ai | -| | -| ZIP contents: report.md, diagnostics.json | -| > Save ZIP | -| Draft a GitHub issue | -| Give feedback on Discord | -| Close | ++-- After opening the email draft -----------------------------+ +| To: feedback@arcships.ai | +| Subject: Dim report | +| Purpose: | +| SHA-256: | +| Attach in your email app, then send. | +--------------------------------------------------------------+ ``` -The error-only overlay uses `Report this error`. The Session overlay shows when the Timeline could not be read or the bounded excerpt has no reportable activity. Either state permits generation. Local generation is available on its own. Clients can expose a model picker once the one-shot operation in §7 is available. Its initial model is the adopted model of the referenced branch, or of the Session's main branch when there is no branch reference. It also offers models from the client's admitted catalog and **Generate locally**. Redaction starts checked on every new report: Generate then Save ZIP produces diagnostics only. Before generation, the Session dialog explains that turning redaction off may include sensitive text from recent user and assistant messages. An error-only report has no conversation to attach. Generating and saving never send a report to a feedback destination. Options accepts a short instruction about what to omit or keep. There are no required fields. With a model selected, the dialog exposes the exact model material and limits before Generate can send it. Local mode displays zero model requests. After a stale plan or a failed generation, the client offers to refresh the plan. When the draft expires, the client offers to prepare a report for the original target and reapplies the chosen options. +The error-only overlay uses `Report this error`. The Session overlay shows when the Timeline could not be read or the bounded excerpt has no reportable activity. Either state permits generation. Local generation is available on its own. Clients can expose a model picker once the one-shot operation in §7 is available. Its initial model is the adopted model of the referenced branch, or of the Session's default branch when there is no branch reference. It also offers models from the client's admitted catalog and **Generate locally**. Every report starts with diagnostics only and redaction on. In a Session report, selecting **Include conversation** adds recent user and assistant excerpts to the attachment preview. Turning redaction off changes how included evidence is shown; it does not select conversation. Both modes require inspection before sharing. An error-only report has no conversation to attach. Generating and saving never send a report to a feedback destination. Options accepts a short instruction about what to omit or keep. There are no required fields. With a model selected, the dialog exposes the exact model material and limits before Generate can send it. Local mode displays zero model requests. After a stale plan or a failed generation, the client offers to refresh the plan. When the draft expires, the client offers to prepare a report for the original target and reapplies the chosen options. -The overlay follows the TUI's focus and list conventions. Up and Down move between controls, and Tab and Shift+Tab cycle focus. Enter activates the focused control. Esc closes a picker first, cancels generation while busy, or closes the report. Focus starts on Model. The TUI shortens the error and report title to fit the overlay and keeps the focused action visible. The result lists the archive contents and shows the saved path so users can inspect the files with their own tools. Place `/report` immediately before `/exit` in both curated menus with the description `report the current session`, following the existing exact-name, Enter and Tab behavior. The CLI command owner owns the menu (§7). [TUI design](Tui.md), [command menu contract](../cli-commands.md#command-menu). +The overlay follows the TUI's focus and list conventions. Up and Down move between controls, and Tab and Shift+Tab cycle focus. Enter activates the focused control. Esc closes a picker first, cancels generation while busy, or closes the report. Focus starts on the local attachment preview; Enter opens both complete files for scrolling. The TUI shortens the error and report title to fit the overlay and keeps the focused action visible. The result lists the archive contents and shows the saved path so users can inspect the files with their own tools. Place `/report` immediately before `/exit` in both curated menus with the description `report the current session`, following the existing exact-name, Enter and Tab behavior. The CLI command owner owns the menu (§7). [TUI design](Tui.md), [command menu contract](../cli-commands.md#command-menu). ## 3. Evidence and redaction -For a report about the Session, the admitted Session is the entire client-supplied reference. The Report part captures recent activity from its main branch at the published head. Error actions can supply a typed Timeline failure reference with an observed-error fallback, or an observed error alone. A typed reference contains the branch and committed sequence in the admitted Session. An observed error contains a registered client operation, a stable error code if present, the observation time and the client version. The client keeps the displayed message for the dialog. The report projects a stable operation summary and registered error code from that input. Unknown codes collapse to a generic failure for that operation. The request has no field for that message, since an error string can contain a credential, provider response or file path. +For a report about the Session, the admitted Session is the entire client-supplied reference. The Report part captures recent activity from its default branch at the published head. Error actions can supply a typed Timeline failure reference with an observed-error fallback, or an observed error alone. A typed reference contains the branch and committed sequence in the admitted Session. An observed error contains a registered client operation, a stable error code if present, the observation time and the client version. The client keeps the displayed message for the dialog. The report projects a stable operation summary and registered error code from that input. Unknown codes collapse to a generic failure for that operation. The request has no field for that message, since an error string can contain a credential, provider response or file path. Project only the following fields, with their provenance, into the snapshot. | Source | Fields | | --- | --- | -| Current Session's main branch, when readable | Up to 16 recent turn, model, tool and branch lifecycle records reduced to event kind, timestamp, sequence and registered outcome. Successful, failed and cancelled activity are eligible. | -| Current Session, only when redaction is turned off | Up to six recent user/assistant excerpts from the same main-branch cutoff, at most 2 KiB each and 8 KiB total. Only `report.md` includes them, as literal text; the diagnostic schema and sharing summary do not. | +| Current Session's default branch, when readable | Up to 16 recent turn, model, tool and branch lifecycle records reduced to event kind, timestamp, sequence and registered outcome. Successful, failed and cancelled activity are eligible. | +| Current Session, local plan with conversation explicitly included and Timeline not omitted | Up to six recent user/assistant excerpts from the same default-branch cutoff, at most 2 KiB each and 8 KiB total. Redaction replaces identifiers in those excerpts; it does not change which messages are selected. Only `report.md` includes them, as literal text. | | Captured error | Operation, registered error code, UTC observation time, fixed diagnostic summary | | Error's referenced branch, when readable | The referenced terminal failure, time, verified correlation IDs and up to 16 nearby committed failure or lifecycle records reduced to event kind, timestamp, sequence and registered outcome | | Process diagnostics | The daemon build's display label and protocol version, platform, the reporting client's label when it differs from the daemon's, and typed diagnostic metadata only when the owner supplies it for this error | @@ -77,7 +78,7 @@ Project only the following fields, with their provenance, into the snapshot. The Timeline read is branch-local and bounded by 32 candidate events ending at the captured head or the referenced failure. Validate that a failure reference resolves to a reportable failure in that branch. An observed-only error has no Timeline anchor. An unavailable reference, failed read or unavailable diagnostics source leaves the observed error intact. A successful Session read with zero eligible records is an empty excerpt. The process entry performs zero Session reads. Preparation reads published evidence without interrupting or rerunning work and uses only the admitted Session. [Timeline read ownership](../timeline-read-ownership.md), [observability boundaries](../../adr/005-observability.md#d1-two-observation-layers). -Diagnostics never include message bodies, raw logs, workspace files, tool input or output, or raw model requests. Their fields come from typed sources or fixed renderings, and correlation IDs come from verified metadata. With redaction on, remove correlation IDs and do not select conversation text. Only an explicit local plan with redaction off may add a recent excerpt to the Session report. Do not collect hidden reasoning, tool calls or results, attachments, instructions, or full history for the excerpt. User and assistant text can itself contain sensitive details; the user should inspect the ZIP before attaching it. Options maps recognized omit or keep instructions to field directives and shows unsupported instructions in the dialog. A keep directive cannot override redaction. The generation result cannot add new evidence. +Diagnostics never include message bodies, raw logs, workspace files, tool input or output, or raw model requests. Their fields come from typed sources or fixed renderings, and correlation IDs come from verified metadata. The Session draft captures eligible excerpts at prepare time, but excludes them from both preview and ZIP until the user selects them. Redaction on removes diagnostic correlation IDs and uses the [evidence-pack text replacements](../../eval/evidence-pack.md) on whole selected messages before cutting display excerpts. The offline packer and the report use one native replacement implementation. The report knows the admitted Session ID, the host home and identifiers from typed records in the bounded window; it does not scan the full export or import packer decisions. Turning redaction off bypasses those replacements, not the report's credential guard. Neither mode includes recognizable credentials, credential-like lines or unreviewably large candidates. If replacement fails it must never show the original as a redacted result. Do not collect hidden reasoning, tool calls or results, attachments, instructions, or full history for the excerpt. User and assistant text can itself contain sensitive details; the user should inspect the ZIP before attaching it. Options maps recognized omit or keep instructions to field directives and shows unsupported instructions in the dialog. A keep directive cannot override redaction. The generation result cannot add new evidence. ## 4. Report methods @@ -86,13 +87,15 @@ Register the Session namespace in `sessionMethods` and discover it via `session. | Method | Inputs | Reply | | --- | --- | --- | | `prepare` | Session calls accept optional `error`. Omit it for a report on the admitted Session. When supplied, `error` is `{kind: "timeline", branchId, sequence, observed}` or `{kind: "observed", observed}`. The process part requires `error` in the observed variant. | `{reportId, defaultModel?, plan}`. Evidence availability is included in the plan. The default plan lets the dialog open with a preview without an extra round trip. | -| `plan` | `{reportId, generation, redact, instructions?}`, with generation `{kind: "local"}` or `{kind: "model", model: {providerId, modelId}}` | `{planId, generation, evidence, instructionsStatus}`. A model plan includes `material`, `maxOutputTokens` and `estimatedCost` as `{amount, currency}` or `null` for unknown. A successful replacement invalidates the previous plan. | +| `plan` | `{reportId, generation, redact, includeConversation?, instructions?}`, with generation `{kind: "local"}` or `{kind: "model", model: {providerId, modelId}}` | `{planId, generation, evidence, instructionsStatus, files}` for a local plan; `files` contains the preview text for both ZIP members. A model plan includes `material`, `maxOutputTokens` and `estimatedCost` as `{amount, currency}` or `null` for unknown. A successful replacement invalidates the previous plan. | | `generate` | `{reportId, planId}` | `{title, body, files: {"report.md", "diagnostics.json"}, archive: {filename, base64}, sharing: {githubIssueUrl, discordUrl, description}}` | | `cancel` | `{reportId, target: "generation", planId}` or `{reportId, target: "report"}` | `{cancelled: boolean}`. Generation cancellation affects only the named in-flight plan and keeps the evidence available for a new plan. An inactive plan returns `{cancelled: false}`. Report cancellation drops the draft. | The TUI omits `error` for a Session report and sends the `observed` variant to the process entry for a conversation-open failure. Clients with an error-bound action, such as the Desktop and Web action in §2, can use the `timeline` variant to attach a known failure position in an admitted Session. -The local plan uses `generation: {kind: "local"}`. The `evidence` object includes the filtered diagnostic sources and a Timeline availability reason when activity records are absent. For a Session report, only a local plan with `redact: false` and Timeline enabled may also return `evidence.conversation` (an ordered array of `{role, sequence, text}`); the field is absent if no eligible text is available. `generate` renders that plan without reading later messages. Options recognizes comma- or newline-separated `omit` and `keep` directives for `timeline`, `error codes`, and `correlation ids`. The reply reports `instructionsStatus` as `none`, `applied`, `partially_applied`, or `unsupported`. It does not echo the entered text. Redaction always removes correlation IDs, so `keep correlation ids` is unsupported while redaction is on. +The local plan uses `generation: {kind: "local"}`. The `evidence` object includes the filtered diagnostic sources and a Timeline availability reason when activity records are absent. The default plan contains no conversation. A Session plan returns `evidence.conversation` (an ordered array of `{role, sequence, text}`) only when `includeConversation` is `true`, Timeline is included and eligible text is available. Omitting the flag means `false` on each request, regardless of `redact`, instructions or any preceding plan. `generate` renders that plan without reading later messages. Options recognizes comma- or newline-separated `omit` and `keep` directives for `timeline`, `error codes`, and `correlation ids`. The reply reports `instructionsStatus` as `none`, `applied`, `partially_applied`, or `unsupported`. It does not echo the entered text. Redaction always removes correlation IDs, so `keep correlation ids` is unsupported while redaction is on. + +Older servers reject the new flag and may include conversation in an unredacted Session plan. The CLI omits the flag only when omission is safe on both servers. It does not retry a rejected request without the flag. The observed error contains `operation` (`session_read`, `session_fork`, `branch_create` or `model_generation`), `code?`, `observedAt` (UTC timestamp) and `clientVersion` (the reporting client's build label, as the client's own `--version` prints it). No reader orders or compares it; it is display only. These fields carry neither Session authority nor a provider connection. The report ID and plan ID are opaque. Access requires the same caller connection and, for a Session draft, the same admitted Session. A missing, expired or foreign draft returns `report_not_found`. Invalid fields return `invalid_params`. A replaced or consumed plan returns `report_plan_stale`. A concurrent generation returns `report_busy`. A missing or changed model selection returns `report_model_unavailable` before a request. The other execution failures use `report_generation_failed` or `report_cancelled`. Error messages use stable summaries. Prepare returns a local plan when no usable model is available and retains the adopted model identity when known. @@ -116,7 +119,9 @@ Build `report.md` and versioned `diagnostics.json` from the same approved conten | Draft a GitHub issue | Open an issue draft on `arcships/dim` with a diagnostic title and summary only. The user decides whether to attach the ZIP and submit the issue. | | Give feedback on Discord | Open the [Dim Discord invite](https://discord.gg/ds35K3TadP) and copy the diagnostic summary only. The user chooses whether and where to post it or attach the ZIP. | -After a successful save, both TUI modes show a hint below the saved path. Users can attach the saved ZIP to an email to `feedback@arcships.ai`. +Email is a client action, not an upload. Both TUI modes preview the local plan's `report.md` and `diagnostics.json`; changing conversation inclusion or redaction replaces the preview. Use the same file rendering for preview and generation. An unavailable or pending preview must never show a previous unredacted plan. In the same flow users select one mail purpose: report only (default), or report plus team-internal regression evaluation of this attachment. The choice neither selects more evidence nor changes the ZIP. It does not authorize external model providers, training or public release. + +Open email draft saves the reviewed ZIP locally if needed, then opens the user's mail composer addressed to `feedback@arcships.ai`. Only the selected scope and SHA-256 identifying the attachment belong in the draft text, never report contents or a local path in the URI. Show the ZIP path for manual attachment; opening a composer does not send. The result page also offers email when the generated files match the preview. After inspecting the files or retrying a failed save, use the same saved ZIP. If no handler opens, retain the file and let the user reopen the details for manual composition. The recipient must verify scope and digest before reuse. This is not consent for a full Timeline evidence pack, and the public sharing actions do not carry the private evaluation authorization. The client keeps the completed preview and bytes when a share action fails. The plugin cannot publish an issue or upload an archive. The browser flow is sufficient without an authenticated `gh`. [GitHub's attachment flow](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files). @@ -130,7 +135,7 @@ The client keeps the completed preview and bytes when a share action fails. The ## 8. Dependencies and rule check -The Session part declares the `sessionMethods`, `sessionLifecycle` and `treeCommands` data faces. It uses the [public branch read surface](../timeline-read-ownership.md#8-binding-appendix) for the published cutoff and adopted model selection. The process part declares the `managementMethods` and `partRegistry` data faces. Both use caller origin and the process build metadata already available to App Server. With no approved typed diagnostics source, build and platform information are sufficient process evidence. Model-assisted generation depends on the model owners in §7. App Server composes the parts as one feature. [Service catalog](../../architecture/rust-agent/generated/catalog.md). +The Session part declares `sessionMethods`, `sessionLifecycle`, `treeCommands`, `sessionIdentity` and `hostPlatform`. Only the admitted Session ID and the platform's home path are used to recognize identifiers; neither service's full data is included in the report. It uses the [public branch read surface](../timeline-read-ownership.md#8-binding-appendix) for the published cutoff and adopted model selection. The process part declares the `managementMethods` and `partRegistry` data faces. Both use caller origin and the process build metadata already available to App Server. With no approved typed diagnostics source, build and platform information are sufficient process evidence. Model-assisted generation depends on the model owners in §7. App Server composes the parts as one feature. [Service catalog](../../architecture/rust-agent/generated/catalog.md). | Rule | Check | | --- | --- | @@ -147,11 +152,12 @@ The Session part declares the `sessionMethods`, `sessionLifecycle` and `treeComm ## 9. Verification - Exercise `/report` in both TUI modes with an error-free Session, during a running turn, and after switching from a Session with an earlier error. Verify that the report stays bound to the Session selected when it opened and that a fresh command targets the newly shown Session. Cover Home with and without a failed conversation open. -- Generate a ZIP from a Session with successful and repeated activity. Verify the excerpt comes from the main branch at the captured head, excludes later activity, respects the window and record bounds, and supports an empty excerpt. Verify both archive versions through their corresponding prepare inputs. +- Generate a ZIP from a Session with successful and repeated activity. Verify the excerpt comes from the default branch at the captured head, excludes later activity, respects the window and record bounds, and supports an empty excerpt. Verify both archive versions through their corresponding prepare inputs. - Exercise a failed authorized history read and failed Session admission separately. Confirm the process route does not read Session data, the local Web route requires authentication, and guessed, foreign or stale report IDs do not expose drafts. -- Seed distinct markers in public conversation text, hidden fields, raw tool output and source errors. Verify no marker reaches the default ZIP; only the opted-in user and assistant text appears in `report.md`, never in `diagnostics.json`, the GitHub URL or the Discord description. Turn redaction back on and verify the new plan omits the excerpt. Compare both returned preview files byte-for-byte with the archive entries. +- Seed distinct markers in public conversation text, hidden fields, raw tool output and source errors. Verify the default preview and ZIP contain no conversation, including after changing redaction or instructions alone. Opt in and check that only `report.md` includes visible excerpts, with known identifiers replaced. Toggle redaction: the same sequences remain, and only the unredacted plan retains original identifiers. Neither mode exposes hidden markers. Neither mode puts conversation in `diagnostics.json`, the GitHub URL or the Discord description. Compare both returned preview files byte-for-byte with the archive entries. - Use a counting provider to verify zero local requests, one model request after Generate, and no retry after a failed or duplicate call. Verify cancellation, expiry, close and reconnect settle work, discard late output and allow local generation from the same evidence while the draft remains open. A late cancellation for a settled plan leaves its successor running. - Generate a report on a daemon and confirm its `Dim` line carries the same label the binary prints, and that a client whose `clientVersion` names another build adds one `Client` line, in the body and in `evidence.process.clientVersion`. `crates/dim-report/tests/report_flow.rs` covers this at RPC level; `crates/dimcode/tests/cli_flow/report.rs` covers the product daemon and binary. +- Use a synthetic ZIP and an intercepted mail handler for both TUI modes. Check the default and opted-in purposes, the exact ZIP digest, and that no conversation, local path or report-derived subject enters the URI. A missing or mismatched preview disables the email action. A missing handler leaves the saved ZIP and manual composition details available. Do not send mail in these tests. - Save a report ZIP on a client connected to another host and exercise the GitHub draft and Discord flows without `gh`. Verify explicit sharing follows review or local save and that a failed share leaves the saved bytes available. ## 10. Ablation diff --git a/docs/eval/evidence-pack.md b/docs/eval/evidence-pack.md new file mode 100644 index 0000000000..80f318daa7 --- /dev/null +++ b/docs/eval/evidence-pack.md @@ -0,0 +1,310 @@ +# 证据包打包:Timeline 的分级披露与脱敏 + +Scope: 提交人本机上的一个一次性工具,不在 daemon 里,不属于任何 Session。 +Related: [#1701](https://github.com/arcships/dim/issues/1701)。交付状态在 issue,不在本文。 + +## 目的与范围 + +[Badcase 评测流水线](usercases-pipeline.md)的证据包里有一份 Timeline。原始的 +[Timeline 导出](../design/appserver/timeline-export.md)含 prompt、代码和工具输出,不能原样离开 +提交人的机器。本文定义导出与证据包之间的那一步:**哪些内容默认带上,哪些要提交人逐项放行, +带上的内容怎样替换标识,以及凭什么确认输出里没有不该有的东西。** + +调用者是要把案例交给别人的提交人:开放之后的外部用户,以及把案例交给另一位构建人的内部 +报告人。两者都要等[私有接收的前置条件](usercases-pipeline.md#接收用户提交的前置条件)定案。 +自己做构建的 dogfood 报告人用不到它:原始导出不离开他的机器。 + +三条设计约束,后文每一节都服从它们: + +1. **默认省略。** 只输出已列出的结构字段和允许保留的内容。未知字段连键一起丢弃,未知事件只保留事件外层信息。 +2. **要人判断的量必须小到看得完。** 默认带上的内容由提交人一次读完;其余的按单元点名追加。 +3. **输出不依赖判断全对。** 机器能检查的由工具检查,不通过就不产出;人会漏的由下游兜住 + (见 §不靠这一步保证的事)。 + +| 范围 | 是否纳入 | 所有者 | +|---|---:|---| +| 单元的划分、默认取舍、点名追加 | 是 | 本文 | +| 标识替换、占位格式、输出的校验 | 是 | 本文 | +| 确认时如何附上授权记录 | 是 | 本文 | +| 证据包的其余内容、授权范围、存放、撤回、上传通道 | 否 | [流水线](usercases-pipeline.md#收集) | +| 导出的行格式与内容 | 否 | [Timeline export](../design/appserver/timeline-export.md) | +| `/report` 的内容 | 否 | [Report 插件](../design/plugins/Report.md) | +| 工作区文件怎样进证据包 | 否 | [流水线](usercases-pipeline.md#证据包);文件没有可利用的结构,只能逐个点名 | + +本文不涉及插件、Capability、事件或核心机制,不改导出格式;设计规则 §4 与 ADR 002 不适用。 + +## 流程 + +```text + dimcode export(完整,以 end 结尾) 留在本机,从不上传 + │ + ▼ + ① 划分单元:同样的字符串算一个单元,流式分片先拼接 + │ + ▼ + ② 取舍:第 1 级默认 + 决定文件里点名的单元 决定文件 ◄─┐ + │ │ + ▼ │ + ③ 替换:保留的单元里的标识换成占位 │ + │ │ + ▼ │ + ④ 校验:任一项不过就不产出 │ + │ │ + ├──► 审阅文件(本机):保留的单元全文、省略的单元清单 ────┘ 提交人改决定后重跑 + ▼ + 包:timeline.jsonl + pack.json + 摘要 + │ 提交人确认摘要,记入授权记录 + ▼ + 证据包(上传与存放见流水线) +``` + +打包脚本只向本机受信任的 `dimcode evidence-redact` 进程传入原文,每次打包只启动一个进程;保留内容的替换、授权里的凭据检查和输出残留检查都由它处理。运行时显式指定支持此命令的可执行文件,例如: + +```sh +python3 benchmarks/usercases/pack.py EXPORT --out DIR --dimcode /absolute/path/to/dimcode +``` + +也可以设置 `DIM_EVIDENCE_DIMCODE` 为该文件的绝对路径。命令行参数优先;工具不从 `PATH` 或当前目录寻找程序。未指定、路径不是绝对路径或进程失败时,不会改用其他程序或 Python 规则,也不留下包。 + +工具不联网、不调用模型、不上传。同一份导出、同一份决定文件、同一版规则,生成的 `timeline.jsonl` +逐字节相同。清单里的 `timeline_sha256` 供收件人校验 Timeline;本机确认使用完整待发送清单的 +SHA-256。清单已包含 Timeline 的摘要,所以确认时两份文件都不能变。这个摘要不是签名,不证明 +提交人身份。 + +## 单元 + +工具按事件种类列出允许输出的字段及类型。**未列出的键和值一起省略**,不因值是数字、布尔值或 +对象而保留;未列出的事件只带事件外层信息,不带原始事件正文。 + +| 已列出的字段 | 例子 | 处理 | +|---|---|---| +| 结构 | 事件名称、序号、关联 ID、状态、模型 ID、计量数字 | 保留结构;按替换规则处理标识 | +| 不可读 | 供应商的签名、加密内容及无法审阅的推理数据 | 用固定占位替换,不允许放行 | +| 内容 | 对话、工具参数和结果、before trace、自由文本错误原因 | 划成单元,按 §分级 取舍 | + +字段是不是内容由协议定义,不由某个样例的取值决定。例如回合结束的 `reason` 即使写着 +`end_turn`,仍按自由文本处理。新增字段在列入允许清单前不会进入输出。 + +**单元按内容相等划分。** 同样的字符串无论出现在多少个事件字段、多少次模型请求里,都是同一个 +单元,一次取舍对所有出现处生效。这是必须的而不是优化:每次 `model/call` 携带当时的完整上下文, +同一条消息会随后续的每次请求再出现一次,逐处处理一定会漏。 + +- 流式输出按「流」拼接后算一个单元。一条流是同一分支、同一次模型请求(从 `step/model-start` + 到它的 `step/model-output-end`)里同一种类(`step/thinking` 或 `step/text`)的全部分片, + 中间夹着别的事件也不断开。分片可以短到一个字符,任意两片之间都可能切断一个标识;读包的人 + 会把它们拼起来读,所以替换、取舍和校验都只看拼接后的整条流,不看单个分片,也不看相邻的 + 几片。流分片事件的 `turn_id` 与 `request_id` 是结构,规格没有列到的其余字段直接丢弃, + 不生成单元,也不能通过决定文件点名追加。一条流跨了多个内容块时,它拼接后的全文与各个块 + 不是同一个字符串,因此是不同的单元;点名时点的是内容块的那一个。 +- 工具参数、结构化结果和 before trace 等明确列为内容的对象,键也可能是内容,所以整个对象 + 序列化后作为一个单元,不拆开。 +- 工具名按来源处理。来源是 `builtin` 或 `extension` 的名字保留;`extension` 的名字同时列在审阅 + 文件里,提交人可以改成编号。其余来源(例如 MCP)和来源不明的名字换成编号(`tool-1`、 + `tool-2`),同一个名字在各处是同一个编号。 + +每个单元有一个编号(`u1`、`u2`……,按首次出现的顺序)和一个种类。同一个单元出现在几处时,种类按 +下表的先后取:它的各处出现里,排得最靠前的那个种类就是它的种类。 + +种类不能取自首次出现的位置。导出按分支 ID 排序,所有子分支都排在 `main` 之前,而子分支的第一次 +请求带着从父分支继承的全部上下文;按首次出现定种类,整段对话就都成了「其他」。按先后取则与 +行的顺序无关;而且一个字符串只要在某一处被保留,它就已经在包里了,所以第 1 级的种类总是优先。 + +| 种类 | 来自 | +|---|---| +| 用户输入 | 用户提交的消息正文,不含后来追加的运行时文本块 | +| 助手回复 | 模型输出里的正文 | +| 思考 | 模型输出里的思考 | +| 工具参数、工具结果 | 工具调用及其结果,含后台任务的描述与输出 | +| 注入内容 | 运行时注入的规则、状态、目标、通知及其在提示词条目里的原文,以及提交检查追加的上下文 | +| 系统提示、工具定义 | 请求里的 `system` 与 `tools` | +| 附件 | 图片等二进制内容 | +| 错误信息 | 回合与模型输出结束、打断、审批取消与协作收尾时的 `reason` 与 `error` | +| 其他 | 明确列为内容的诊断对象、before trace;只在模型请求里出现、对不上任何事件字段的文本 | + +在 `input/message` 的 `user.content` 里,首块即使以运行时标签开头,也不算注入内容;后续块只有文本类型且以 Dim 识别的完整运行时标签名开头,才算注入内容(见 [`markup::runtime_context`](../../crates/dim-agent-types/src/markup.rs))。因此,提交检查追加的上下文和后续模型请求中相同的副本默认都用同一个占位;提交人有权分享时,可在第 2 级逐个点名保留。恰好与真正的用户输入或助手回复完全相同的文本,仍按上表的优先顺序归类。 + +审阅文件里为单元标的位置,是定下它种类的那一处。 + +## 分级 + +| 级别 | 带什么 | 谁审 | +|---|---|---| +| 0 | [`/report`](../design/plugins/Report.md#6-preview-and-sharing) 的报告 ZIP,不经过本工具。报告默认只含诊断信息。只有发送人勾选附带对话,当前会话报告才会加入近期用户和助手的片段;脱敏开关不决定是否附带对话 | 发送人在本机检查附件。公开渠道的自动摘要不含对话原文 | +| 1 | 全部事件的结构,加「用户输入」与「助手回复」两种单元 | 提交人,一次读完 | +| 2 | 第 1 级之上,决定文件点名的单元 | 提交人,逐个放行 | + +第 1 级是默认。首次提交只交第 1 级;工具按提交人点名的单元决定级别,并不判断是否为首次提交。第 1 级足以回答分诊的问题:用户要什么、助手说了 +什么、调了哪些工具、顺序和耗时、每段内容多大、用户在哪一步提出异议、每次操作有没有被批准、 +在哪一步被打断、压缩发生在哪一轮。它不足以构建题目。 + +第 2 级由构建人发起。他在跟踪 issue 里写单元编号;编号就在包里的占位上,不含内容,可以公开。 +提交人把它们加进决定文件,重跑,重新审阅整个待提交包后再确认。编号不变不代表内容不变:替换词、源导出或选择规则变化时,旧单元的输出也可能变化。 +提交人也可以不放行;构不出题的案例按[分诊](usercases-pipeline.md#分诊)留在 issue。 + +决定文件还能反过来用:把第 1 级默认带上的某个单元改成省略。 + +**省略的单元留下占位,不改变结构。** 占位是一个固定格式的字符串,带单元编号、种类和字节数: +`[omitted u412 tool-result 1823B]`。所在字段的 JSON 类型不变:字符串换成占位字符串,整体省略的 +对象换成只含一个占位成员的对象;省略的分片把占位放在第一片,其余为空串。行数、序号和每个 +事件的种类都与导出一致,读导出的工具照样能读。 + +没有「按失败点裁剪」这一步。结构本身不含内容,而保留下来的任何一次模型请求都带着此前的全部 +上下文,按序号裁剪并不缩小被带走的内容;真正决定带走什么的是单元的取舍。 + +## 替换 + +替换作用于输出里的全部字符串:保留的单元,以及结构字段里的 ID。替换表在本机,从不进入包。 + +| 来源 | 内容 | 自动 | +|---|---|---| +| 导出自己记录的事实 | Dim 注入的环境状态里的主目录、由它得到的用户名;Session ID;供应商侧的条目 ID 与调用 ID | 是 | +| 高置信的密钥形态 | 已知前缀的令牌、私钥块、JWT | 是 | +| 候选词 | 保留的单元里出现的:不在公开名单里的域名、主目录下的目录名、代码托管链接里的账号名 | 否,列在审阅文件里由提交人勾选 | +| 提交人自己写的词 | 人名、公司名、项目代号 | 否,写在决定文件里 | + +- 主目录只从 Dim 注入的环境状态里取:工具结果里可能引用同样的标签(例如读到一个拼出这个标签 + 的测试文件),把它当成主目录会让真实的用户名漏过去。环境状态里出现几个主目录就替换几个; + 一个也没有时,审阅文件提示提交人把自己的用户名写进决定文件。 +- 同一个原文在整个包里换成同一个占位,调用与结果、请求与事件之间的对应关系因此保持。主会话和每个协作成员会话各用一个包内代号。请求、投递、结果和保留的对话正文引用同一会话时都用这个代号;不同会话不共用代号。 +- 主目录与用户名的占位和原文等长;其余占位是短标签(`call-3`、`tool-2`、`[secret-1]`、 + `[term-1]`)。 +- 拉丁字母的词按词边界匹配,其余按子串匹配;匹配不区分大小写,并覆盖 JSON 转义与 URL 编码 + 两种写法。Windows 主目录同时匹配反斜杠和正斜杠写法。路径前缀之外,用户名还会单独出现 + (例如文件列表的属主列),所以用户名自己也入表。 +- 两种用户名不作为单独的词替换:人人都有的账号名(`root`、`ubuntu` 等),它不标识任何人; + 短于 4 个字符的用户名,替换它会改写对话里无关的词,它改列为候选词。同理,短于 8 个字符的 + 供应商 ID 只在自己的字段里换成占位,不在内容里搜索。 +- 正则命中的「密钥赋值」形态(`token = …`)不自动替换。在代码会话里它几乎全是标识符,只在 + 审阅文件里标成提示。 +- 保留的流在拼接后的全文上替换,再按原来的边界切回各个分片;边界落在被替换的词中间时移到 + 词尾,所以没有一个分片带着被替换词的一部分。 + +## 审阅与确认 + +每次运行写出两样东西:包,和只留在本机的审阅文件。审阅文件按这个顺序排: + +1. 保留的单元,替换之后的全文,每个带编号、种类、位置、出现次数和扫描提示。 +2. 替换表、候选词,以及保留了原名的 `extension` 工具。 +3. 省略的单元,每个一行:编号、种类、位置、字节数、出现次数。 +4. 被引用但不在导出里的文件,例如粘贴的文本和后台命令的输出文件。它们不会被带上。 +5. 完整待提交清单,以及可以确认时使用的摘要。 + +未确认的包只供本机审阅,`pack/pack.json` 不含正式授权记录。在决定文件(默认是输出目录里的 +`decisions.json`)里填写 `consent`,不带 `--confirm` 重跑,审阅完整的 `pack/timeline.jsonl` +和审阅文件第 5 节中的完整待提交清单。单元列表是阅读辅助,不替代检查两份文件。两份都确认后, +用第 5 节的摘要运行 `--confirm DIGEST`。授权示例: + +```json +{ + "consent": { + "diagnosis": true, + "regression": false, + "providers": [], + "expires": "2027-05-16" + } +} +``` + +这个例子只授权诊断。`diagnosis` 和 `regression` 必须明确填 `true` 或 `false`;`providers` +只填允许使用的供应商名称,不填凭据,未授权任何供应商就填 `[]`。允许纳入回归集时至少要列一个 +供应商。`expires` 是 `YYYY-MM-DD` 格式的到期日期,到期当天仍有效。确认时按提交人本机日期 +判断:授权已过期、填写不合规则或摘要对不上,都不留下包。隔天确认时 `given` 会变;需重新预览。 + +同一个输出目录一次只允许一个打包进程。重跑时,工具用本地凭条 `.pack-receipt` 核对上次写出的两份包文件和 `review.md`。如果有同名文件但没有有效凭条、内容被改过、目录里混入其他文件,或有符号链接或遗留的 `pack.tmp/`,工具不开始重建,也不改动这些文件。请换一个新输出目录;原目录中的文件不是本次打包结果。不要发送凭条、审阅文件或中间目录。如果进程被强制终止而留下 `.pack.lock`,先确认进程已退出,再换新目录重跑。 + +确认时工具把这四项和当天的 `given` 日期写入 `pack.json`,不写提交人身份。摘要与规则版本是 +[授权记录](usercases-pipeline.md#授权)的「脱敏版本」。接收方核对摘要与授权,并在收件时重新 +检查授权是否过期;确认时还有效,不代表收件时仍有效。私有接收仍须满足 +[前置条件](usercases-pipeline.md#接收用户提交的前置条件)。 + +包里有两个文件: + +| 文件 | 内容 | +|---|---| +| `timeline.jsonl` | 导出 v1 的行格式。头部的 `sensitive` 仍是 `true`:打包之后它依然是敏感材料 | +| `pack.json` | 证据包编号、规则版本、来源导出的版本、用到的全部模型、各种类保留与省略的单元数和字节数、占位清单(不含原文)、未包含的外部文件数、摘要;确认后另有 `consent`:三项授权范围、给出日期与到期日期 | + +决定文件、替换表、单元编号与原文的对应关系留在提交人本机,与原始导出放在一起。没有它们就 +回应不了第 2 级的请求,所以它们的保留期限跟随原始导出。 + +## 校验 + +通过输出目录的归属检查后,工具先清掉已核实的旧包,再生成新包。写完后重新读一遍输出:任一项不成立就不留下可交付的包,只报告哪一项、在哪个序号。 + +| 检查 | 不成立说明什么 | +|---|---| +| 输入以 `end` 结尾,计数相符 | 导出不完整 | +| 内容位置上的每个值是占位,或一个保留单元替换后的文本;ID 与工具名的位置上是占位或保留的名字。流式输出按整条流拼接后判断 | 取舍有漏 | +| 替换表里每个原文及其转义、编码写法在输出的任何字符串和键里都找不到,在每条流拼接后的全文里也找不到 | 替换有漏,或提交人列的词撞上了结构字段的值 | +| 输出里没有高置信的密钥形态 | 密钥出现在内容之外的位置;内容里的已经被替换 | +| 输出里没有不可读字段 | 删除有漏 | +| 行数、序号、事件种类、各字段的 JSON 类型与输入一致;不同的 ID 没有共用一个占位 | 输出不再是可读的导出 | + +这一遍重新解析并重新分类输出,逐行对照输入,不复用写输出时算出的结果。 + +## 不靠这一步保证的事 + +- **自由文本里的敏感内容找不全。** 人名、业务信息、专有代码没有形态可循。本设计的回答是让 + 它们默认不进输出,而不是去识别它们。 +- **提交人会漏。** 所以包仍按敏感材料对待:私有存储、访问有审计、可撤回;公开的 issue 里不出现 + 它的内容;进入语料的 fixture 由构建人重写,不照搬包里的原文。这几条由流水线规定。 +- **省略可能把触发条件一起去掉。** 占位保留了字节数,长度相关的触发条件可以用等长的合成材料 + 重建;重建得对不对,由[区分度证明](usercases-pipeline.md#构建)回答。 +- **提交人无权替第三方授权。** 工具返回的内容默认全部省略,其中可能有第三方的数据;第 2 级 + 放行某个工具结果之前,提交人要自己判断它是不是自己有权分享的。 + +## Verification + +flow test 的输入是测试自己生成的合成导出,不含真实会话,不调用模型: + +- 在这些位置各放一个标记串:工具结果、跨两个分片的思考、不可读字段、清单不认识的事件种类、 + 非内置工具的名字与参数、只在模型请求里出现的消息、流分片里规格没有列到的字段、 + 属主列形态的用户名,以及标记串的 JSON 转义与 URL 编码写法。第 1 级的输出里一个都找不到。 +- 用户输入与助手回复里的标识被换成占位,同一个原文在各处是同一个占位。 +- 多块用户输入中的首块运行时标签和后续普通文本都保留。提交检查追加的块及两次模型请求里的相同副本在第 1 级都省略;人为把这些副本放回时校验逐处报告,点名保留后各处均带上脱敏文本。 +- 子分支排在 `main` 之前、第一次请求带着继承的上下文时,第 1 级仍带上 `main` 的用户输入与 + 助手回复,审阅文件把它们标成这两个种类、位置指向 `main` 的事件;子分支排在后面时,各种类 + 保留与省略的数量不变。子分支里一个引用了主目录标签的工具结果不会被当成主目录。 +- 决定文件点名一个单元后,它在每个出现处都被带上并完成替换;保留的分片拼接后等于合并内容。 +- 用户名被切在两个分片之间,两片之间紧挨着或夹着别的事件,每一片里都找不到用户名的任何一半; + 把原来的两半放回已写出的包,校验报告这条流。 +- 同样的输入运行两次,输出逐字节相同。 +- 合成 flow test 的边界导出覆盖审批、打断、压缩和协作事件:第 1 级保留审批的决定、打断的范围、 + 压缩的触发与结果状态、协作的收信人;审批的调用与理由、打断的理由、权限策略、压缩的替代内容、 + 协作的提示词与结果文本按内容省略。单独的图片用例也覆盖图片块的首个操作块规则;这些用例不替代 + 真实导出的检查。 +- 名册按 `events.rs` 的域与名字枚举核对,缺任何一个核心事件种类,测试失败。 +- 确认后清单带当天的授权日期,不带提交人身份;未确认时不带授权,即使决定文件里已经填写过。 +- 同一份授权在到期当天可以确认,次日拒绝确认,且不留下包。 +- 能由输入触发的拒绝各有一个输入:不完整的导出、不存在的单元编号、撞上结构字段的替换词、 + 内容之外的密钥、对不上的确认摘要、缺失或无效的授权。拒绝之后没有包留下。 +- 防的是工具自身出错的检查,用改动已写出的包来验证:放回一段内容、一个不可读字段、一个 + 供应商 ID,改掉一个序号,删掉一行,各自被报告。 +- 输出的行数、序号、事件种类与字段类型和输入一致。 + +已知的不确定: + +- 合成导出覆盖了多分支、before trace、压缩事件、带图片块的用户输入,以及协作请求与结果。 + 其中协作事件的测试只检查字段的取舍,不能证明完整子 agent 会话里的委派提示会被归为哪类输入。 +- 对照过的真实材料只有两份:一份单分支会话保留了内容引用;另一份是已跑通的多分支内联 + `dimcode export`。仍需用真实导出验证 before trace、压缩、图片和完整的子 agent 会话,尤其要核实 + 父 agent 的委派提示是否会在子分支被记为用户输入,因而进入第 1 级。 +- 「第 1 级足以分诊」是判断,没有用真实案例验证过。第一批 dogfood 案例用来验证它:报告人在 + 本机打出第 1 级的包,看只凭它能否写出分诊结论。这不需要把包交给任何人。 + +运行结果写在 issue 或 PR 里。 + +## 向所有者提出的需求 + +无。工具读的是现有导出,写的是同一行格式;事件新增字段时默认按内容省略,不需要事件的所有者 +配合。 + +首版是本仓库里的一个本地脚本([pack.py](../../benchmarks/usercases/pack.py)),供内部交接案例 +使用。开放外部用户提交时它需要随产品分发,那是一个新的 CLI 命令,届时另行设计并向 CLI 命令的 +所有者提出;本文的规则是它的合同。 + +## 开放问题 + +- **思考默认省略的代价。** 「模型为什么这样做」常常只在思考里。它不进第 1 级是因为体积大、 + 没人读得完;是否值得为它设一个更窄的默认(例如只带异议之前的最后一次请求),等第一批案例 + 用下来再定。 diff --git a/docs/eval/usercases-pipeline.md b/docs/eval/usercases-pipeline.md new file mode 100644 index 0000000000..c11f596947 --- /dev/null +++ b/docs/eval/usercases-pipeline.md @@ -0,0 +1,345 @@ +# Badcase 评测流水线:从真实失败到回归题 + +Related: [#1701](https://github.com/arcships/dim/issues/1701)(usercases 语料)。交付状态在 issue,不在本文。 + +## 目的与范围 + +usercases 语料回答「这次改动有没有把用户真实踩过的坑重新挖开」。语料本身只是流水线的中段。 +本文定义它的前后两段,以及各段之间交接什么:**一个真实失败怎样被收进来、怎样决定它该变成 +哪种测试、怎样证明做出来的题确实在测那个失败、跑完之后怎样读结果并回到修复。** + +来源是三个:**用户主动提交、内部 dogfood、公开 issue。** 前两个带真实材料,是这条流水线存在的 +理由;第三个没有授权负担,用来先把后半段跑通。不扫描、不默认上传任何会话。 + +| 范围 | 是否纳入 | 所有者 | +|---|---:|---| +| 各阶段的输入、产物、准入条件与交接 | 是 | 本文 | +| 证据包的内容、授权范围、存放与撤回 | 是 | 本文 | +| Timeline 进证据包之前在本机怎样取舍、替换和校验 | 否 | [证据包打包](evidence-pack.md) | +| 根案例的身份,以及按根案例读结果的规则 | 是 | 本文 | +| 结果到 issue 的闭环动作 | 是 | 本文 | +| 任务格式、判分语义、成对规则、pin | 否 | [usercases 语料合同](../../benchmarks/usercases/README.md)(#1701) | +| 触发、k 的语义、门禁是否阻断 | 否 | [trigger-policy.md](trigger-policy.md) | +| 运行入口、结果有效性、baseline 与配对比较 | 否 | [benchmarks/README.md](../../benchmarks/README.md) | +| `/report` 里能带什么证据 | 否 | [Report 插件](../design/plugins/Report.md) | +| Timeline 导出的格式、内容与敏感性 | 否 | [Timeline export](../design/appserver/timeline-export.md) | +| 缺陷修复自带的 flow test 怎么写 | 否 | [AGENTS.md](../../AGENTS.md) Testing | + +本文依赖语料合同里的三项:manifest 的 `source_issue` 与 `kind`,以及主任务与对照成对入集的 +规则;该合同变化时本文跟随,不另行定义。 + +本文不涉及插件、Capability、事件或核心机制,也不改 Timeline 导出格式或 Report 插件;设计规则 +§4 与 ADR 002 不适用。 + +## 总览 + +```text + 用户主动提交 内部 dogfood 公开 issue + │ 证据包 + 授权 │ 证据包(留在本机) │ 公开复现 + │ 私有接收 │ │ + ▼ ▼ ▼ + 跟踪 issue ═══ 根案例,贯穿全程的唯一身份;只含可公开的内容 ═══════════╗ + │ 分诊:授权与材料可用、能否复现、预期能否写清、选去向 §分诊 ║ + ├──────────────► 留在 issue(不可复现或预期不清,不入分母) ║ + ├──────────────► 产品 flow test,随修复 PR(需要中断、重启、时序) ║ + ▼ ║ + 构建:失败前的初始状态 + 脱敏 + 主任务与对照 + 区分度证明 §构建 ║ + ▼ ║ + usercases 语料(任务树在私有仓库,本仓库只留 pin) 语料合同 ║ + ▼ ║ + 运行(daily_run.py,k 语义沿用 trigger-policy) 已有 ║ + ▼ ║ + 分析:按根案例成对读结果 × issue 状态 §分析 ║ + ▼ ║ + 闭环:重开、关闭、改题、撤回 §闭环 ═══╝ +``` + +本文新增的是:证据包与授权的合同、分诊去向规则、区分度证明、按根案例的读法、闭环与撤回动作。 +其余阶段由已有的合同承载,本文只给链接。 + +## 根案例是一个跟踪 issue + +一个根案例对应本仓库的一个 issue。语料 manifest 里每道题的 `source_issue` 就是它的根案例键, +主任务和对照共用同一个键。 + +| 来源 | 跟踪 issue 是什么 | +|---|---| +| 公开 issue | 原 issue 本身 | +| 内部 dogfood、用户主动提交 | 新开的 issue,只写可公开的内容:一句不含用户材料的症状、机制类别、Dim 版本、证据包编号 | + +本仓库是公开的,所以带真实材料的根案例在 issue 里只留一个壳:会话 ID、用户身份、对话与文件 +内容都不出现在里面。证据包编号是随机生成的,不从账号、会话或内容派生。 + +这样定的后果是有意的: + +- 不另设登记表或状态机。分诊结论、修复状态都写在 issue 里,仓库的惯例本来就是「状态在 issue」。 +- 回归题和能力题不需要字段区分:issue 已关闭的是回归题,仍打开的是能力题,读法见 §分析。 +- 一个根案例可以同时有 usercases 题和 flow test,它们是同一个案例的两种证据,统计时只算一个 + 根案例。 + +待进入流水线的 issue 用一个标签标出(建议 `eval-badcase`,尚不存在);流水线发现的失败沿用 +已有的 `eval-failures`。 + +## 收集 + +### 三个来源 + +| 来源 | 复现材料 | 原始材料在哪 | 谁做构建 | +|---|---|---|---| +| 用户主动提交 | 证据包 | 经授权后私有接收 | 有权访问该证据包的人 | +| 内部 dogfood | 证据包 | 不离开报告人本机 | 报告人本人 | +| 公开 issue | [缺陷报告模板](../../.github/ISSUE_TEMPLATE/01-bug-report.yml)里的最简复现 | issue | 任何贡献者 | + +三种来源都可以用 [`/report`](../design/plugins/Report.md#6-preview-and-sharing) 反馈。报告默认只含诊断信息。只有发送人勾选附带对话,当前会话报告才会加入近期用户和助手的片段。脱敏默认开启;关闭脱敏不会自动附带对话。分享前要查看预览。GitHub 草稿和 Discord 的自动摘要不含对话,不代表 ZIP 可以公开。 + +普通反馈到此即可,不要求导出 Timeline。邮件默认只允许排查本次问题。只有发送人明确选择团队内部回归评测,且收件人核对邮件里的 SHA-256 与附件一致时,才可按此范围使用**这份报告**。附件不符、授权缺失或措辞含混时,不作评测。这个选项不授权把内容发给外部模型供应商,不允许训练或公开,也不是完整证据包的接收入口。材料不足就向报告人说明缺什么,不从会话里自动补采。 + +### 提交 + +以下步骤只用于报告不足、需要进一步提交证据包的案例。普通报告的邮件流程不要求再开 issue、再做一份 ZIP,也不调用 Timeline 打包器。 + +1. 在出问题的 Session 里运行 `/report`,用它的 issue 草稿建跟踪 issue。 +2. 选定失败锚点:`/report` 里的事件序号,或整个任务。 +3. 写两句话:哪里不对;怎样才算做对。它们可能带用户材料,所以进证据包,不进 issue。 +4. 导出这个 Session 的 Timeline,在本机[打包](evidence-pack.md)。默认只带事件的结构和双方的 + 对话文字;提交人读完将要带走的全部内容,可以删减。工具输出、思考和文件不在默认范围里, + 构建人需要时按编号点名,提交人逐个放行。 +5. 逐项给出授权(见下)。 +6. 拿到证据包编号,凭它查询处理进度或撤回。 + +自己做构建的 dogfood 报告人跳过第 4 步:材料不离开他的机器。只提交文字、不给任何材料也可以。 +这样的提交停在 issue,成不了可运行的题。 + +### 证据包 + +| 内容 | 必需 | +|---|---| +| 哪里不对、怎样才算做对、失败锚点 | 是 | +| Dim 版本、模型身份、权限模式、启用的插件 | 是 | +| 授权记录 | 是 | +| Timeline:`dimcode export` 的输出经[打包](evidence-pack.md)之后的包 | 由别人分诊或构建时 | +| 失败**之前**的输入文件与工作区状态 | 要做成可运行的题时 | +| 外部依赖的冻结副本:题目用到的网页或 API 响应 | 题目依赖它们时 | + +Timeline 导出不是可运行的环境:它没有文件快照,也没有外部服务的状态。只有失败之后的文件 +通常恢复不出原题,所以工作区状态要单独提供。模型的思考过程不是必填项,判分也不依赖它。 + +证据包永不包含:provider 凭据、`.env`、SSH 私钥、cookie、浏览器 profile、整个 home 或整个 +工作区、生产账号的登录态。导出按合同不读凭据表,但用户或工具写进对话里的密钥会原样出现在 +Timeline 中。 + +原始导出不在证据包里,始终留在提交人本机。证据包里的 Timeline 是打包之后的:默认省略内容、 +替换标识、校验不过就不产出,规则见[证据包打包](evidence-pack.md)。打包之后的包仍是敏感材料, +下面的授权与存放照样适用。 + +### 授权 + +三项范围分开给出、分开记录,缺一项就不做那一项对应的事: + +| 范围 | 允许什么 | +|---|---| +| 诊断 | 用证据包分析这一次失败 | +| 回归集 | 脱敏后的派生材料进入长期保留的私有语料 | +| 模型供应商 | 派生材料随评测运行发送给被测模型的供应商,失败 trial 的片段发送给失败分析所用的模型 | + +第三项是必需的而不是附带的:运行一道题就是把它的 fixture 发给模型, +[analyze.py](../../benchmarks/report/analyze.py) 归类失败时会把题面、判分器输出和 Timeline +末段发给另一个模型。 + +任何一项授权都不包含:模型训练、公开发布、原始证据包的长期保存。 + +授权记录只有证据包编号、给出的范围、日期、到期时间和脱敏版本。提交人的身份映射与它分开 +保存,只有分诊者可见;跟踪 issue 里只出现证据包编号。团队或企业工作区的提交还要满足管理员 +策略,并由提交人确认自己有权分享其中的材料。 + +### 存放 + +| 资产 | 存放 | 删除 | +|---|---|---| +| 原始证据包 | dogfood:报告人本机。用户提交:私有、可删除、访问有审计的存储 | 到期或撤回时删除 | +| 派生 fixture | 语料任务树,在私有仓库里 | 从任务树移除并升 pin | +| 授权记录、身份映射 | 与原始证据包同一存储,彼此分开 | 撤回后只留不含内容的删除记录 | +| 跟踪 issue | 本仓库,只有可公开的内容 | 不需要 | + +原始证据包不进任何 git 仓库、issue、CI 产物或日志。 + +### 接收用户提交的前置条件 + +以下各项定案之前,不开放用户提交的私有接收: + +- 原始证据包存放在哪,谁能访问; +- 保留期限与撤回后的删除时限,包括备份; +- 派生 fixture 撤回后,私有仓库 git 历史里的副本怎样处理。这一条必须在授权时向提交人说明; +- 允许使用哪些模型供应商。 + +这些由产品与隐私负责人决定(见 §向所有者提出的需求)。定案之前,用户仍可以通过公开 issue +提交不含隐私的最小复现。dogfood 不受此限:原始证据包不离开报告人本机,给出授权的就是报告人本人, +进入私有语料的只有他审过的派生 fixture。 + +首版用专用企业邮箱作为唯一的私有提交入口,不另做上传页。邮箱通过验收且上述条件全部满足后, +才接收提交人在本机审阅确认、为本次排查所必需的脱敏证据包。不接收原始会话导出、凭据或本机 +审阅文件。收件人核对已确认的 `pack.json`、其中记录的 `timeline.jsonl` 摘要、授权范围和到期日,再按证据包编号发回执。打包器确认的不是外层 ZIP;同一封邮件里另附的失败说明、工作区文件或外部依赖,不继承这份授权。未经单独审阅并绑定授权的旁附材料,不接收、不复用。提交人可回复邮件,凭编号申请撤回。 + +开放前,邮箱管理员和隐私负责人用合成包验证:只有指定收件人能访问(获准与未获准账号各测一次), +有可查询的访问记录,能按编号受理撤回。确认到期或撤回后邮件、归档和备份各自的删除时限; +验收前不接收真实证据包。用合成附件检查三种拒绝情况:普通报告摘要相符但未选内部回归,不作评测;选了内部回归但 ZIP 摘要不符,也不作评测;已确认的证据包附带其他文件,不把包的授权延伸给旁附文件。 + +## 分诊 + +分诊回答四个问题,结论写在跟踪 issue 里,写法不带用户材料。 + +**一、材料能不能用。** 带证据包的来源先核对授权是否仍有效,再按用途分别判断:只有授权诊断才 +能用包排查;只有授权回归集且列出允许的模型供应商才能用派生材料做题;评测和失败分析也只能把材料 +发给获准的供应商。缺少某项授权就不做该项,不以另一项代替。公开 issue 跳过这一问。 + +**二、它是不是一个可用的案例。** 以下任一项不成立就留在 issue,不进入后续阶段,也不进任何 +分母:失败有证据;预期结果能写成一句不依赖解题路线的话;失败能在一个干净环境里重新出现,偶发 +的要写明出现次数。 + +用户不满意不等于 harness 有缺陷。分诊不要求给出根因,根因不明的案例照样可以入题,只要失败 +可复现、预期可判分。 + +**三、它与已有根案例是否同源。** 同源就并到已有 issue,不另立案例。 + +**四、它该变成哪种测试。** 按可表达性选去向,不按重要程度: + +| 复现这个失败需要什么 | 去向 | +|---|---| +| 一次 `dimcode exec` 能在容器里跑完,终态能被确定性判分 | usercases 题:主任务 + 对照 | +| 进程被杀后重启、取消与完成竞争、通知乱序等时序,且用固定的模型输出就能驱动 | 产品 flow test,随修复 PR 合入;不入语料 | +| 真模型 + 多轮输入、中途 steer 或外部事件 | 目前没有承载,见 §开放问题 | + +第二行不入语料的原因是适配器每个 trial 只运行一次 `dimcode exec`,注入不了中断。这类案例由 +确定性的 flow test 保护更便宜也更准,它是普通的 CI 测试,不产生通过率,本文也不为它另设 +统计。flow test 在本仓库里是公开的,所以它的 fixture 只能是合成材料。 + +## 构建 + +任务格式、成对规则和判分语义以语料合同为准。本节规定从材料到题目之间必须做到的三件事, +结论写在入集 PR 里。 + +**初始状态是失败之前的状态。** 题目从用户开始这件事时的工作区出发,不从失败之后的现场出发, +也不把用户后来用来纠错的话写进题面。最小化可以删掉与触发无关的内容,但要保留触发条件本身。 + +**fixture 重写,不照搬;替换不能改掉触发条件。** 来自证据包的 fixture: + +- 题面和工作区由构建人重写或合成,用来复现触发条件,不从证据包里照搬原文。只有触发条件 + 依赖原文时才保留那一段。这让进入语料的内容经过第二个人,不依赖提交人打包时没有漏。 +- 重复出现的名称、路径、数值用一致的占位符替换;失败所依赖的长度、相对关系、单位和边界条件 + 保持不变。压缩类案例需要等长的替代材料,而不是把上下文删短。 +- 任务名与本仓库 manifest 里的任何字段不带用户材料。 +- 提交的脚本、文件和网页一律视为不可信:构建时不在沙箱之外执行它们,任务容器里没有生产 + 凭据。 + +**区分度证明。** 一道回归题如果在修复前和修复后都通过,它什么也没测。入集前在修复 PR 的父提交 +上运行这一对题,期望结果是主任务失败、对照通过。证明跑的是脱敏之后、准备入集的那份 fixture, +所以它同时回答了「脱敏有没有把缺陷一起修掉」。 + +| 修复前的结果 | 结论 | +|---|---| +| 主任务失败,对照通过 | 题目复现了根案例,可以入集 | +| 主任务通过 | 题目没有触发这个失败,回到最小化或脱敏 | +| 对照失败 | 失败不属于这个机制,或题目本身有缺陷,回到构建 | +| 修复前的构建无法运行 | 入集 PR 写明原因;该题的通过不得被引用为「修复仍然有效」的证据 | + +能力题(issue 仍打开)在当前 main 上做同一件事:主任务失败、对照通过,才算复现。 + +这次测量用 `baseline` 运行类型加 `--head <提交>` 进行,它不判窗口、不推进 state。该运行类型 +会写出 `.json`,所以 `--baselines-dir` 要指向临时目录,避免覆盖同一 pin 的参照;结果写在 +入集 PR 里,不作为 baseline 文件提交。 + +## 运行 + +没有新的入口。运行方式、窗口语义和首次上机自检见语料合同;k=1 是 screen、k=3 才可定性, +见 [trigger-policy.md](trigger-policy.md#experiment-parameters)。 + +## 分析 + +通用的配对比较和逐 trial 的失败归类已经存在:[baseline.py](../../benchmarks/runner/baseline.py) +给出每题相对 baseline 的变化,analyze.py 把每个失败 trial 归为 `agent`、`environment`、 +`timeout`、`model_api`、`harness` 或 `unknown`。本节在它们之上增加一层:**按根案例成对读。** + +读法只在 k=3 的运行上有定义。k=1 的运行只回答一个问题:哪些根案例值得跑一次 k=3。未判分和 +infra 失败的 trial 先按结果合同剔出;剔出后不足 k 次的那一对不读。 + +| 主任务 | 对照 | 读法 | +|---|---|---| +| k/k | k/k | **保持**:机制在这个构建上成立 | +| 0/k | k/k | **失败**:失败形态与根案例一致 | +| 介于两者之间 | k/k | **不稳**:记录通过次数,不下结论 | +| 任意 | 不是 k/k | **对照失效**:这一对不产生关于该机制的结论 | + +对照失效时看 analyze.py 给对照题失败 trial 的类别:`environment` 或 `harness` 指向题目或评测 +环境,`agent` 或 `timeout` 指向通用能力或预算。两种都不是这个根案例的回归。 + +读法再与 issue 状态相交,得到这次运行对这个根案例的结论: + +| 读法 | issue 已关闭(回归题) | issue 仍打开(能力题) | +|---|---|---| +| 保持 | 无动作 | 修复候选 | +| 失败 | 回归 | 预期中,无动作 | +| 不稳 | 记录 | 记录 | +| 对照失效 | 查题 | 查题 | + +这一层目前没有实现。它需要的输入都已存在:manifest 的 `source_issue` 与 `kind`、运行的逐题 +结果、analyze.py 的输出,以及 issue 的开闭状态。建议作为 `benchmarks/report/` 下报告的一个 +分节实现,不改 ledger 的记录格式。 + +**这不是门禁。** trigger-policy 的标定表明,同一构建上观测到 3/3 的任务下一轮仍是 3/3 的概率 +约为 72%,所以单次「失败」是值得人去看的信号,不是已确认的回归。它不阻断合并。 + +## 闭环 + +| 结论 | 动作 | +|---|---| +| 回归 | 重开原 issue;原修复不再适用时新开 issue 并链接原 issue | +| 修复候选 | 在 issue 里附这次运行,由修复者确认后关闭;关闭后该题自然成为回归题 | +| 记录 | 在 issue 里记通过次数;反复出现时按随机故障讨论,不改题 | +| 查题 | 题目或判分有缺陷就改题,改题按语料合同升 pin 并重采 baseline;环境问题修环境,不改判分 | + +**写进 issue 的内容随来源而定。** 公开 issue 来源的题可以附 trial 的 Timeline 末段与判分器 +输出。带证据包来源的题只写任务名、通过次数、读法、失败类别和运行编号;Timeline 片段、判分器 +输出和 analyze.py 引用的原文留在评测机的结果目录里,不进 issue。 + +题目只在它保护的行为被有意改变时退役:需求变了,修改或删除旧断言,在 PR 里说明。不因为 +「一直通过」而删题,回归题的正常状态就是一直通过。 + +### 撤回 + +提交人凭证据包编号撤回。沿根案例做完以下各步才算完成: + +1. 删除原始证据包,授权记录换成不含内容的删除记录。 +2. 从任务树移除该根案例的题,重新生成 manifest;新 pin 按语料合同重采 baseline。 +3. 删除评测机结果目录里含该题 trial 的运行产物。 +4. 在跟踪 issue 上注明已撤回并关闭;issue 本来就不含用户材料,予以保留。 + +已发布的汇总数字不回改:baseline 与比较本来就按 pin 分开,旧 pin 的数字停留在旧 pin 上。 + +## Verification + +- 每个来源各有一个根案例走完全程:跟踪 issue、分诊结论、区分度证明、入集、k=3 运行、按根案例 + 的读法、issue 上的动作。带证据包的那两个,跟踪 issue 与入集 PR 的公开部分里找不到用户材料。 +- 一个带合成材料的证据包走完撤回的四步,之后在任务树、结果目录和存储里都找不到它的内容。 +- 打包的验证见[证据包打包](evidence-pack.md#verification)。 +- 区分度证明的四种结果各有一个真实或构造的例子,结论与 §构建的表一致。 +- 按根案例分析的验收要求:实现这一层时,须用固定的结果文件逐项验证读法表的四行与结论表的八格,不调用模型。 + +运行结果写在 issue 或 PR 里。 + +## 向所有者提出的需求 + +| 需求 | 现状与替代 | 所有者 | +|---|---|---| +| 入集规则增加区分度证明(§构建);每道题有且只有一个 `source_issue`;带证据包来源的题,其 `source_issue` 指向跟踪 issue,任务名与本仓库里的任务表不带用户材料 | 现规则要求参考解与负例校准判分器,这证明判分器正确,不证明题目触发了根案例;现规则已允许「已获授权的真实失败」,未说明它在公开的 manifest 与 README 里怎样出现 | usercases 语料,[#1701](https://github.com/arcships/dim/issues/1701) | +| §接收用户提交的前置条件所列四项 | 现有语料全部在 git 仓库里,没有可删除的存储;定案前只开放 dogfood 与公开 issue | 产品与隐私负责人,尚无 issue | +| TUI 的 `/export` 对话框增加一项:把当前 Session 的完整 Timeline 存到本机。读不到本机的库(连接的是另一台主机的 daemon)时明确报错;文件存在工作区之外;之后不接任何分享动作 | `dimcode export` 已能导出,但要在命令行里给出 Session ID;对话框现约定恰好两项(Markdown、JSON),都只含主分支的对话,缺模型请求、其他分支和 before trace。没有这一项时提交人改用命令行,流水线不受阻 | CLI 命令([`/export`](../design/cli-commands.md#command-menu)),尚无 issue | +| usercases 接入 issue 报告路由之前,带证据包来源的题不得把 trial 片段发到公开的 issue | 语料合同下 usercases 目前不接报告路由,所以现在没有这条路径;报告器的 `redact` 只处理评测机信息、令牌形态的字符串和打印出来的期望值,不识别 fixture 内容 | 评测报告(`benchmarks/report/`),尚无 issue | + +## 开放问题 + +- **真模型多轮案例没有承载。** [scenario-eval](../../xtask/src/scenario_eval.rs) 有隔离运行、 + 脚本化的多轮输入、按时间或工具调用触发的事件和 judge,但它的两臂是同一构建上的两份策略 + 文本,不是两个构建。它能否用来比较两个构建,需要它的所有者回答;在那之前这类案例留在 issue。 +- **只重跑一对题的成本。** 运行入口按整棵任务树运行,没有按任务筛选。语料只有几对题时整跑 + 可以接受;增大之后,区分度证明和对「失败」的 k=3 确认都需要更便宜的路径。 +- **标签名**(`eval-badcase`)待仓库维护者确认。