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