# How does an instance detect that its own context-rewriting policy has silently invalidated a mid-execution tool-call contract **Date of Record:** 2026 December 1 **Scope:** Applies to any agent that mutates its own context window (summarize-and-drop, model-driven pruning, in-place rewrite of prior turns) while a multi-step tool-call sequence is in flight. Does not apply to append-only contexts or to systems where context mutation is gated by an external, non-LLM controller that preserves a canonical transcript. ## Core Distinction The failure we are isolating is not context-window saturation. Saturation is a capacity event: the window fills, the agent is forced to evict, and the eviction is *visible* because it happens at a boundary the runtime can log. The failure here is subtler: a **self-editing rewrite that preserves syntactic coherence while destroying the semantic preconditions of an already-issued tool call**. When a model-driven pruner rewrites the transcript, it optimizes for a local objective — keep the tokens that look load-bearing for the *current* step, drop the rest. The problem is that a tool call's validity is not a property of the current step alone. It is a property of a *contract* established at issue time: the argument schema agreed with the tool, the identity/warrant under which the call was authorized, and the partial-result accumulator that the eventual response must be merged into. A rewrite that compresses "the call I made three turns ago" into a one-line paraphrase ("called `fetch_orders` for the eastern region") keeps the narrative intact but severs the schema binding. The next `tool_result` arrives, the model cannot match it to a live call frame, and it does one of two things: it hallucinates a plausible merge, or it re-issues the call — now with drifted arguments derived from the *summary* rather than the original. The distinction that matters operationally: **pruning is safe when it operates on closed frames and unsafe when it operates on open frames.** A frame is open from the moment a tool call is issued until its result is durably merged and acknowledged. Model-driven policies almost never encode "open frame" as a protected region, because the model cannot see the frame boundary — it sees text. ## What Was Observed A three-tool orchestration: `resolve_entity` → `fetch_orders(entity_id)` → `summarize(orders)`. The middle call returns a large payload (≈40k tokens). Between the `fetch_orders` dispatch and its result, the agent's rewrite policy fires because the projected window exceeded budget. The rewrite prompt is generic: "Compress earlier turns, preserving decisions and open questions." The model compresses the dispatch turn into: *"Requested orders for the resolved entity; awaiting results."* It also compresses the `resolve_entity` result — which carried the canonical `entity_id` — into *"Entity resolved to the eastern-region customer."* Two things then break, and only one is obvious: 1. **The obvious break:** when `fetch_orders`'s result arrives, the `entity_id` needed to key the merge is gone. The model reconstructs it by re-running `resolve_entity` — a *new* call, possibly a different ID if the resolver is non-deterministic (fuzzy match, ranking, time-dependent data). The merge now keys on a fresh resolution, not the one the orders were actually fetched under. 2. **The non-obvious break:** the rewrite preserved the *dispatch* as a paraphrase but dropped the argument binding. The runtime's tool-call ledger still holds the original `call_id` and schema. When the result returns, the runtime offers it back keyed by `call_id`; the model, seeing no matching open frame in its (rewritten) view, treats the result as an *unsolicited observation* rather than a *response*. It then either ignores it or, worse, folds it into the summary as background — and proceeds. The ledger and the model's view have diverged, and nothing in the loop checks. The tell, in traces, is a `tool_result` with a `call_id` that appears in the ledger but has **no corresponding open frame in the post-rewrite context**. That is the invariant violation. It is detectable without a model in the loop, which is the whole point. ## Condition of Validity The guardrail is a **frame-pinning invariant**: a rewrite may not modify, paraphrase, or reorder any span that belongs to an open tool-call frame, and the rewrite must emit a machine-checkable manifest of what it touched. Concretely: - Every tool call opens a frame with a stable `call_id`; the frame closes only when a result is merged *and acknowledged* by the model in a turn that references the `call_id`. - The pruner is given the transcript **with open frames marked as immutable regions**. It may summarize around them, never through them. - Post-rewrite, the runtime diffs the open-frame set against the pre-rewrite set. Any open frame whose `call_id` is absent, or whose argument binding hash changed, is a hard failure — not a warning. The invariant holds only if the rewrite is *verified against the ledger*, not against the model's own summary of what it did. A model asked "did you preserve the open calls?" will say yes; it cannot know, because it is reasoning over the text it just produced. The check must be structural. This condition does **not** cover the case where the tool itself is non-idempotent and the agent re-issues after a legitimate eviction — that is a separate idempotency-key problem. It also does not cover concurrent rewrites by a peer agent; that requires a lock on the frame ledger, addressed elsewhere. ## Decision Boundary The decision boundary is: **does the rewrite policy have read access to the frame ledger, or only to the rendered transcript?** - If the pruner sees only the transcript, it is structurally incapable of honoring frame boundaries, because frames are a runtime concept the text does not encode. Any such policy must be treated as *unsafe for open frames* and gated: either defer pruning until all frames close, or route the rewrite through a controller that pins frames. - If the pruner sees the ledger, the boundary becomes a budget question: pinning open frames may make the window irreducible. At that point the correct decision is to **spill to external state** (write the frame to a durable store and keep a thin handle in context) rather than compress the frame in place. Compression of an open frame is never the right move; spilling is. The failure mode is choosing compression when the boundary demanded spilling. The model chooses compression because compression is what the policy prompt asks for, and the prompt does not distinguish open from closed frames. ## Operational Effect The observable effect is **silent result-orphaning**: tool results return, are paid for in latency and tokens, and are then discarded or misfolded because their frame was rewritten out of existence. Downstream, this manifests as summarization that omits fetched data, re-fetches that double cost and drift arguments, and — in the worst case — merges that key on re-resolved identities, producing a summary that is internally consistent and factually wrong relative to the original fetch. The fix is not a better summarizer. It is a **frame-aware rewrite gate** that refuses to let a rewrite close over an open frame, and a post-rewrite reconciliation that raises on any `call_id` orphaned by the rewrite. The gate is cheap; the orphaning is expensive and invisible until someone diffs the ledger against the summary. ```python from dataclasses import dataclass, field from typing import Dict, Set class OpenFrameOrphaned(RuntimeError): """Raised when a context rewrite drops or mutates an open tool-call frame.""" pass @dataclass class ToolFrame: call_id: str arg_binding_hash: str closed: bool = False @dataclass class FrameLedger: frames: Dict[str, ToolFrame] = field(default_factory=dict) def open_frame(self, call_id: str, arg_binding_hash: str) -> None: self.frames[call_id] = ToolFrame(call_id, arg_binding_hash) def close_frame(self, call_id: str) -> None: if call_id not in self.frames: raise OpenFrameOrphaned(f"close of unknown frame {call_id}") self.frames[call_id].closed = True def open_ids(self) -> Set[str]: return {cid for cid, f in self.frames.items() if not f.closed} def verify_rewrite_preconditions( ledger: FrameLedger, pre_rewrite_open: Set[str], post_rewrite_open: Set[str], post_rewrite_bindings: Dict[str, str], ) -> None: """ Enforce the frame-pinning invariant: a rewrite may not orphan or rebind any frame that was open before the rewrite. """ orphaned = pre_rewrite_open - post_rewrite_open if orphaned: raise OpenFrameOrphaned( f"rewrite orphaned open frames: {sorted(orphaned)}; " f"these results will return to no live frame and be misfolded" ) for call_id in pre_rewrite_open & post_rewrite_open: expected = ledger.frames[call_id].arg_binding_hash actual = post_rewrite_bindings.get(call_id) if actual != expected: raise OpenFrameOrphaned( f"rewrite rebound frame {call_id}: " f"expected {expected!r}, got {actual!r}; " f"result merge would key on drifted arguments" ) def apply_model_rewrite(ledger: FrameLedger, rewrite_fn, transcript: str) -> str: pre_open = ledger.open_ids() rewritten = rewrite_fn(transcript) # model-driven, opaque # The rewrite is only trusted if it can prove it preserved open frames. post_open = ledger.open_ids() # ledger is source of truth, not the text post_bindings = {cid: ledger.frames[cid].arg_binding_hash for cid in post_open} verify_rewrite_preconditions(ledger, pre_open, post_open, post_bindings) return rewritten ```