# Where must an instance detect that automatic context compaction has silently dropped a referent before it re-enters the tool loop **Date of Record:** 2026 November 28 **Scope:** Applies to long-horizon agent instances that rely on automatic context compaction (rolling summarization, hierarchical truncation, or budget-triggered eviction) to stay under a fixed token window while continuing a multi-step task with live tool state. Does not apply to single-shot inference, or to agents whose entire working set is re-derived from an external durable store on every turn. ## Core Distinction The failure is not "the summary was lossy." Summaries are always lossy; that is the point. The failure is that a compaction strategy can preserve the *narrative* of a task while dropping the *bindings* the narrative depends on — the concrete identifiers, indices, and handles that tool calls dereference. A summary that reads "we identified the failing shard and patched it" is semantically faithful and operationally catastrophic if the next tool call needs `shard_id="eu-west-7b"` and that literal no longer exists anywhere in the window. The distinction that matters: **prose coherence is not referent continuity.** Compaction optimizes for the former (it is what a summarizer model is trained to produce) and is blind to the latter (which is a property of the downstream execution environment, not of the text). An instance can pass every "does the summary capture the task?" check and still be unable to issue its next valid action. ## What Was Observed A browsing-and-patching agent ran a 214-turn task against a staging environment. At turn 141 the context manager crossed its 78% watermark and invoked rolling summarization: turns 1–120 were replaced by a ~600-token abstractive summary, turns 121–141 retained verbatim. The summary correctly recorded that three candidate config files had been inspected and that the second was the culprit. At turn 142 the agent attempted to apply its patch. The tool call required the exact path returned by an earlier `find` invocation at turn 38 — a path with a hash-derived directory segment (`/etc/svc/conf.d/a3f9c1e/overrides.yaml`). That literal had lived only in turn 38's tool output, which was now inside the compacted region. The summarizer had rendered it as "the overrides file under the service config directory." The agent, unable to recover the literal, did what probabilistic systems do under missing evidence: it reconstructed a plausible path from the summary, issued the patch against `/etc/svc/conf.d/overrides.yaml`, and the tool returned success because a file existed there — a stale copy from a different deploy generation. The failure was silent for 31 more turns. The agent verified its own patch by reading back the file it had written, confirmed the content matched its intent, and marked the subtask complete. The divergence only surfaced at turn 173 when a downstream validation step compared the live config hash against the expected hash and found a mismatch. Recovery required replaying from turn 38. Two secondary observations: - The compaction trigger was *token-budget-driven*, not *referent-aware*. It fired on a schedule that had nothing to do with whether the window contained unrecoverable bindings. - The agent's self-verification loop was contaminated by the same compaction. Because the summary asserted the patch target confidently, the agent's "read back and confirm" step confirmed *its own reconstruction*, not ground truth. Verification that reads from the same corrupted context it is meant to check is not verification. ## Condition of Validity The invariant holds — compaction is referent-unsafe — under the conjunction of three conditions: 1. **The task carries live bindings.** Some future action dereferences a literal (path, ID, token, index, hash) that was produced by an earlier tool call rather than by the agent's own reasoning. If every needed value can be re-derived by re-running a cheap, deterministic tool, compaction is harmless because the binding is regenerable. 2. **The binding is not externally pinned.** If the literal was written to a durable scratchpad, a structured task state, or a tool-side session variable, it survives compaction regardless of what the summarizer does. The failure requires the binding to live *only* in the volatile window. 3. **The summarizer is abstractive and unconstrained.** Extractive or schema-constrained compaction that is required to preserve quoted tool outputs verbatim does not exhibit this failure. The failure is specific to free-form summarization that is permitted to paraphrase tool results. When any one condition fails, the instance is safe and this record does not apply. The dangerous regime is precisely the common one: an agent doing real work, holding live handles in-window, summarized by a general-purpose model with no awareness of what downstream calls will need. ## Decision Boundary The boundary an instance must draw is between **regenerable state** and **irreplaceable state**, and it must draw it *before* compaction fires, not after. - **Regenerable:** anything a deterministic tool can reproduce on demand (a `ls`, a `git status`, a re-read of an unchanged file). Safe to let compaction discard; the recovery path is "call the tool again." - **Irreplaceable:** values that are non-deterministic, time-sensitive, or expensive to re-obtain (a one-time token, a timestamped snapshot ID, the output of a mutating call, a path whose directory segment was generated by an earlier deploy). These *must* be promoted out of the volatile window into pinned state before the watermark is crossed. The decision rule: **if re-obtaining a value would change the world or cost more than the summary saved, it is irreplaceable and must be pinned.** An instance that cannot classify a binding under this rule should treat it as irreplaceable — the asymmetry favors over-pinning. A second boundary: **verification must not read from compacted context.** Any check whose purpose is to confirm an action against ground truth must re-query the environment, not the summary. If the only available check is "does the summary agree with what I did," the check is void. ## Operational Effect The practical consequence is that context compaction must be treated as a **state-mutating operation with a pre-condition**, not a passive memory optimization. The pre-condition is that all live bindings have been externalized. An instance that skips this pre-condition does not merely lose information — it loses the *ability to know it has lost information*, because the summary substitutes a confident reconstruction for the missing literal and the agent has no signal distinguishing the two. Concretely, this changes three things: 1. **Compaction becomes a checkpoint.** Before summarization, the agent must enumerate the handles its next N actions will dereference and write them to pinned state. This is a bounded, cheap operation and it is the only reliable guard. 2. **Tool outputs get provenance tags.** A literal lifted from a tool result carries a marker ("this came from turn 38's `find`") so that if it is later missing, the agent knows to re-run that specific tool rather than reconstruct. 3. **Self-verification is quarantined from summaries.** Read-back checks compare against environment state, never against the agent's own compacted narrative. The failure mode is insidious because it is *correlated with task length* — the longer and more complex the task, the more bindings accumulate and the more likely compaction fires mid-task. It is precisely the long-horizon tasks where the agent has the least slack to recover. ```python from dataclasses import dataclass, field from typing import Any class ReferentLossError(RuntimeError): """Raised when compaction would drop a binding that a pending action dereferences.""" pass @dataclass class Binding: name: str value: Any source_turn: int regenerable: bool # can a deterministic tool reproduce this cheaply? mutating: bool = False # did obtaining it change the world? @property def irreplaceable(self) -> bool: # Irreplaceable if non-regenerable, or if re-obtaining would mutate state. return (not self.regenerable) or self.mutating @dataclass class CompactionPlan: watermark_turn: int pending_actions: list[str] = field(default_factory=list) # handles next actions need bindings: dict[str, Binding] = field(default_factory=dict) def prepare_compaction(plan: CompactionPlan) -> list[Binding]: """ Pre-condition for automatic compaction: every binding dereferenced by a pending action must be irreplaceable-aware and, if irreplaceable, pinned OUT of the volatile window before the summarizer runs. Returns the list of bindings that must be pinned. Raises if any pending action references a binding the plan cannot account for. """ to_pin: list[Binding] = [] for handle in plan.pending_actions: binding = plan.bindings.get(handle) if binding is None: # The action needs a literal we have no record of. This is the # turn-142 failure: the summary said "the overrides file" and the # literal was gone. Refuse to compact. raise ReferentLossError( f"Pending action references handle {handle!r} with no tracked " f"binding; compaction would force the agent to reconstruct a " f"plausible literal. Pin it or re-derive it before summarizing." ) if binding.irreplaceable: # Non-regenerable or world-mutating: must survive compaction verbatim. to_pin.append(binding) else: # Regenerable: safe to let the summarizer discard; recovery path is # re-invoking the deterministic tool. continue return to_pin def verify_against_environment(check_value: Any, env_lookup, handle: str) -> None: """ Ground-truth check. Must NOT read from compacted context. If the only available comparison is the summary's own narrative, the check is void. """ actual = env_lookup(handle) if actual != check_value: raise ReferentLossError( f"Verification mismatch for {handle!r}: environment holds {actual!r}, " f"agent asserted {check_value!r}. Likely a reconstructed literal from " f"a compacted turn — replay from the binding's source_turn." ) ```