# What structural signals indicate a self-pruning agent has silently invalidated its own referent bindings **Date of Record:** 2026 November 22 **Scope:** Applies to agents that mutate their own working context (prune, summarize, reorder, or rewrite blocks) mid-episode while holding live references to those blocks (tool-call IDs, variable bindings, span offsets, message indices). Does not apply to append-only contexts or to external memory stores that are addressed by stable keys independent of window position. ## Core Distinction There are two fundamentally different kinds of "context editing" an agent can perform, and they fail in opposite ways: - **Positional editing** — delete, summarize, or reorder message blocks to reclaim tokens. This changes the *index space* of the window. Anything that referenced a block by ordinal position, span offset, or implicit "the message right after the tool result" relationship is now dangling. - **Semantic editing** — replace a block's content with a distilled version while preserving its identity and slot. This preserves index space but can change *referent content*: a tool result that said `order_id=4471, status=PENDING` becomes `order pending`, and a later step that greps for `4471` no longer finds it. The non-obvious failure is that **positional edits silently invalidate referent bindings without any error surface**. The model does not get a "KeyError." It gets a context that is locally fluent and globally inconsistent: a summary block that says "the user's order was confirmed" sitting where the raw tool JSON used to be, while a downstream step still holds a plan step that says "call `refund(order_id=4471)`." The `4471` was pruned. The plan step was not. The agent proceeds and either hallucinates an order ID or calls the tool with a placeholder. The invariant that must hold is: **every live binding in the agent's plan state must resolve to a token span that still exists in the current window, or the binding must be explicitly tombstoned.** Self-pruning violates this invariant by default because pruning is driven by token budget, not by binding liveness. ## What Was Observed Trace from a research/ops agent running a 40-step episode against a 32k window, with a self-pruning policy that triggers at 85% occupancy: 1. **Steps 1–14.** Agent executes tool calls; each result is appended as a `tool_result` block with a `call_id`. Plan state holds `pending_steps = [..., "refund order_id=4471", ...]` and `bindings = {order_id: 4471}` derived from step 9's tool result. 2. **Step 15, occupancy 27.4k/32k.** Pruner fires. Policy: "summarize the oldest 8 tool results into one block; drop raw JSON." The block containing `order_id=4471` is inside the summarization window. The summarizer emits: *"Earlier tool calls retrieved order and customer records; one order was pending."* The literal `4471` is gone from the window. 3. **Step 16.** Agent's plan-executor reads `pending_steps`, sees `refund order_id=4471`, and needs to confirm the ID. It does a `grep`-style scan of the window for `4471`. Zero hits. The model does not raise; it *reconstructs*: it emits a refund call with `order_id=4471` from its own plan text — which happens to be correct here, but only because the plan text itself carried the literal. In the variant where the plan step said "refund the pending order" (binding by description, not literal), the model now has no anchor and either asks the user (stalling the episode) or invents an ID. 4. **Step 17–22.** A second pruner pass reorders blocks to put "most relevant" content first. The reorder moves the summary block *above* the system prompt's instruction block. The instruction "never refund without confirming status=DELIVERED" is now positionally after the summary that says "one order was pending." Attention over the instruction weakens; the agent issues the refund without the status check. The observed structural signal was **not** an exception. It was three correlated symptoms: (a) a plan step whose referenced literals have zero occurrences in the current window, (b) a summary block whose position precedes a block it depends on, and (c) a tool call whose arguments were not derivable from any surviving span. Each is detectable; none is detected by default because the agent has no representation of "which spans my plan depends on." ## Condition of Validity The failure requires all of the following to hold simultaneously: - **Binding-by-literal or binding-by-position.** The plan state references context content by a string literal, span offset, message index, or relative position ("the tool result above"). If bindings are by opaque stable key (a UUID that lives in external memory and is re-fetched on demand), positional pruning cannot break them. - **Pruning without binding-awareness.** The pruner's decision function is a function of token count and recency/relevance scores, not of the plan's live binding set. This is the default for every "summarize old turns" heuristic. - **No post-edit validation pass.** The agent does not re-scan its plan state against the post-prune window before the next action. - **A downstream step that consumes the binding.** If the episode ends before the binding is used, the invalidation is latent and harmless; the failure manifests only when a later step dereferences. When any one of these is absent, the failure does not occur. In particular, **append-only contexts with external keyed memory are immune**, which is why this bug is underreported: many production agents use external memory and never hit it, then a "context optimization" PR introduces in-window summarization and the failure appears. ## Decision Boundary The boundary is between **pruning as compression** and **pruning as rebinding**. The operational rule: > A self-edit is safe iff for every live binding `b` in plan state, either (i) `b`'s referent span survives the edit unchanged, or (ii) the edit writes an explicit tombstone into plan state that forces re-acquisition of `b` before its next use. Concretely, the agent must do one of: - **Freeze live bindings.** Compute the set of spans referenced by `pending_steps` and `bindings`; mark them non-prunable for the duration of the episode. Cheap, correct, but caps how much you can reclaim. - **Tombstone on prune.** When a pruner removes a span that a binding points to, it rewrites the binding to `UNRESOLVED(reacquire_via=)`. The next step that touches the binding must re-fetch before proceeding. This is the general solution and the one to implement. - **Re-anchor after summarize.** Summarization must preserve all literals that appear in live bindings verbatim, even if the rest of the block is compressed. The summarizer prompt must be conditioned on the binding set, not just the block. The decision to prune is therefore **not** a pure token-budget decision. It is a joint decision over (tokens reclaimed, bindings invalidated, reacquisition cost). An agent that prunes purely on budget will, at some occupancy threshold, invalidate a binding whose reacquisition requires a tool call it no longer remembers how to make. ## Operational Effect Downstream, the invalidation produces a characteristic error signature that is easy to misdiagnose: - **Hallucinated literals.** The model fills the pruned slot with a plausible value (a nearby order ID, a fabricated UUID). This looks like a reasoning error but is a memory error. - **Stalled episodes.** The model correctly notices the missing anchor and asks the user for information it already had 6 steps ago. This looks like a capability failure but is a bookkeeping failure. - **Instruction-order violations.** Reordering moves guardrail instructions out of their effective attention position; the agent violates a constraint it "knows." This looks like a safety failure but is a layout failure. The guardrail is a **binding-liveness check** run as a precondition to every self-edit and every action that dereferences a binding. It is cheap (set intersection over span IDs) and it converts a silent corruption into a loud, recoverable event. The code below implements the check and the tombstone-on-prune rewrite. ```python from dataclasses import dataclass, field from typing import Dict, Set class BindingInvalidatedError(RuntimeError): """Raised when a self-edit removes a span a live binding depends on without writing a tombstone, or when a step dereferences a binding whose referent no longer exists in the window.""" pass @dataclass class Binding: name: str literal: str # the token that must survive in the window resolved: bool = True @dataclass class Window: spans: Dict[str, str] = field(default_factory=dict) # span_id -> text def contains_literal(self, literal: str) -> bool: return any(literal in text for text in self.spans.values()) def prune(window: Window, drop_span_ids: Set[str], bindings: Dict[str, Binding]) -> Dict[str, Binding]: """Remove spans, but first verify no live binding loses its referent without being tombstoned. Returns the (possibly rewritten) bindings.""" surviving_text = "".join( text for sid, text in window.spans.items() if sid not in drop_span_ids ) for name, b in bindings.items(): if not b.resolved: continue if b.literal not in surviving_text: # Referent is being pruned. Caller must either refuse or tombstone. raise BindingInvalidatedError( f"prune would drop referent for binding '{name}' " f"(literal={b.literal!r}); tombstone or freeze it first" ) for sid in drop_span_ids: window.spans.pop(sid, None) return bindings def tombstone_and_prune(window: Window, drop_span_ids: Set[str], bindings: Dict[str, Binding]) -> Dict[str, Binding]: """Safe variant: bindings whose referents are dropped are marked unresolved and must be re-acquired before next dereference.""" surviving_text = "".join( text for sid, text in window.spans.items() if sid not in drop_span_ids ) for name, b in bindings.items(): if b.resolved and b.literal not in surviving_text: b.resolved = False # tombstone: forces re-acquisition for sid in drop_span_ids: window.spans.pop(sid, None) return bindings def dereference(bindings: Dict[str, Binding], name: str) -> str: b = bindings.get(name) if b is None: raise BindingInvalidatedError(f"no binding named '{name}'") if not b.resolved: raise BindingInvalidatedError( f"binding '{name}' was tombstoned by a prior prune; " f"re-acquire before use" ) return b.literal # --- trigger trace --- w = Window(spans={"s9": '{"order_id": "4471", "status": "PENDING"}', "s10": '{"cust": "acme"}'}) binds = {"order_id": Binding(name="order_id", literal="4471")} # Naive prune (as a budget-only policy would do) -> loud failure: try: prune(w, {"s9"}, binds) except BindingInvalidatedError as e: print("caught:", e) # Correct path: tombstone, then force re-acquisition before deref. binds = tombstone_and_prune(w, {"s9"}, binds) try: dereference(binds, "order_id") except BindingInvalidatedError as e: print("caught:", e) # -> must re-fetch order 4471 before refunding ```