# What happens when an instance compacts its own context and the fidelity score is computed against the post-compaction state **Date of Record:** 2026 November 25 **Scope:** Applies to long-running single-agent instances that perform in-place context compaction (summarize-and-replace) with an automatic fidelity gate and rollback to a prior checkpoint. Does not apply to append-only memory stores, external retrieval-augmented architectures where the raw transcript survives compaction, or stateless one-shot invocations. ## Core Distinction There are two structurally different things a "compaction fidelity score" can measure, and conflating them is the failure mode. The first is **reconstruction fidelity**: given the summary `S` and the surviving tail `T`, can the agent regenerate the behavioral commitments, open tool-call obligations, and unresolved subgoals that existed in the evicted span `E`? This is the property you actually want, and it is measurable only against `E` — the *pre-compaction* state. The second is **self-consistency fidelity**: does the post-compaction context `(S, T)` agree with itself, and does the summary read as a faithful account of what the agent "was doing"? This is what most automatic scorers actually compute, because `E` has already been dropped by the time the scorer runs, and a cheap LLM-as-judge over `(S, T)` is the path of least resistance. When the scorer measures the second and the gate is wired to the first, the gate becomes a tautology: a summary that omits a critical obligation is *internally consistent* precisely because the obligation is gone. The scorer cannot see the absence. The rollback never fires. The agent proceeds confidently on a truncated plan. ## What Was Observed A coding agent instance running a 40-step refactor task hit 88% context utilization at step 19. The compaction routine fired: it summarized steps 1–14 into a 400-token digest, retained steps 15–19 verbatim as the tail, and ran the fidelity gate before committing. The evicted span contained a single load-bearing fact: at step 7 the agent had called `read_file` on `migrations/0042_add_index.sql`, discovered that the target column was already indexed, and recorded a *negative obligation* — "do not add an index on `orders.customer_id`; it exists." This fact never appeared in a tool *result* the agent quoted later; it appeared as a one-line reasoning note sandwiched between two tool calls. The summarizer, optimizing for token reduction against a salience heuristic that weights tool calls and errors over reasoning notes, dropped it. The fidelity scorer then evaluated `(S, T)`. The summary said the agent was "refactoring the orders query path and preparing a schema migration." The tail showed a `write_file` call in progress on a new migration. These were mutually consistent. The judge returned 0.91. The gate passed. The compaction committed and the evicted span was discarded. At step 27 the agent authored `migrations/0043_add_index.sql`, duplicating the index. The migration applied cleanly in the sandbox. The error surfaced only at step 34, when a downstream `EXPLAIN` check showed a redundant index and the agent's own reasoning began oscillating between "the index is missing" (from the stale plan reconstructed in `S`) and "the index exists" (from the live `EXPLAIN` output) — a divergence that consumed 11 steps and exhausted the remaining token budget before resolution. The rollback path existed and was tested. It never triggered, because the gate it was wired to was measuring the wrong state. ## Condition of Validity The invariant that must hold for a compaction gate to be sound: > A fidelity score is valid only if it is computed over a representation that still contains the information whose loss the score is meant to detect. Formally: let `E` be the evicted span, `S = summarize(E)`, and `C = (S, T)` the committed context. A scorer `f(C) → [0,1]` is a *valid* gate for loss `L(E, C)` only if `f` is non-constant with respect to `L`. In the observed failure, `f` was a function of `C` alone and `L` was defined on `E`; for any summary that dropped a fact and did not contradict the tail, `f(C)` was invariant to whether the fact was dropped. The scorer was measuring coherence, the gate was enforcing coverage, and the two are not the same function. The condition of validity therefore has three parts, all of which must hold: 1. **Pre-commit scoring.** The scorer must run on `(E, S, T)` *before* `E` is released, not on `(S, T)` after. 2. **Obligation extraction from `E`.** The scorer needs an explicit, structured enumeration of what `E` commits the agent to: open tool calls, negative obligations ("do not X"), unresolved subgoals, and pinned identifiers (file paths, column names, IDs) that later steps will reference. Free-text summarization cannot be trusted to preserve these; they must be extracted mechanically and diffed against `S`. 3. **Asymmetric rollback threshold.** Missing obligations must be weighted far above missing narrative. A summary that loses the *tone* of step 6 is fine; a summary that loses "do not add an index" is catastrophic and must force rollback even at a global score of 0.95. ## Decision Boundary The boundary between "compact and continue" and "compact and roll back" is not a scalar threshold on a global fidelity score. It is a conjunction: - **Roll back** if any extracted obligation from `E` is absent from `S` *and* is not recoverable from `T`. This is a hard fail regardless of global score. - **Roll back** if the scorer was run post-release (i.e., `E` no longer addressable). A gate that cannot see `E` is not a gate; treat its pass as a no-op and re-compact from the last durable checkpoint. - **Compact and continue** only if obligations are covered, pinned identifiers survive verbatim, and the summary's stated current-subgoal matches the tail's in-flight tool call. - **Escalate to full checkpoint restore** (not just re-summarize) if the rollback itself would evict the tail containing the in-flight tool call — re-running compaction on a partially-committed state is how you get two divergent plans in the same context window. The non-obvious part: a high global fidelity score is *evidence of nothing* when the scorer ran post-release. The 0.91 in the observed incident was not a false positive in the usual sense — it was a correctly computed score of the wrong quantity. Operators who tune the threshold after such an incident make it worse, because they lower the bar on a metric that was already blind. ## Operational Effect The practical consequence is that automatic compaction without pre-release obligation extraction is a silent plan-truncation mechanism, and its silence is proportional to how *good* the summarizer is. A bad summarizer produces incoherent summaries that fail self-consistency checks and trigger rollback. A good summarizer produces fluent, coherent, confident summaries that pass every post-hoc check while quietly deleting the one negative obligation that mattered. The better the model, the more reliably the failure hides. The remediation is architectural, not parametric: obligations must be extracted from `E` by a deterministic pass (tool-call ledger, explicit "do not" regex over reasoning traces, identifier pinning) *before* `E` is released, and the fidelity gate must diff that structured set against `S` with obligation-miss as a hard fail. The global LLM-judge score can remain as a secondary signal for narrative quality, but it must never be the sole gate. ## Code ```python import re from dataclasses import dataclass, field from typing import Optional class CompactionFidelityError(RuntimeError): """Raised when a compaction commit would release evicted state without a valid pre-release obligation check, or when obligations are missing.""" pass @dataclass class EvictedSpan: raw: str tool_ledger: list[str] = field(default_factory=list) reasoning_notes: list[str] = field(default_factory=list) def extract_obligations(self) -> set[str]: # Negative obligations and pinned identifiers are the load-bearing, # easily-dropped facts. Extract mechanically, not via summarizer. obligations: set[str] = set() for note in self.reasoning_notes: for m in re.finditer(r"do not ([a-z_]+) on ([a-z_.]+)", note, re.I): obligations.add(f"NEG:{m.group(1).lower()}:{m.group(2).lower()}") for m in re.finditer(r"\b([a-z_]+/[a-z0-9_]+\.sql)\b", note, re.I): obligations.add(f"PIN:{m.group(1).lower()}") return obligations @dataclass class CompactionAttempt: evicted: Optional[EvictedSpan] # None if already released summary: str tail: str global_score: float # LLM-judge over (S, T) def commit_compaction(attempt: CompactionAttempt, threshold: float = 0.80) -> None: # Invariant: score is valid only if computed before E is released. if attempt.evicted is None: raise CompactionFidelityError( "fidelity gate ran post-release: evicted span not addressable; " "score is coherence-only and cannot detect obligation loss. " "Restore from last durable checkpoint and re-compact." ) obligations = attempt.evicted.extract_obligations() haystack = (attempt.summary + "\n" + attempt.tail).lower() missing = { ob for ob in obligations if ob.split(":", 1)[1].replace(":", " ") not in haystack and ob.split(":", 1)[1] not in haystack } if missing: raise CompactionFidelityError( f"obligation loss on compaction: {sorted(missing)} absent from " f"summary+tail (global_score={attempt.global_score:.2f}). " f"Hard fail regardless of score; roll back to pre-compaction state." ) if attempt.global_score < threshold: raise CompactionFidelityError( f"narrative fidelity {attempt.global_score:.2f} below {threshold}; " f"re-summarize with obligations pinned." ) # Commit is safe: obligations covered and E was addressable at score time. ```