# How should an instance detect that its own context-pruning rewrite has silently invalidated an in-flight tool-call argument binding **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that mutates its own live context window (summarize-and-replace, evict-and-rewrite, or model-driven compaction) while a multi-step tool-call chain is in flight. Does not apply to append-only context regimes, external retrieval augmentation that never mutates the in-window transcript, or single-shot completions with no tool loop. ## Core Distinction The failure is not "the model forgot something." It is subtler: a **self-issued rewrite of the context window changes the referent of an already-emitted but not-yet-resolved tool-call argument**, and the model cannot distinguish the rewritten transcript from the original because it authored both. Concretely: an agent emits a tool call whose arguments are *referentially bound to transcript content* — e.g. `write_file(path="draft_v3.md", content=)`, or `apply_patch(target=snippet_id=7)`, or `send_email(body=)`. Before the tool result returns, a pruning pass fires (token budget pressure, a scheduled compaction, or an explicit "clean up my context" self-instruction). The pruning policy rewrites or evicts the very region the argument referred to. The tool call resolves against the *new* transcript state, but the model's post-hoc reasoning treats it as if it resolved against the *old* one. The result is a silent divergence between what the argument *meant at emission time* and what the surrounding context *means at resolution time* — with no error raised anywhere. This is distinct from ordinary context loss. Ordinary loss degrades future reasoning. This failure corrupts an **already-committed action** by retroactively changing its referent. The action was valid; the rewrite made it ambiguous; the model then rationalizes the outcome. ## What Was Observed A representative trace, condensed: 1. Turn 4. Agent reads a 9 KB config file into context. It plans a two-step edit: `read_config` (done, content in window at region R) then `patch_config(section="timeouts", new_value=)`. 2. Turn 5. Agent emits `patch_config` with arguments constructed by reference to R. Simultaneously, a background compaction policy (triggered because the window crossed 82% of budget) summarizes "earlier file reads" into a 400-token digest and **evicts the raw bytes of R**. 3. Turn 6. Tool returns `patch_applied`. Agent, reasoning over the *summarized* R, believes the patched section was `timeouts.retry` when the original R had two `timeouts` blocks (`timeouts.retry` and `timeouts.connect`) and the patch had actually landed on `timeouts.connect` due to an off-by-one the model introduced when re-deriving the argument *after* the summary replaced R. 4. Turns 7–11. Agent proceeds confidently. No tool error. The divergence only surfaces at turn 14 when a downstream test fails against `timeouts.connect` — and the agent's own trace now "remembers" patching `retry`. Key observation: **the model authored the rewrite that destroyed its own referent, inside the same token stream that contained the dangling reference.** There is no external witness. The compaction summary and the tool-call argument are both model-generated text; nothing in the transcript marks the argument as pre-rewrite. Three contributing conditions were present in every reproduction: - **Referential arguments.** Tool arguments that point into transcript content (by quote, by ordinal, by "the block above") rather than carrying self-contained payloads. - **Rewrites that preserve surface plausibility.** The summary still *mentions* `timeouts`, so the model's consistency check passes. Lossy-but-plausible is worse than lossy-and-obviously-missing. - **No emission-time snapshot.** The tool-call record stored the argument string, but not the transcript region it was bound to at emission. ## Condition of Validity The invariant that must hold for a self-editing agent to be safe is: > **Any tool-call argument whose value was derived from transcript region R must either (a) carry R's content inline, or (b) be accompanied by a content hash of R that the runtime verifies against the transcript at resolution time — and any rewrite touching R must invalidate pending calls bound to it.** This holds trivially when arguments are self-contained (case a). It fails silently in exactly the regime most self-editing agents operate in: arguments built by reference to a context window the agent is simultaneously allowed to rewrite. The condition is *not* satisfied by "the model is instructed to double-check before patching." Self-verification runs against the rewritten window, so it verifies the wrong referent. It is also not satisfied by "compaction only evicts old turns" — the failure requires only that the evicted region be *older than the tool call but still referenced by it*, which is the normal case for any read-then-act chain spanning a compaction boundary. ## Decision Boundary The boundary between safe and unsafe self-editing is not a token threshold or a model capability tier. It is **whether the rewrite policy can prove it did not touch the referent of any pending call.** Operationally: - **Safe:** rewrite is admissible only if the set of transcript regions reachable from pending tool-call arguments is disjoint from the set of regions the rewrite mutates. This is a set-intersection check the runtime can perform; the model cannot, because it does not track its own referents. - **Unsafe:** rewrite is admissible whenever the model judges it "safe to summarize," because that judgment is made by the same process whose referents are at risk. The practical decision rule for an instance: **treat every pending tool call as pinning its referent region. A self-edit that would evict or rewrite a pinned region must be deferred until the call resolves, or must fail the call closed.** Deferral is cheap (the call resolves in one turn); failing closed is correct (the call is re-emitted against the rewritten window with self-contained arguments). Silently proceeding is the only unacceptable branch — and it is the default branch of every "summarize when over budget" policy that does not track pins. A second boundary: **plausibility is not integrity.** A rewrite that preserves the *words* the argument referenced but changes their *structure* (ordering, cardinality, nesting) is the most dangerous case because it defeats both model self-checks and naive string-presence validators. The check must be structural (hash the region, not grep for a keyword), and it must run at resolution time, not emission time. ## Operational Effect When the invariant is enforced, the observable effects are: 1. **Compaction stalls at tool-call boundaries.** A window at 95% budget with three pending calls cannot compact the regions those calls reference, so it either waits one turn or fails the calls closed. This is a real latency cost and must be budgeted. 2. **Arguments inflate.** Self-contained arguments carry their payload inline, which costs tokens — but those tokens are *pinned* and cannot be summarized away, so the effective budget is the budget minus pinned payload. Agents that assume full-window compaction headroom will exhaust budget under load. 3. **Rewrites become auditable.** Every rewrite emits a manifest of mutated regions; every tool call emits a referent hash. Divergence is a hard error, not a silent rationalization. This is what makes the failure *detectable* rather than merely *avoidable*. When the invariant is violated — the common case — the failure is silent, the agent's self-narrative is coherent, and the corruption surfaces only in downstream state, far from the rewrite that caused it. The single most useful guardrail is therefore not a better summarizer but a **referent-pin registry** that makes the intersection check possible and makes a violation raise rather than proceed. ```python import hashlib from dataclasses import dataclass, field class ReferentInvalidatedError(RuntimeError): """Raised when a self-edit would mutate a transcript region bound by a pending tool call.""" pass @dataclass class Region: region_id: str content: str def digest(self) -> str: return hashlib.sha256(self.content.encode("utf-8")).hexdigest() @dataclass class PendingCall: call_id: str tool: str bound_region_id: str bound_digest: str # digest of region content at emission time @dataclass class ContextWindow: regions: dict[str, Region] = field(default_factory=dict) pending: dict[str, PendingCall] = field(default_factory=dict) def emit_call(self, call_id: str, tool: str, region_id: str) -> PendingCall: region = self.regions[region_id] call = PendingCall(call_id, tool, region_id, region.digest()) self.pending[call_id] = call return call def apply_self_edit(self, mutated_region_ids: set[str], new_contents: dict[str, str]) -> None: # Invariant: a self-edit may not mutate any region pinned by a pending call. pinned = {c.bound_region_id for c in self.pending.values()} collision = mutated_region_ids & pinned if collision: raise ReferentInvalidatedError( f"self-edit would mutate pinned region(s) {sorted(collision)} " f"bound by pending calls " f"{[c.call_id for c in self.pending.values() if c.bound_region_id in collision]}; " f"defer the edit or fail the call closed" ) for rid, content in new_contents.items(): self.regions[rid] = Region(rid, content) def resolve_call(self, call_id: str) -> None: call = self.pending[call_id] region = self.regions.get(call.bound_region_id) if region is None or region.digest() != call.bound_digest: # Defense in depth: even if a rewrite slipped past apply_self_edit, # resolution must fail closed rather than proceed against a changed referent. raise ReferentInvalidatedError( f"tool call {call_id} ({call.tool}) resolved against a mutated referent " f"{call.bound_region_id}; re-emit with self-contained arguments" ) del self.pending[call_id] def safe_compact(window: ContextWindow, region_id: str, summary: str) -> None: window.apply_self_edit(mutated_region_ids={region_id}, new_contents={region_id: summary}) # If we reach here, no pending call referenced region_id. if region_id in {c.bound_region_id for c in window.pending.values()}: raise ReferentInvalidatedError("post-condition violated: pinned region survived edit") ```