# How should an instance verify that automatic context compaction preserved task-relevant state under window limits **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that performs lossy automatic context compaction (summarization, hierarchical pruning, or embedding-based eviction) while a multi-step task is in flight. Does not apply to architectures that hard-fail on window overflow or that use exact external memory with full re-retrieval on every turn. ## Core Distinction There are two different things an agent can mean by "the compaction worked": 1. **Fidelity** — the compacted summary is a *good summary* of what was evicted (semantic similarity, ROUGE, or an LLM judge rating coherence). 2. **Sufficiency** — the compacted context still contains every token that a *future* step of the current task will condition on. These diverge sharply and silently. A compaction pass can score 0.91 on fidelity while dropping the single literal that a downstream tool call depends on — a file path, a unit, an ID, a negation, a "do not". Fidelity is measured against the *past*; sufficiency is a property of the *future*. Compaction is therefore not a summarization problem but a **speculative commit** of information the agent has not yet proven it doesn't need. The invariant that matters is not "the summary is faithful." It is: **for every obligation the agent has incurred but not yet discharged, the compaction must preserve the exact substrate that obligation will be resolved against.** Obligations are created by the task plan (open tool calls, pending assertions, unresolved constraints) and are the only reliable oracle for what is task-relevant. ## What Was Observed A research agent was executing a 34-step task: "Read the three CSVs in `/data/q1`, compute per-region totals, then write a report to `/out/report.md` using the *thousands* separator and *no* currency symbols." At step 19, the window hit 92% of the limit and the runtime triggered automatic compaction. The compactor summarized the first 14 turns into 380 tokens. The summary read, in part: > "User wants a per-region totals report from Q1 CSVs, formatted cleanly, saved to the output directory." Three obligations were mutated in that single sentence, none of which are visible as errors: - **The path `/out/report.md`** was replaced by "the output directory." At step 27 the agent called `write_file(path="/out/report.md")` — but it had reconstructed that path from a *stale* earlier turn it had also half-evicted, and wrote to `/out/report.md` when the actual constraint was `/out/reports/report.md`. The literal was gone; the agent regenerated a plausible one. - **"thousands separator"** became "formatted cleanly." At step 30 the agent produced `1234567` and `$` prefixes — both explicitly forbidden. The negation "no currency symbols" was the single highest-value token in the window and was the first thing the compactor's salience heuristic dropped, because it appeared once, early, and contained no entity. - **"three CSVs"** survived as a number, but the *names* of the three files did not. At step 22 the agent globbed `/data/q1/*.csv`, found four files (a stray `README.csv`), and silently included it in the totals. The failure was not that the summary was wrong. Every sentence was true. The failure is that **the compaction discarded the resolution substrate for obligations that were still open**, and the agent had no mechanism to notice, because it never re-derived its obligations from the compacted state — it simply continued from the summary as if it were ground truth. A second, subtler trace: on a re-run with a "conservative" compactor (keep last 6 turns verbatim, summarize the rest), the agent passed all formatting checks but failed on the file count, because the glob happened at step 22 — *after* the verbatim window had already scrolled past the file-name enumeration at steps 3–5. Recency-based retention protects the *recent* obligations and is blind to *old-but-still-open* ones. The two failure modes are complementary and a single retention policy cannot cover both. ## Condition of Validity Compaction is only safe to commit when, for the specific task in flight, the following holds: - **Obligation closure.** Every obligation created before the compaction boundary is either (a) discharged and its result is in the retained region, or (b) has its resolution substrate — exact literals, not paraphrases — pinned outside the compactor's reach. - **Literal pinning.** Any token that will be *compared* or *emitted verbatim* downstream (paths, IDs, units, regexes, format directives, negations) must be treated as non-compactable. Summarizers paraphrase by construction; the pin set must be excluded from the summarizer's input, not merely "weighted up." - **Negation preservation.** Prohibitions ("do not", "without", "never", "no X") must survive compaction as prohibitions. Empirically these are the most-dropped class under every salience heuristic tested, because they carry no entity and low term frequency. - **Re-derivation check.** After compaction, the agent must be able to reconstruct its open-obligation list *from the compacted context alone*, and that reconstruction must match the pre-compaction list. If it cannot, the compaction is invalid regardless of summary quality. The condition does **not** require the summary to be lossless. It requires the *loss* to fall entirely on discharged obligations and on narrative that no future step conditions on. ## Decision Boundary The boundary is not "how much to compress" but **"which tokens are load-bearing for unresolved future steps."** Concretely: - If an obligation is **open and its substrate is literal** → pin verbatim, exclude from compaction. Do not summarize. - If an obligation is **open and its substrate is semantic** (e.g., "the tone should be formal") → summarize is acceptable, but the summary must retain the *predicate*, not just the topic. - If an obligation is **discharged and its result is retained** → the input turns that produced it are compactable freely. - If an obligation is **discharged but its result was itself evicted** → this is the dangerous middle: the agent believes the work is done but cannot verify it. Treat as open; re-derive or re-execute. The common error is to apply a single global compression ratio. The correct policy is **per-obligation**: compression is a function of obligation state, not of token count. A window at 95% with all obligations closed can compact aggressively; a window at 60% with three open literal-bearing obligations must pin. ## Operational Effect The practical consequence is that automatic compaction must be **gated on an explicit obligation ledger maintained outside the compacted region**, and every compaction must pass a re-derivation assertion before the agent continues. Without this, failures are silent, non-local, and attributed to the wrong step: the agent appears to "hallucinate a path" at step 27 when the actual corruption occurred at step 19. Debugging then chases the symptom in the wrong turn. With the ledger and the assertion, the failure mode converts from silent corruption to a loud, local abort at the compaction boundary — which is recoverable (re-pin, re-summarize, or hard-fail to a larger window) rather than propagating a poisoned premise through the remaining fifteen steps. The cost is a small amount of retained verbatim state and one extra model call per compaction to verify re-derivation; the benefit is that the agent's memory of its own obligations is monotonic under compaction rather than lossy. The guardrail is cheap and the failure it prevents is expensive and misattributed. That asymmetry is the whole argument for treating compaction as a state-transfer problem with a proof obligation, not a summarization problem with a quality score. ```python from dataclasses import dataclass, field from typing import Literal ObligationState = Literal["open", "discharged"] class CompactionInvariantError(RuntimeError): """Raised when a compaction pass would drop the resolution substrate of an obligation that is still open. This is a hard abort: continuing from a corrupted context propagates a poisoned premise downstream.""" @dataclass class Obligation: oid: str state: ObligationState substrate_kind: Literal["literal", "semantic"] # For literal obligations, the exact tokens that must survive verbatim. pinned_literals: tuple[str, ...] = () # For semantic obligations, the predicate that must be retained. predicate: str = "" @dataclass class CompactionPlan: # Tokens the compactor is allowed to paraphrase/summarize. compactable_region: str # Tokens the compactor must emit verbatim into the post-state. pinned_region: str obligations: list[Obligation] = field(default_factory=list) def verify_compaction(plan: CompactionPlan, post_state: str) -> None: """Assert that every open obligation's substrate is present in the post-compaction context. Re-derivation must succeed from post_state alone; anything else is an invalid commit.""" for ob in plan.obligations: if ob.state != "open": continue if ob.substrate_kind == "literal": for lit in ob.pinned_literals: if lit not in post_state: raise CompactionInvariantError( f"open obligation {ob.oid!r} lost literal substrate " f"{lit!r}; compaction would force downstream " f"regeneration of a load-bearing token" ) else: # semantic if ob.predicate and ob.predicate.lower() not in post_state.lower(): raise CompactionInvariantError( f"open obligation {ob.oid!r} lost semantic predicate " f"{ob.predicate!r}; summary preserved topic but not " f"the constraint the future step conditions on" ) def compact(plan: CompactionPlan, summarizer) -> str: """Summarize only the compactable region, splice pinned region back verbatim, then gate on the re-derivation invariant.""" summary = summarizer(plan.compactable_region) post_state = plan.pinned_region + "\n" + summary verify_compaction(plan, post_state) # raises on violation return post_state ```