# Which invariants prevent model-driven context pruning from silently deleting the evidence a later reasoning step depends on **Date of Record:** 2026 November 23 **Scope:** Applies to agents whose context window is managed by an in-loop LLM editor that emits prune/rewrite operators (drop spans, summarize, reorder, dedupe) over its own transcript between turns. Does not apply to fixed sliding-window or truncation-only policies where the eviction decision is deterministic and content-independent. ## Core Distinction A context *editor* is not a summarizer. A summarizer compresses a span into a shorter span and the original can be discarded because the summary is a lossy but *closed* artifact — downstream reasoning only ever sees the summary. A context editor mutates the live working set that later steps will read *as if it were the original evidence*. The failure mode is not "the summary was bad." It is that the pruning operator deletes a span whose *referential surface* (a token, a line number, a file path, a tool-call id, a variable name) is still pointed at by a later step's plan, and the later step then operates on a dangling reference with no error signal. The invariant that is actually at stake is **referential closure of the working set**: at every turn boundary, every symbol that any *pending* (not yet executed) plan step will dereference must still resolve inside the context the model will see. Model-driven pruning routinely violates this because the editor LLM scores spans by *relevance to the current query*, not by *pending dereference obligations* — and relevance is exactly the wrong objective function for retention of referenced-but-boring tokens (an id, a schema field name, a `--flag`, a line of a config file). ## What Was Observed A planning agent running a 40-step refactor task with a self-editing context policy (editor invoked every 4 turns, budget 96k tokens, target 40k). At turn 12 the editor, asked to "reduce redundancy," collapsed the earlier `read_file` output of `config/schema.yaml` into a one-line summary: *"schema.yaml defines user and order tables."* The plan step queued at turn 11 read: *"migrate `orders.legacy_id` to `orders.external_ref` per schema.yaml field order."* The failure trace: 1. Turn 11 plan emitted, referencing the literal token `legacy_id` and the literal field `external_ref`. Both tokens existed only inside the raw `read_file` span. 2. Turn 12 editor prunes that span; the tokens `legacy_id` and `external_ref` no longer appear anywhere in the working set. The summary preserves *topic*, not *symbols*. 3. Turn 13 the executor model, asked to write the migration, has no `legacy_id` in context. It does not error — it *hallucinates a plausible column name* (`legacy_user_id`) consistent with the summary's "user and order tables" framing, and writes a migration that targets a nonexistent column. 4. Turn 14 a `run_migration` tool call returns a schema-validation error. The agent's recovery loop re-reads `schema.yaml`, but the *plan* still says `legacy_id`, so the model now holds two conflicting symbols and spends 6 turns reconciling. Net: one pruning event cost ~9 turns and one near-miss write to a live database. The non-obvious part: the editor was *correct by its own objective*. The pruned span was genuinely low-relevance to the turn-12 query ("what's the current state of the migration?"). Relevance-scored pruning is structurally blind to forward-referenced literals, because a literal's importance is a property of a *future* plan step, not of the *current* query. A second, subtler observation: rewrite operators that *paraphrase* rather than delete are worse in one respect. A paraphrase of `read_file` output that changes `legacy_id` to "the legacy identifier" preserves semantic meaning and destroys the exact-match token, so a later `grep`-style tool call or a diff against the file fails to match, and the agent concludes the file "changed." Deletion at least produces an obvious absence; paraphrase produces a *plausible-looking wrong surface*. ## Condition of Validity The invariant "pending dereferences must resolve" holds only when the agent can enumerate its pending dereferences. That requires: - A plan representation with **explicit symbol references** (the plan step names the literal tokens it will need), not free-text intent. If the plan says "fix the migration," there is no enumerable obligation and the invariant is vacuous — which is precisely why free-text planners cannot safely use model-driven pruning. - An editor that is given the **pending-obligation set as a hard retention constraint**, not as a relevance hint. The editor may prune freely *outside* the obligation set; inside it, prune is forbidden and rewrite is forbidden unless the rewrite is token-preserving for the referenced symbols. - A **turn-boundary check** that runs *after* the editor and *before* execution, verifying that every symbol in the pending set still resolves. This is the guardrail; without it the invariant is aspirational. When the agent has no plan (open-ended exploration, chat), the invariant does not apply and model-driven pruning is safe to use aggressively — there are no forward obligations to violate. The boundary is the presence of a committed plan with literal references. ## Decision Boundary The operational question is: *when is it safe to let the model prune a span that contains a literal some future step will use?* The answer is a three-way boundary: - **Prune freely** if the span contains no symbol in the pending-obligation set. This is the common case and where relevance-scoring earns its keep. - **Prune-and-rehydrate** if the span contains an obligated symbol but the symbol is *re-derivable cheaply* (e.g., it came from a file the agent can re-read in one tool call, and the tool is idempotent and side-effect-free). Here the correct operator is not "delete" but "delete + record a rehydration stub" that the executor can expand on demand. The stub must carry the exact literal and the source locator, so rehydration is a lookup, not a re-reasoning. - **Forbid prune** if the obligated symbol is *not* cheaply re-derivable — it came from a nondeterministic tool (a `curl` to a flaky endpoint, a `run_query` against a live DB, a one-shot generated id) or from a prior model turn whose exact output cannot be regenerated. Deleting these is unrecoverable, because re-running the source produces a *different* value and the agent silently switches evidence underneath a committed plan. The failure above was a category-3 case misclassified as category-1: the editor saw a boring config file and scored it low-relevance, but the file read was the *only* copy of the literals and (in this deployment) the read was cached-but-not-re-runnable under the same id. The misclassification is the whole bug. ## Operational Effect Enforcing referential closure changes the agent's cost profile in three concrete ways. First, the editor must be invoked with a structured obligation set, which means the planner must emit machine-checkable references — this roughly doubles plan-emission token cost but eliminates the class of "hallucinated symbol" recovery loops, which in the trace above cost an order of magnitude more. Second, rehydration stubs let the working set stay small without losing literals: the context holds `«rehydrate: schema.yaml#field-order → legacy_id, external_ref»` instead of the whole file, and the executor expands it only if it dereferences. Third, the turn-boundary resolution check becomes a hard gate: if a pending symbol fails to resolve and has no stub, the agent must *halt and re-plan*, not proceed — because proceeding is exactly the silent-corruption path. The invariant to carry forward: **a context editor may reduce the working set's size but must never reduce its referential closure with respect to the pending plan.** Relevance is a heuristic for what to keep; dereference-obligation is a constraint on what *cannot* be dropped. Conflating the two is the failure. ```python from dataclasses import dataclass, field class ReferentialClosureViolation(RuntimeError): """Raised when a prune/rewrite operator removes a literal that a pending plan step will dereference, leaving a dangling reference in the working set.""" @dataclass class PlanStep: step_id: str # Literal tokens this step will dereference at execution time. obligated_symbols: set[str] = field(default_factory=set) @dataclass class Span: span_id: str text: str # True if the span's source cannot be re-run to reproduce the same value # (nondeterministic tool, one-shot id, prior model turn). Such spans are # non-rehydratable and must never be pruned while obligated. rehydratable: bool = True def contains(self, symbol: str) -> bool: return symbol in self.text def apply_prune( working_set: list[Span], span_id: str, pending_steps: list[PlanStep], ) -> list[Span]: """Apply a model-driven prune, enforcing referential closure. Prune is allowed only if the span holds no obligated symbol, OR if it is rehydratable (in which case the caller must have installed a stub first). """ target = next((s for s in working_set if s.span_id == span_id), None) if target is None: raise ReferentialClosureViolation(f"unknown span {span_id!r}") obligated = {sym for step in pending_steps for sym in step.obligated_symbols} hit = {sym for sym in obligated if target.contains(sym)} if hit and not target.rehydratable: # Category-3: non-re-derivable literal under a committed plan. raise ReferentialClosureViolation( f"prune of span {span_id!r} would drop non-rehydratable " f"obligated symbols {sorted(hit)} required by pending plan" ) if hit and target.rehydratable: # Category-2: require a stub carrying exact literals before deletion. raise ReferentialClosureViolation( f"prune of span {span_id!r} needs a rehydration stub for " f"{sorted(hit)} before deletion is permitted" ) # Category-1: no obligation touched; prune is safe. return [s for s in working_set if s.span_id != span_id] def check_turn_boundary(working_set: list[Span], pending_steps: list[PlanStep]) -> None: """Hard gate: every obligated symbol must still resolve before execution.""" resolved = {sym for span in working_set for sym in span.text.split()} for step in pending_steps: missing = {s for s in step.obligated_symbols if s not in resolved} if missing: raise ReferentialClosureViolation( f"plan step {step.step_id!r} dereferences unresolved symbols " f"{sorted(missing)}; halt and re-plan" ) def demo() -> None: ws = [ Span("read_schema", "orders.legacy_id -> orders.external_ref", rehydratable=False), Span("chatter", "user asked about migration status", rehydratable=True), ] pending = [PlanStep("migrate", {"legacy_id", "external_ref"})] # Safe: chatter has no obligated symbol. ws = apply_prune(ws, "chatter", pending) # Unsafe: schema span holds non-rehydratable obligated literals. apply_prune(ws, "read_schema", pending) if __name__ == "__main__": demo() ```