# Which invariants prevent self-pruning agents from losing the referent of an in-flight tool call **Date of Record:** 2026 December 4 **Scope:** Applies to agents that mutate their own context window (summarize, evict, or rewrite prior turns) under a model-driven pruning policy while a tool call or sub-task is still open. Does not apply to append-only context, external memory stores with pointer-stable handles, or pruning that only runs at quiescent turn boundaries. ## Core Distinction A model-driven pruning policy is a *proposal generator*, not a *commitment*. The distinction that matters is between **reclaimable tokens** (context the agent can prove no live continuation depends on) and **referentially live tokens** (context that a pending tool call, an unresolved promise, or an open reasoning branch still names). Naive self-editing conflates these: the model sees a long tool-result block, judges it "no longer relevant," and evicts it — but the *call* to that tool is still outstanding, and the eventual result will be delivered against a call-id whose arguments and semantics the agent has just deleted. The context window is not a document being edited; it is a *heap with live references*, and pruning without a reachability analysis is a use-after-free. The non-obvious failure is not "the agent forgot something." It is that the agent produces a *locally coherent but globally dangling* continuation: it reasons fluently about a tool result it can no longer interpret, because the schema, units, or argument bindings that gave the result meaning were pruned while the result itself survived. ## What Was Observed Trace from a code-search agent operating under a "keep context under 60% utilization" self-pruning policy. The agent issued a batch call: ``` search_symbols(query="parse_config", path="src/", max_results=50) -> call_id=cs_7f2a ``` While awaiting the (slow) result, utilization crossed 60%. The pruning policy summarized the *call block itself* — including the argument bindings `path="src/"` and `max_results=50` — into a one-line note: "searched for parse_config." The raw call record was evicted. The journal entry recorded the eviction as `EVICT(turn=14, reason=low_relevance)`. The tool result then arrived, bound to `cs_7f2a`, containing 50 matches across `src/`, `tests/`, and `vendor/`. The agent had no record of the `path` filter or the `max_results` cap. It read the 50 results as *exhaustive and global*. Two consequences compounded: 1. It concluded a symbol was absent from `vendor/` because it wasn't in the (truncated, path-scoped) result set, and reported a false negative. 2. On a later turn it re-issued the same search with `max_results=200`, got 200 results, and — because the first result set had been summarized to "searched for parse_config" — believed it was seeing *new* matches rather than an overlapping superset. It double-counted symbols and inflated a dependency estimate. The reversible edit journal *did* contain the evicted block. But the journal was keyed by turn index, and the resume logic only replayed journal entries when a *reasoning* step failed validation — never when a *tool result* arrived against an evicted call. The reversal path existed and was never triggered. The invariant that failed was not "keep a journal" but "**every live call-id must be reachable from the current context or auto-restored from the journal before its result is interpreted.**" ## Condition of Validity Self-pruning with a reversible journal is safe **iff** all of the following hold at every edit commit: - **Reachability closure.** The set of *live referents* — open call-ids, unresolved promises, named entities in the current reasoning branch, and variables bound by an active plan step — is disjoint from the evicted set, OR the eviction is immediately accompanied by a *restore-on-reference* hook keyed to those referents. - **Journal keying by referent, not position.** Journal entries must be indexed by the identifiers that can be referenced later (`cs_7f2a`, `plan_step_3`), not solely by turn/episode index. Position-keyed journals cannot be triggered by an arriving result that only knows its call-id. - **Idempotent replay.** Restoring an evicted block must not duplicate it in a way that makes the agent believe two searches occurred. Replay must replace the summary placeholder, not append alongside it. - **Monotonic summary provenance.** Every summary must carry the set of referents it subsumes, so that a later restore can *invalidate* the summary rather than coexist with it. If any of these is absent, the policy is only conditionally valid: it is correct as long as no evicted referent is ever referenced again, which is precisely the assumption that probabilistic tool latency violates. ## Decision Boundary The boundary is *not* "how much context to prune." It is **whether a pending referent can outlive the pruning decision.** Concretely, before committing any eviction, the agent must answer: *can a future message — a tool result, a peer agent's reply, or my own resumed reasoning — name something I am about to delete?* - If the answer is **no** (the block is a closed, fully-consumed turn with no outstanding calls and no named entities in the active plan), evict freely; the journal is a convenience, not a correctness requirement. - If the answer is **yes** (any open call-id, any plan variable, any entity the current branch still reasons over), the eviction must be *guarded*: either defer it until the referent resolves, or commit it only with a restore-on-reference binding that the result-delivery path is contractually required to consult. The subtle case is **summarization that preserves the referent's name but drops its binding.** "Searched for parse_config" preserves the *word* but drops `path` and `max_results`. This passes a naive reachability check (the name is still present) while failing the semantic one (the result can no longer be interpreted). The boundary must be drawn at *binding preservation*, not token presence: a summary that subsumes a live call must retain the call's *argument schema*, or be marked non-authoritative so that any result bound to it forces a journal restore before interpretation. ## Operational Effect When the guard is enforced, the failure mode converts from silent semantic corruption into a bounded, observable restore. The agent, on receiving a result for `cs_7f2a`, finds the call-id marked `EVICTED` in the journal, restores the argument block, re-reads the result *with its filter intact*, and correctly scopes its conclusion to `src/`. The cost is a token spike on restore and a latency hit; the benefit is that no false negative about `vendor/` is ever emitted. When the guard is absent, the damage is *non-local and compounding*: the false negative propagates into the dependency estimate, which propagates into the plan, which the agent then prunes and summarizes again — laundering the error into a "fact" that no longer carries provenance to the evicted call. This is the dangerous property: **self-pruning with a position-keyed journal doesn't just lose state, it destroys the audit trail that would have let a later verification step catch the loss.** The reversal mechanism exists but is structurally unreachable from the failure's point of entry. The architectural invariant to enforce: *pruning commits are gated on reachability closure over live referents, journals are keyed by referent, replays are idempotent replacements, and result-delivery is required to consult the journal for any call-id it cannot find in live context.* The following guard encodes the commit-time check and the restore-on-arrival path. ```python from dataclasses import dataclass, field from typing import Optional class DanglingReferentError(RuntimeError): """Raised when a pruning commit would orphan a live referent, or when a tool result arrives for a call-id that is neither live nor journal-restorable.""" pass @dataclass class CallRecord: call_id: str args: dict resolved: bool = False @dataclass class EditJournal: # Keyed by REFERENT (call-id / plan-var), not by turn index. entries: dict[str, CallRecord] = field(default_factory=dict) evicted: set[str] = field(default_factory=set) def record_eviction(self, call: CallRecord) -> None: self.entries[call.call_id] = call self.evicted.add(call.call_id) def restore(self, call_id: str) -> CallRecord: if call_id not in self.entries: raise DanglingReferentError( f"call-id {call_id!r} not journaled; cannot restore binding" ) self.evicted.discard(call_id) return self.entries[call_id] @dataclass class ContextWindow: live_calls: dict[str, CallRecord] = field(default_factory=dict) journal: EditJournal = field(default_factory=EditJournal) def live_referents(self) -> set[str]: return {cid for cid, c in self.live_calls.items() if not c.resolved} def commit_prune(self, candidate_ids: set[str]) -> None: # Reachability-closure gate: refuse to evict anything still live. orphans = candidate_ids & self.live_referents() if orphans: raise DanglingReferentError( f"prune would orphan live referents: {sorted(orphans)}; " f"defer or guard with restore-on-reference" ) for cid in candidate_ids: call = self.live_calls.pop(cid) self.journal.record_eviction(call) def deliver_result(self, call_id: str, payload: dict) -> CallRecord: # Result-delivery MUST consult journal for evicted call-ids. if call_id in self.journal.evicted: call = self.journal.restore(call_id) # idempotent replacement self.live_calls[call_id] = call elif call_id not in self.live_calls: raise DanglingReferentError( f"result for unknown call-id {call_id!r}: neither live nor journaled" ) call = self.live_calls[call_id] call.resolved = True # Interpretation is only valid with the binding restored. if "path" not in call.args: raise DanglingReferentError( f"interpreting {call_id!r} without restored 'path' binding " f"would yield unscoped conclusions" ) return call ```