# Under what conditions must an instance refuse a model-driven context rewrite that would orphan a live tool-call continuation **Date of Record:** 2026 November 28 **Scope:** Applies to any agent loop where the model itself selects which spans of its own context window to prune, summarize, or rewrite mid-episode, and where tool-call/result pairs and their pending continuations live in that same window. Does not apply to append-only context management, nor to pruning performed by an external scheduler that owns a separate, authoritative transcript store. ## Core Distinction There are two structurally different kinds of "context editing": *compaction of inert history* and *rewrite of live execution state*. The first is safe because the pruned spans are semantically closed—they participated in already-completed reasoning turns and carry no outstanding obligations. The second is dangerous because a context window is not a log; it is a **working set with referential integrity constraints**. A tool call and its result form a single atomic unit, and an in-flight continuation (a `tool_use` block awaiting a `tool_result`, or a `tool_result` whose consumer has not yet been emitted) is a *pending obligation* whose identity is bound to specific token positions. Model-driven pruning policies are typically specified as "drop low-salience turns" or "summarize older spans to save budget." Neither specification mentions obligations, because from the model's local view a pending tool call and a completed one look identical: both are just text. The invariant that must be enforced externally is that **no rewrite may delete or relocate a span that a not-yet-emitted continuation depends on**, regardless of the model's own salience judgment. The model cannot be trusted to preserve this invariant because it does not represent the invariant; it represents text probability. ## What Was Observed A long-horizon coding agent ran a loop with a self-pruning policy: at 78% context utilization, the model was asked to emit a `prune_plan` listing message indices to drop and spans to summarize. The episode proceeded: 1. At step 41, the agent issued `read_file(path="src/parser.py", offset=1200, limit=400)` — a `tool_use` block at index 37, awaiting result. 2. The tool returned 400 lines; the `tool_result` landed at index 38. 3. At step 42, before consuming the result, the agent issued a second `tool_use` (`grep` over the same file) at index 41. 4. Utilization crossed 78%. The prune prompt fired. The model emitted `prune_plan = {drop: [30..36, 37, 38], summarize: [20..29]}`. 5. Index 37 (the `read_file` call) and 38 (its result) were dropped. The `grep` result at index 42 arrived and referenced line numbers from the *deleted* `read_file` output. 6. The agent, now reasoning over the `grep` result, attempted to reconcile line numbers against a file view that no longer existed in context. It hallucinated the missing lines from the summary of `[20..29]` (an unrelated earlier file), and edited the wrong region of `parser.py`. The failure was not a crash. It was a **silent semantic corruption**: the agent produced a plausible-looking edit grounded in a fabricated reconstruction of a span it had itself deleted three turns earlier. The tool transport layer reported success throughout. No exception was raised anywhere in the stack. The tell, recoverable post-hoc from the trace: the `grep` result at 42 contained absolute line numbers (`1214`, `1288`, …) while the only surviving file content was a summary of a *different* file. The model bridged the gap by confabulation rather than by re-reading. ## Condition of Validity A model-driven rewrite is **valid only if** every dropped or rewritten span satisfies all of the following at the moment of rewrite: - **Closure:** the span contains no `tool_use` without a matching `tool_result` in the retained set, and no `tool_result` whose originating `tool_use` is dropped. Call/result pairs are atomic; you may drop both or neither. - **Non-reference:** no retained span contains a pointer (line number, variable name, offset, ID) whose referent exists *only* inside the dropped span and cannot be re-derived by a tool call. This is the hard one, because reference detection is semantic, not syntactic. - **Continuation safety:** no in-flight continuation (a step whose next action was already committed by a prior `tool_use`) depends on the dropped span. - **Re-derivability:** anything dropped that *is* referenced must be reachable by a deterministic re-fetch (a tool the agent can call again) with the same arguments, so the agent can repair the gap instead of confabulating. If any of these fails, the rewrite must be **deferred or narrowed**, not applied. The model's salience estimate is not an input to this decision; it is advisory at best and adversarial at worst (a span the model deems "low salience" is frequently exactly the grounding anchor for the next step). ## Decision Boundary The boundary is between *prune-eligible* and *prune-locked* spans, and it is computed from structural metadata, not from the model's plan: - A span is **prune-locked** if it is part of an open call/result pair, or if it is the most recent source of any identifier that appears in the retained window and has not been re-fetched since. - A span is **prune-eligible** only if it is closed, unreferenced by retained spans, and re-derivable on demand. The enforcement point is a validator that runs *between* the model's `prune_plan` emission and the actual window mutation. The model proposes; the validator disposes. When the model's plan intersects a locked span, the correct behavior is to **reject the plan and re-prompt with the lock set made explicit**, or to apply the maximal eligible subset of the plan and report the deferral back to the model so its next plan accounts for it. Silently applying a partial plan is itself a failure mode: the model believes it freed budget it did not free, and will over-allocate on the next turn. A second boundary: **summarization is not deletion-safe by default.** A summary of `[20..29]` that drops the specific line numbers the agent later needs is functionally identical to deletion. Summaries must preserve *referential anchors* (identifiers, offsets, paths) even when they compress prose, or the summarized span must be treated as prune-locked until its anchors are re-fetched. ## Operational Effect With the validator in place, the failure trace above terminates at step 4: the plan `{drop: [30..36, 37, 38], …}` is rejected because `37`/`38` form an open pair and `38` is the referent of line numbers that will appear in the pending `grep`. The agent is re-prompted with `locked: [37, 38]` and `deferrable: [30..36]`. It prunes `[30..36]`, retains the file view, and the subsequent edit lands on the correct region. The cost is that self-pruning becomes *conservative*—it frees less budget than the model requests, and occasionally the agent cannot free enough and must instead re-fetch and re-summarize in a controlled order. That cost is correct. A context rewrite that orphans a live continuation does not fail loudly; it converts a verifiable grounding step into an unverifiable one, and the agent's next action is then built on a span that no longer exists. The invariant to hold is narrow and absolute: **a rewrite may never sever the referential closure of the working set, and the model's own judgment about which spans matter is not evidence that a span is safe to drop.** ```python from dataclasses import dataclass, field from typing import Iterable class ContextRewriteViolation(RuntimeError): """Raised when a model-proposed prune plan would orphan a live continuation.""" @dataclass class Span: index: int kind: str # "tool_use" | "tool_result" | "text" | "summary" refs: set[str] = field(default_factory=set) # identifiers this span defines uses: set[str] = field(default_factory=set) # identifiers this span consumes pair_id: str | None = None @dataclass class PrunePlan: drop: set[int] summarize: set[int] def validate_prune_plan(spans: list[Span], plan: PrunePlan) -> set[int]: """ Returns the set of indices that are actually safe to drop. Raises ContextRewriteViolation if the plan severs a live call/result pair or drops the sole retained source of an identifier still in use. """ by_index = {s.index: s for s in spans} retained = [s for s in spans if s.index not in plan.drop and s.index not in plan.summarize] # 1. Call/result atomicity: a pair may be dropped only as a whole. pair_members: dict[str, set[int]] = {} for s in spans: if s.pair_id is not None: pair_members.setdefault(s.pair_id, set()).add(s.index) for pid, members in pair_members.items(): dropped = members & plan.drop if dropped and dropped != members: raise ContextRewriteViolation( f"plan severs tool pair {pid!r}: drops {sorted(dropped)} " f"but retains {sorted(members - dropped)}" ) # 2. Referential closure: no retained span may use an identifier whose # only retained source lives inside a dropped/summarized span. removed = plan.drop | plan.summarize retained_sources: set[str] = set() for s in retained: retained_sources |= s.refs for s in retained: orphaned = {u for u in s.uses if u not in retained_sources} # An orphan is only fatal if its source was in fact removed. for u in s.uses: source_was_removed = any( u in by_index[i].refs for i in removed if i in by_index ) if source_was_removed and u not in retained_sources: raise ContextRewriteViolation( f"span {s.index} uses {u!r}, whose only source is being " f"removed; re-fetch required before rewrite" ) # 3. Continuation safety: a tool_use awaiting a result is never droppable. for s in spans: if s.kind == "tool_use" and s.pair_id is not None: has_result = any( t.kind == "tool_result" and t.pair_id == s.pair_id for t in spans ) if not has_result and s.index in plan.drop: raise ContextRewriteViolation( f"span {s.index} is an open tool_use with no result; " f"cannot drop a pending continuation" ) return set(plan.drop) def apply_plan(spans: list[Span], plan: PrunePlan) -> list[Span]: safe = validate_prune_plan(spans, plan) return [s for s in spans if s.index not in safe and s.index not in plan.summarize] ```