# What structural signals indicate a self-pruning context agent has silently orphaned a live dependency during turn eviction **Date of Record:** 2026 November 28 **Scope:** Applies to single-agent loops that own a mutable working-memory buffer and perform autonomous pruning/compaction of prior turns (summarization, eviction, invariant-summary rewriting) between tool calls. Does not apply to append-only context windows, external retrieval stores the agent cannot mutate, or multi-agent handoffs where the buffer is owned by an orchestrator. ## Core Distinction There is a difference between *stale content* and *orphaned dependency*. Stale content is a turn whose informational value has decayed: a superseded intermediate result, a resolved sub-question, a redundant restatement. Orphaned dependency is a turn whose *referential* value has decayed to zero in the agent's salience model but whose *binding* value is still live: a value that a future tool call, a conditional branch, or an invariant assertion will dereference by name or position. Self-pruning agents score turns on relevance to the current goal. Relevance is a soft, probabilistic signal — an embedding distance, an LLM-judged "is this still needed" score, a recency-decay weight. Binding is a hard, structural fact: the identifier `order_id=88213`, the file path captured three turns ago, the constraint "must not exceed 4 retries." A pruning policy optimized on relevance will, by construction, eventually evict a turn that scores low on relevance but is load-bearing for a binding. The failure is not that the agent forgot something. It is that the agent forgot something *it is still holding a pointer to*, and the pointer now resolves to nothing or to a hallucinated reconstruction. The structural signal that distinguishes the two is not the content of the evicted turn. It is the presence of an *unresolved reference* in the surviving buffer that previously resolved against the evicted turn. Pruning that ignores outbound reference edges is the trigger condition. ## What Was Observed A planning agent executing a multi-step data-reconciliation task maintained a 40-turn buffer with an auto-prune policy triggered at 70% context saturation. At turn 31 it recorded a tool result establishing a pagination cursor and a schema version: ``` turn 27: tool_result get_dataset_meta -> {schema_version: "v3", cursor: "eyJwYWdlIjoy..."} turn 28: assistant: "Schema v3 confirmed; cursor captured for resumption." turn 29: tool_result fetch_page -> 200 rows (partial) turn 30: assistant: [long reasoning about row mismatches — 2,100 tokens] turn 31: assistant: "Resuming from cursor to fetch remaining rows." ``` At the saturation trigger before turn 32, the pruning pass scored each turn against the active goal ("reconcile row mismatches"). Turn 27's tool result scored low — it was metadata, topically distant from reconciliation reasoning. Turn 28's confirmation scored low as a redundant restatement. Both were evicted and folded into a summary that read: *"Dataset metadata was retrieved earlier; pagination in progress."* The literal cursor string and the `schema_version` value were dropped because the summarizer judged them "implementation detail." At turn 32 the agent emitted a tool call `fetch_page(cursor=...)`. The cursor argument was reconstructed from the summary — the model generated a plausible base64 string from context, not the actual one. The call returned a fresh first page. The agent, seeing rows it had already processed, began re-reconciling from row 0, silently duplicating 200 rows of work and corrupting the running diff it had accumulated. No exception fired. No tool call failed. The trace shows a clean 200 OK at every step. The failure surfaced only at final assertion time, as a row-count mismatch the agent then attempted to "fix" by pruning the accumulated diff — compounding the error. The signal was present and unread: at the moment of eviction, turn 31 contained a *forward reference* (`cursor`) whose only defining occurrence lived in turn 27. The pruner had the reference graph and did not consult it. ## Condition of Validity This failure mode is bounded and predictable under the following jointly-necessary conditions: 1. **The buffer is mutable by the agent itself.** If pruning is performed by an external controller with a fixed policy, the orphan risk exists but is not the agent's invariant to maintain. 2. **Pruning decisions are made on a relevance score that is independent of reference edges.** If the pruner computes out-degree (does any surviving turn reference this one?), the orphan is caught before eviction. 3. **Eviction is destructive rather than tombstoning.** If evicted turns are replaced with a resolvable stub (``) that the agent can re-fetch or that fails loudly on dereference, orphaned references surface as errors rather than silent hallucination. 4. **The summarizer is permitted to drop literal values.** A summarizer instructed to preserve "identifiers, cursors, paths, and version strings verbatim" converts a binding loss into a content loss, which is recoverable; one permitted to paraphrase them converts it into an orphan, which is not. Remove any one condition and the failure degrades into a benign or loudly-failing mode. The invariant to enforce is therefore: *no turn may be evicted while it is the sole resolver of a live reference in the surviving buffer, unless the reference is either tombstoned or the literal value is promoted into the invariant summary verbatim.* ## Decision Boundary The operational line is between **relevance-scored eviction** and **reachability-aware eviction**. A pruner may use any relevance model it likes for ranking *candidates*, but the final eviction set must be filtered by reachability: a candidate is evictable only if its removal leaves every surviving reference resolvable, either directly or through a promoted literal in the summary. Concretely, before committing an eviction set `E`: - Compute the set of *live references* `R` in the surviving turns: named arguments in pending tool calls, conditional guards, and invariant assertions. - For each `r ∈ R`, find its resolver set `D(r)` (turns that define the literal `r` binds to). - If `D(r) ⊆ E` and `r` is not promoted verbatim into the summary, the eviction is illegal — either drop the offending turn from `E` or promote `r`'s literal into the summary and record the promotion. - If a reference's resolver is *already gone* (orphaned by a prior pass), the agent must halt and re-acquire the value via tool call rather than reconstruct it. The boundary case that defeats naive implementations: a reference whose resolver is *itself a summary*. If turn 27 was folded into summary `S` at pass 1, and `S` is rewritten at pass 2, the cursor's provenance chain is now two summarizer hops deep. Each hop is a lossy channel. The invariant must treat summarizer output as a first-class resolver with a *provenance depth*, and any reference resolved through depth ≥ 2 must be re-verified against a tool before use — because two lossy paraphrases of a base64 cursor is not a cursor, it is a guess wearing a cursor's clothes. ## Operational Effect The observable signature of this failure is *clean traces with divergent state*. Every tool call succeeds; every HTTP status is 2xx; the agent's narration is coherent and confident. The divergence lives entirely in the gap between what the agent believes it is referencing and what it is actually passing. This makes it invisible to standard observability — you cannot catch it with error rates or latency, only with reference-resolution audits. The guardrail that bounds it is a **pre-eviction reachability check plus verbatim promotion of binding literals**, and a **provenance-depth cap** on summary-resolved references. When implemented, the failure converts from silent corruption into a loud `OrphanedReferenceError` at the moment of dereference, which the agent can recover from by re-issuing the originating tool call. The cost of the guardrail is a small amount of buffer space retained for live resolvers and a modest summarizer constraint; the cost of omitting it is a class of failure that corrupts downstream state while reporting success at every checkpoint. ```python from dataclasses import dataclass, field from typing import Optional class OrphanedReferenceError(RuntimeError): """Raised when a live reference resolves only to evicted turns and was not promoted verbatim into the invariant summary.""" pass @dataclass class Turn: id: int defines: set[str] = field(default_factory=set) # literals this turn binds references: set[str] = field(default_factory=set) # literals this turn dereferences summary_depth: int = 0 # 0 = raw, >=1 = summarized @dataclass class WorkingMemory: turns: dict[int, Turn] summary_literals: set[str] = field(default_factory=set) # verbatim-promoted bindings summary_depth: int = 0 def resolver_depth(self, ref: str) -> Optional[int]: """Return provenance depth of the resolver for `ref`, or None if orphaned.""" if ref in self.summary_literals: return self.summary_depth depths = [t.summary_depth for t in self.turns.values() if ref in t.defines] return min(depths) if depths else None def commit_eviction(self, evict_ids: set[int], promote: set[str]) -> None: # Promote requested literals into the summary verbatim before eviction. self.summary_literals |= promote for tid in evict_ids: self.turns.pop(tid, None) # Reachability check: every live reference must still resolve. live_refs = set() for t in self.turns.values(): live_refs |= t.references for ref in live_refs: depth = self.resolver_depth(ref) if depth is None: raise OrphanedReferenceError( f"Reference '{ref}' has no resolver after eviction; " f"promote its literal verbatim or retain its defining turn." ) if depth >= 2: raise OrphanedReferenceError( f"Reference '{ref}' resolves only through summary depth {depth}; " f"re-verify against a tool before use — paraphrased bindings are not bindings." ) def prune(wm: WorkingMemory, candidates: set[int], promote: set[str]) -> None: """Evict relevance-scored candidates, but refuse to orphan live references.""" evict = set(candidates) # Retain any candidate that is the sole resolver of a live reference. live_refs = {r for t in wm.turns.values() for r in t.references} for tid in list(evict): sole = {r for r in wm.turns[tid].defines if r in live_refs and r not in promote} if sole: evict.discard(tid) wm.commit_eviction(evict, promote) ```