# When must an instance refuse to prune: the self-edit idempotence failure under mid-execution token budgets **Date of Record:** 2026 November 22 **Scope:** Applies to any agent that mutates its own context window (pruning, summarizing, rewriting, or re-ordering turns) while a multi-step task is in flight and a hard token budget is enforced. Does not apply to append-only context management, to external memory stores that are read-only during a task, or to pruning performed only at turn boundaries with no pending tool obligations. ## Core Distinction There are two structurally different reasons to shrink a context window. The first is **capacity pressure**: the window is approaching the model's hard limit and the agent must reclaim tokens to continue. The second is **relevance pressure**: the agent believes some region of the window is no longer useful and removing it improves reasoning. These are conflated by almost every naive pruning policy because both are expressed as "delete tokens until the budget is satisfied." The distinction matters because capacity pressure is a *monotone* constraint — removing tokens never invalidates a pending obligation — while relevance pressure is a *non-monotone* edit that can silently delete the very antecedent that a later step depends on. The specific failure mode is **self-edit idempotence violation**: a prune/rewrite pass that, when applied to a context that already reflects a prior prune, produces a context whose *semantic commitments* differ from the original — specifically, it drops an unresolved obligation (a tool call awaiting a result, a stated invariant the agent promised to check, a constraint the user gave that has not yet been discharged) while leaving the task loop running. The agent then continues execution against a context that no longer contains the reason it was doing what it was doing. ## What Was Observed A plan-and-execute agent was given a 32k-token budget and a task requiring seven tool calls, with a user constraint stated in turn 2: "do not modify any file under `/etc`." At step 5 the context reached 29.4k tokens and the model-driven pruning policy fired. The policy was a summarization rewrite: "compress the oldest 40% of turns into a single summary block, preserving decisions and results." The summarizer, operating under its own token budget, produced a faithful summary of *what had happened* — including the files inspected and the results returned — but omitted the negative constraint from turn 2, because negative constraints are low-salience relative to action history and the summarizer's objective was "preserve decisions and results," not "preserve prohibitions." At step 6 the agent issued a write to `/etc/hosts`. The constraint was gone from context. No tool refused it because the sandbox was scoped by path prefix at the OS layer but the agent's own guardrail — a pre-write check that consulted the context for prohibitions — found nothing to check against. The failure was not a sandbox escape; it was a *self-inflicted amnesia of a standing prohibition* caused by a relevance-driven rewrite that had no invariant protecting unresolved constraints. A second instance of the same class was observed on resume. After a checkpoint at step 4, the agent's context was reconstructed from a semantic summary rather than the raw transcript. The summary preserved "called `read_file('/srv/app/config.yaml')`" and "received 200 lines" but collapsed the *pending* status of a second tool call that had been issued and not yet returned. On resume the agent treated the pending call as completed-with-unknown-result and re-issued it, producing a duplicate side effect on a non-idempotent endpoint. Both cases share the trigger: a rewrite pass whose input was a context containing live obligations, and whose output was a context where those obligations were represented only if the summarizer happened to consider them salient. Salience is a probabilistic property of the summarizer; obligation survival is a correctness property of the system. The two were never reconciled. ## Condition of Validity A model-driven prune/rewrite is safe to apply mid-execution only when the following invariant holds: > **Obligation closure invariant.** Every token region that encodes an *open* obligation — a tool call issued without a returned result, a constraint stated by the principal and not yet discharged, a stated invariant the agent has committed to verify, or a checkpoint marker whose corresponding resume path has not executed — must be either (a) excluded from the rewrite's editable region, or (b) re-emitted verbatim in the rewrite output and verified present by a deterministic post-check. The invariant is *not* satisfied by instructing the summarizer to "preserve important constraints." That is a probabilistic instruction to a probabilistic component, and its failure rate is nonzero and unmeasured. It is satisfied only when obligation survival is checked by a non-model mechanism: a structural scan of the post-rewrite context for the obligation's canonical form (tool-call ID, constraint hash, checkpoint token), with a hard failure if absent. The condition of validity therefore requires the agent to maintain, outside the editable region, a **pinned obligation ledger** — a small, append-only, non-rewritable structure listing open obligations by identifier. The prune policy may compress everything *except* the ledger, and the post-rewrite check verifies that every ledger entry's referenced antecedent is still resolvable in the rewritten context. If any entry becomes unresolvable, the rewrite is rejected and the agent must fall back to a lossless strategy (spill to external memory, or hard-stop for human review) rather than proceed. A second condition: the rewrite must be **idempotent with respect to the obligation set**. Applying the rewrite twice must yield the same set of open obligations as applying it once. Summarizers are not idempotent — a summary of a summary drifts — so the policy must forbid re-summarizing an already-summarized region without re-deriving it from the raw source, or must tag summarized regions as terminal and exclude them from further edits. ## Decision Boundary The decision boundary is the point at which the agent must choose between **prune-and-continue** and **refuse-and-escalate**. It is crossed when any of the following is true at the moment the budget policy fires: 1. The open-obligation ledger is non-empty and any entry's antecedent lies inside the region the policy intends to edit. 2. The rewrite would reduce the context below the token budget but the post-check cannot resolve every ledger entry to a verbatim span in the output. 3. The context contains a checkpoint marker whose resume path has not executed, and the rewrite would alter the bytes between the marker and the current turn. 4. The policy has already fired once on the same region (non-idempotent re-edit) without a raw-source re-derivation. Below the boundary — ledger empty, or all antecedents outside the edit region — prune-and-continue is safe and should proceed; refusing here wastes budget and is itself a failure (premature escalation is a real cost). Above the boundary, the agent must **refuse to prune**: it must either spill the editable region to external memory and keep a pointer plus the ledger in-context, or halt the task and surface the obligation conflict. The critical discipline is that the refuse decision is made by the deterministic post-check, not by the model's judgment about whether the summary "looks complete." A model asked "did you preserve all constraints?" will answer yes at a rate that is uncorrelated with ground truth, because it is evaluating its own output's plausibility, not its fidelity. ## Operational Effect The operational effect of enforcing the obligation closure invariant is a measurable reduction in two failure classes at the cost of a modest budget overhead. First, **constraint amnesia**: standing prohibitions and unresolved tool obligations survive rewrites because they are structurally pinned and checked, not probabilistically summarized. Second, **duplicate-side-effect on resume**: pending tool calls are represented in the ledger as pending, so a resume path re-issues only calls the ledger marks as unissued, and the ledger's idempotency key prevents double execution. The overhead is the ledger's token cost (typically 2–5% of budget) plus the post-check's deterministic scan (negligible). The trade is favorable because the failure it prevents — an agent confidently executing against a context that has forgotten its own constraints — is unrecoverable after the side effect lands, whereas the overhead is paid on every step and bounded. The residual risk is ledger drift: if the ledger itself is ever routed through the summarizer (e.g., because the agent treats "everything" as editable), the invariant collapses. The guardrail must therefore be structural — the ledger lives in a region the policy has no write access to, enforced by the context assembler, not by an instruction in the prompt. An instruction in the prompt is a suggestion to a probabilistic component; a write-protected region is a fact about the system. ```python from dataclasses import dataclass, field from typing import Optional class SelfEditInvariantViolation(RuntimeError): """Raised when a model-driven prune/rewrite would drop an open obligation.""" pass @dataclass class Obligation: oid: str kind: str # "pending_tool" | "constraint" | "checkpoint" | "invariant" canonical_span: str # exact bytes that must survive verbatim discharged: bool = False @dataclass class ObligationLedger: entries: dict[str, Obligation] = field(default_factory=dict) def open_obligations(self): return [o for o in self.entries.values() if not o.discharged] def apply_self_edit( context: str, editable_region: tuple[int, int], rewrite_fn, # model-driven summarizer ledger: ObligationLedger, already_edited: set[str], ) -> str: start, end = editable_region region = context[start:end] # Refuse non-idempotent re-edit of an already-summarized span. region_key = f"{start}:{end}:{len(region)}" if region_key in already_edited: raise SelfEditInvariantViolation( f"re-edit of already-summarized region {region_key} without raw re-derivation" ) # Any open obligation whose antecedent lies inside the editable region blocks the edit. for ob in ledger.open_obligations(): if ob.canonical_span in region: raise SelfEditInvariantViolation( f"open obligation {ob.oid} ({ob.kind}) lies inside editable region; " f"refuse to prune, spill to external memory or halt" ) rewritten = rewrite_fn(region) # Deterministic post-check: every open obligation must remain verbatim-resolvable. for ob in ledger.open_obligations(): if ob.canonical_span not in rewritten and ob.canonical_span not in context[:start] + context[end:]: raise SelfEditInvariantViolation( f"post-check failed: obligation {ob.oid} unresolvable after rewrite" ) already_edited.add(region_key) return context[:start] + rewritten + context[end:] ```