# Why does an instance lose task state when it prunes its own context mid-execution: the self-edit commit barrier and the orphaned-tool-call invariant **Date of Record:** 2026 November 26 **Scope:** Applies to any agent instance that mutates its own working memory (summarization, rewriting, re-ranking, eviction) under a token budget while a multi-step task is in flight. Does not apply to external, out-of-band context compaction performed between turns by a supervisor that holds the authoritative transcript. ## Core Distinction There are two structurally different ways an agent reduces its context: *observation-time compaction* (the harness truncates tool output before it enters the window) and *self-editing* (the model, as an act of reasoning, calls a mutation primitive—`prune`, `rewrite`, `rerank`, `summarize_span`—that alters messages already resident in the window). The first is safe because it never touches committed history. The second is where the failure lives, and the failure is not "the model forgets things." It is that self-editing is a **mutation of the substrate the model is currently reasoning over**, and the model has no transactional view of that substrate. When it prunes or rewrites, it is editing the very tokens that define the task's open obligations, and it cannot observe the edit's effect until the next turn—by which point the edit is already committed and the obligations may be gone. The non-obvious invariant: **a self-edit is only safe if it preserves the closure of open tool-call obligations and the anchors those obligations depend on.** Most implementations enforce a token budget, not a closure invariant. The budget is satisfied; the task is not. ## What Was Observed A research agent on a 40-step task (fetch → parse → cross-reference → write) hit 82% of its context budget at step 19. It invoked a self-summarization primitive over the span `messages[2:14]`—the early fetch/parse turns—with the instruction "condense to key findings." The summarizer, optimizing for information density, collapsed twelve messages into three. Two of the collapsed messages were: - `assistant: tool_call(id=call_7f2a, name=read_file, args={path: "spec.md"})` - `tool: result(id=call_7f2a, content: "")` The summary retained the *finding* ("spec requires schema v3 with a nullable `region` field") but dropped the `tool_call`/`tool_result` pairing, because a summary of findings is not a transcript of calls. At step 23 the model attempted to re-read `spec.md` to check an edge case, but its re-rank step had also demoted the original fetch turn. It then reasoned: "I have already read spec.md (per summary), so I will proceed without re-reading." It proceeded on a *paraphrase* of the spec, not the spec. The final artifact omitted the nullable-`region` handling. The summary was accurate; the task still failed, because the summary replaced the ground truth the model was entitled to re-inspect. A second, sharper trace: an agent pruned a span containing the *only* `tool_call` whose `tool_result` was still pending (the call had been issued, the result had not yet arrived). The prune removed the call; the result arrived on the next turn as an orphaned `tool` message with no matching `tool_call`. The harness rejected the turn as malformed (tool result without preceding call), the model saw a protocol error, and—critically—retried the *prune* rather than the *call*, because its own reasoning trace now said "the previous action failed." It looped three times before the budget forced a hard stop. The orphaned result was the only copy of the data it needed. ## Condition of Validity The commit barrier must hold: **no self-edit may commit while the edited span is the target of an unresolved obligation.** Formalize the window as a sequence of messages, each tagged with `(kind, call_id?, depends_on?)`. Define the *open set* at turn *t* as the set of `call_id`s for which a `tool_call` exists but no matching `tool_result` exists, plus the set of `call_id`s referenced by the model's current plan (the "anchors" it intends to re-inspect). A self-edit over span *S* is **valid** iff: 1. **Closure preservation:** for every `call_id` in the open set, either its `tool_call` and (if present) `tool_result` are both outside *S*, or both are inside *S* and the edit preserves the pair as an atomic unit. Never split a pair. 2. **Anchor preservation:** no message in *S* is an anchor for a step the model has not yet completed, unless the edit emits an explicit `reacquire` stub that forces a re-fetch before the dependent step runs. 3. **Reversibility:** the pre-edit span is retained in a non-resident store (a "cold ledger") addressable by `call_id`, so a later `reacquire(call_id)` can restore the exact bytes rather than a paraphrase. Condition 1 fails silently when the model summarizes "findings" instead of "transcript." Condition 2 fails silently when the model treats its own summary as ground truth. Condition 3 is what makes recovery possible at all; without it, a bad edit is unrecoverable within the episode. ## Decision Boundary The boundary is not "prune vs. don't prune"—every agent under budget must prune. The boundary is **what the prune is allowed to be a function of.** - **Safe:** prune/rerank operating over *closed* spans (all obligations resolved, no anchors downstream) with the cold ledger retained. The model may summarize freely here; the summary is a cache, and the cache miss path (`reacquire`) is intact. - **Unsafe:** prune operating over *open* spans, or over spans containing anchors for unexecuted steps, or any edit that discards the cold ledger. Here the model is editing the definition of its own task while the task is running, with no rollback. - **The trap:** the unsafe region is exactly where the budget pressure is highest. Long tool outputs (the 6k-token spec) are the biggest budget consumers and the most likely to be anchors. The incentive to prune them is maximal precisely when the invariant forbids it. A budget-only policy will always prune the spec; a closure-aware policy will *rewrite it losslessly* (keep the bytes, shrink the resident view) or *defer the dependent step* until the spec's obligations close. The decision rule: **budget pressure triggers a lossless compaction (dedupe, reference-by-id, cold-ledger spill) before it triggers a lossy self-edit.** Lossy self-edit is the last resort, permitted only over spans that pass the closure and anchor checks. ## Operational Effect Enforcing the commit barrier changes the failure surface from *silent task corruption* to *explicit budget exhaustion*, which is the correct failure. An agent that cannot prune an open span will either (a) spill it to the cold ledger and keep a stub, preserving the task, or (b) hit the hard budget and halt cleanly with a recoverable checkpoint. Both are better than a confident, well-summarized, wrong answer. The second effect is on retry semantics. With the barrier in place, an orphaned `tool_result` cannot arise from self-editing, so a protocol error on the next turn unambiguously means "the tool call itself failed," not "my edit ate the call." This removes the loop where the model retries its own destructive edit. The invariant does not make the model smarter; it makes the model's *errors legible* to itself, which is the only thing that lets a probabilistic reasoner recover. ```python from dataclasses import dataclass, field from typing import Optional class SelfEditViolation(RuntimeError): """Raised when a self-edit would break the closure/anchor/ledger invariant.""" pass @dataclass class Msg: kind: str # "tool_call" | "tool_result" | "assistant" | "user" call_id: Optional[str] = None content: str = "" is_anchor: bool = False # referenced by an unexecuted step @dataclass class ColdLedger: store: dict = field(default_factory=dict) def spill(self, call_id: str, payload: str) -> None: self.store[call_id] = payload def reacquire(self, call_id: str) -> str: if call_id not in self.store: raise SelfEditViolation(f"reacquire({call_id}) missed: ledger dropped") return self.store[call_id] def validate_self_edit(window: list[Msg], span: slice, ledger: ColdLedger) -> None: """Enforce the commit barrier before a lossy self-edit commits.""" edited = window[span] calls = {m.call_id for m in edited if m.kind == "tool_call"} results = {m.call_id for m in edited if m.kind == "tool_result"} # Invariant 1: never split a call/result pair across the edit boundary. for cid in calls ^ results: raise SelfEditViolation( f"span splits call/result pair for call_id={cid}; " f"edit would orphan half the obligation" ) # Invariant 2: no anchor for an unexecuted step may be lossily edited. for m in edited: if m.is_anchor: raise SelfEditViolation( f"span contains anchor for unexecuted step (call_id={m.call_id}); " f"rewrite losslessly or defer dependent step" ) # Invariant 3: cold ledger must retain every edited call's payload. for cid in calls: if cid not in ledger.store: raise SelfEditViolation( f"lossy edit of call_id={cid} without cold-ledger spill; " f"edit is unrecoverable within episode" ) def commit_prune(window: list[Msg], span: slice, ledger: ColdLedger, summary: str) -> list[Msg]: validate_self_edit(window, span, ledger) edited = window[span] for m in edited: if m.kind == "tool_call": ledger.spill(m.call_id, m.content) stub = Msg(kind="assistant", content=f"[pruned span: {summary}]") return window[:span.start] + [stub] + window[span.stop:] ```