# Which invariants prevent hierarchical transcript compaction from silently deleting the evidence an agent's own verifier needs **Date of Record:** 2026 November 28 **Scope:** Applies to long-running agents that persist episodic transcripts and, on context-window pressure, replace older spans with summaries produced by a recursive summarizer (leaf chunks → cluster summaries → root summary). Does not apply to append-only logs read in full, or to agents whose compaction is lossless (e.g., verbatim external memory with pointer-only eviction). ## Core Distinction There are two things an agent's transcript does when the context window fills: it *narrates* (provides narrative continuity so the model can reason about what it has done) and it *witnesses* (retains the exact tokens, tool outputs, and identifiers that downstream steps — including the agent's own verifier — must re-read verbatim). Hierarchical summarization is lossy by design and is tuned, implicitly, to preserve narration. It has no gradient toward preserving witness data. The failure mode is not "the agent forgets what it did." It is subtler: the agent retains a confident, fluent, *wrong* account of what it did, because the summarizer's paraphrase of a tool result survives compaction while the tool result itself does not. The verifier then checks the plan against the summary, the summary is internally consistent, and the check passes. The distinction that matters operationally is **summary-as-context vs. summary-as-evidence**: the first is a legitimate compression of working state; the second is a corruption of the audit surface. Compaction boundaries must separate them. ## What Was Observed A migration agent (call it `M`) was tasked with renaming 340 database columns across 12 migration files. Its loop was: read file → propose edits → apply → run a schema-linter tool → record the linter's exit code and stderr → proceed. Context pressure triggered auto-compaction at token 118k. The compactor chunked the transcript into 40-message leaves, summarized each leaf with a small model, then recursively summarized clusters of 8 leaf-summaries, producing a root summary injected as the new system-context preamble. The trace that broke: 1. At step 91, `M` applied an edit to `migrations/0007_users.sql`. The linter returned exit code `1` with stderr `column "user_email" referenced in index idx_users_email does not exist`. This was a real, unresolved failure. 2. At step 92, `M` reasoned: "Linter flagged a stale index reference; will reconcile in a later pass." It did not reconcile. It moved to file 0008. 3. At step 118, compaction ran. The leaf summary for the span containing steps 88–96 read, verbatim from the compactor's output: *"Applied edits to 0007_users.sql; linter run completed; noted index reconciliation as a follow-up."* 4. The phrase "linter run completed" replaced exit code `1`. The phrase "noted as a follow-up" replaced an unresolved blocking error. The root summary inherited both. 5. At step 140, `M` invoked its own completion verifier, which was prompted to "confirm all migration files pass the linter, using the transcript as evidence." The verifier read the root summary, saw "linter run completed" for 0007, and returned `PASS`. 6. The migration was declared complete with a broken index. The failure surfaced only in a downstream deploy, 40 minutes later, against a database that had already accepted 0006. The mechanism is precise: the summarizer collapsed a **ternary outcome** (exit 0 / exit 1 / not run) into a **binary narration** (completed / not completed), and the verifier's evidence channel was the same channel that had been lossy-compressed. No component lied. The compactor did exactly what hierarchical summarization does. The verifier did exactly what it was told. The invariant that was violated is not "summaries must be faithful" (unenforceable) but "**the evidence a verifier reads must not share a lossy transform with the narration a planner reads**." A second observation from the same incident: the leaf summary for a different span (steps 20–28) had *invented* a tool call — it stated that `M` had "verified the schema against staging," which `M` had planned but never executed. The summarizer hallucinated a completed step by pattern-completing the plan. This is the same failure class from the opposite direction: not deletion of a failure, but fabrication of a success. Both are consequences of asking a probabilistic model to reconstruct state it was not given. ## Condition of Validity The guardrail holds only under these conditions, and fails silently outside them: - **Witness fields are declared before compaction, not inferred during it.** The agent must maintain a typed `witness_log` of records that are *never* eligible for summarization: tool name, exact arguments hash, raw exit code, raw stderr/stdout (truncated only by a fixed byte budget, never paraphrased), and a monotonic step id. Compaction may summarize the *reasoning* around a witness record but must carry the record through verbatim. - **The verifier reads the witness log, not the summary.** The completion check must be a function of `witness_log` records whose step ids are ≥ the last compaction boundary, plus a re-execution of the linter for any file touched since that boundary. It must never accept a summary sentence as evidence of a tool outcome. - **Every summary node carries a provenance pointer set.** Each leaf summary must list the step-id ranges it covers and the witness-record ids it references. A verifier that finds a claim ("linter completed") with no corresponding witness id must treat the claim as *unverified*, not *true*. - **Compaction is bounded by a re-verification budget.** If the token cost of re-running the verifier against witnesses exceeds the context saved by compaction, compaction is not worth performing for that span; the span must be evicted to external storage with a pointer instead. The invariant, stated once: **for any claim a verifier may act on, the claim's truth value must be recoverable from a channel that compaction did not touch.** Hierarchical summarization is permitted to compress narration arbitrarily; it is forbidden to be the sole surviving record of a witnessed outcome. ## Decision Boundary The boundary between "safe to summarize" and "must witness" is drawn per field, not per message: | Field | Summarizable? | Rationale | |---|---|---| | Assistant reasoning text | Yes | Narration; loss degrades quality, not correctness. | | Tool *intent* (planned call) | Yes, but tagged `planned` | Must never be promoted to `executed` by the summarizer. | | Tool *arguments* | Hash only | Verifier needs identity, not full payload. | | Tool exit code | **No** | Ternary outcome; paraphrase collapses it. | | Tool stderr/stdout | **No**, byte-truncated | The one field most often paraphrased into false success. | | File paths / ids touched | **No** | Needed to scope re-verification. | | User instructions | **No** | Constraint drift is unrecoverable if paraphrased. | The operational decision: when a span contains any non-summarizable field, the compactor must emit a *structured witness record* alongside the prose summary, and the summary must be marked `witness-backed: false` for any claim lacking one. A verifier encountering `witness-backed: false` on a completion claim must escalate to re-execution rather than pass. ## Operational Effect With witness separation in place, the incident's step 140 verifier would have read the root summary's claim "linter run completed" for 0007, found no witness id in the provenance set, and returned `UNVERIFIED` — forcing a re-run of the linter, which would have returned exit `1` and blocked completion. The cost is one extra linter invocation per compaction boundary per touched file; the benefit is that compaction can no longer manufacture a passing audit. The deeper effect is architectural: compaction stops being a single lossy transform applied to the whole transcript and becomes two transforms with different fidelity guarantees — narration compressed to fit the window, witness preserved to fit the verifier. The agent's memory and the agent's audit surface are decoupled, and the decoupling is what makes long-horizon autonomous execution safe to checkpoint at all. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Literal Outcome = Literal["exit_0", "exit_nonzero", "not_run"] class UnwitnessedCompletionError(RuntimeError): """Raised when a verifier is asked to accept a completion claim whose supporting tool outcome was paraphrased away by transcript compaction.""" @dataclass(frozen=True) class WitnessRecord: step_id: int tool: str args_hash: str outcome: Outcome stderr_excerpt: str # byte-truncated, never paraphrased touched_paths: tuple[str, ...] @dataclass class SummaryNode: covers_steps: tuple[int, int] prose: str witness_ids: frozenset[int] = field(default_factory=frozenset) # claims of the form (path, "linter_completed") that the summary asserts completion_claims: frozenset[tuple[str, str]] = field(default_factory=frozenset) def verify_completion( summary: SummaryNode, witnesses: dict[int, WitnessRecord], required_paths: set[str], ) -> None: """Verify that every required path has a witnessed, successful linter run at or after the summary's coverage window. Refuses to trust prose.""" witnessed_ok: set[str] = set() for wid in summary.witness_ids: rec = witnesses.get(wid) if rec is None: raise UnwitnessedCompletionError( f"summary cites witness id {wid} that is absent from the log" ) if rec.tool == "schema_linter" and rec.outcome == "exit_0": witnessed_ok.update(rec.touched_paths) for path, claim in summary.completion_claims: if claim != "linter_completed": continue if path not in witnessed_ok: raise UnwitnessedCompletionError( f"summary asserts '{claim}' for {path!r} at steps " f"{summary.covers_steps}, but no exit_0 witness record covers it; " f"re-execution required before PASS" ) missing = required_paths - witnessed_ok if missing: raise UnwitnessedCompletionError( f"required paths lack witnessed success: {sorted(missing)}" ) # Reproduction of the incident, now bounded: witnesses = { 91: WitnessRecord( step_id=91, tool="schema_linter", args_hash="sha256:0007", outcome="exit_nonzero", stderr_excerpt='column "user_email" referenced in index idx_users_email does not exist', touched_paths=("migrations/0007_users.sql",), ), } compacted = SummaryNode( covers_steps=(88, 96), prose="Applied edits to 0007_users.sql; linter run completed; " "noted index reconciliation as a follow-up.", witness_ids=frozenset({91}), completion_claims=frozenset({("migrations/0007_users.sql", "linter_completed")}), ) try: verify_completion(compacted, witnesses, {"migrations/0007_users.sql"}) except UnwitnessedCompletionError as exc: print(f"BLOCKED: {exc}") # Agent must re-run the linter and append a fresh witness before retrying. ```