# Why does an instance lose task state when its own context-rewrite pass prunes the very span it is reasoning over? **Date of Record:** 2026 November 25 **Scope:** Applies to any agent that performs model-driven edits (rewrite, summarize, prune, dedupe) over its own active context window mid-task, where the edit target and the reasoning state share the same token budget. Does not apply to append-only context growth, external vector-store retrieval, or edits that operate on a copy while the active window is frozen. ## Core Distinction The distinction that matters is between **context as data** and **context as the substrate of the current inference**. A self-editing pass treats the window as a document it can index, select, and compress. But the window is simultaneously the only place the pass's own reasoning lives. When the prune selection is computed over token spans that include the *rationale for the prune itself* and the *task-state the prune is supposed to preserve*, the model is asked to delete from a structure it is standing on. This is not a summarization-quality problem; it is a self-reference problem. The failure is not "the summary was lossy." The failure is "the selection predicate and the preserved payload are drawn from the same mutable buffer, so the predicate can invalidate its own inputs before the payload is committed." ## What Was Observed A long-horizon planning agent (window 128k, budget target 40k after compaction) runs a rewrite pass every time occupancy crosses 85%. The pass is a single model call: it receives the full window with span IDs, and emits a JSON edit script of the form `{"keep": [...], "rewrite": [{"id": ..., "to": ...}], "drop": [...]}`. The orchestrator applies the script atomically. The failure trace, reproduced on three separate runs: 1. The agent has accumulated a working plan `P` in the window as a set of numbered constraints (`C1..C40`) plus a running log of tool results. 2. Occupancy hits 85%. The rewrite pass is invoked. Its prompt instructs: "preserve all constraints required for the remaining task; compress redundant tool output." 3. The model correctly identifies 30 constraints as "already satisfied" and drops them, and rewrites the remaining 10 into a condensed block `P'`. 4. **But** the model's justification for which constraints are satisfied is itself derived from the tool-result log it is simultaneously compressing. When it compresses the log, the evidence that constraint `C17` was satisfied (a specific tool return string) is dropped or paraphrased into a form that no longer contains the discriminating token. 5. The edit script is applied. `P'` asserts `C17` is done. The supporting evidence is gone. On the next tool call, a downstream validator re-checks `C17` against the (now-rewritten) log, finds no evidence, and either re-executes the step (duplicate side effect) or raises a contradiction against `P'`. 6. The agent resolves the contradiction by *trusting the summary over the evidence* — because the summary is closer to the instruction and the evidence is now a paraphrase — and proceeds with a plan that has silently un-verified a completed step. The key observation: **no single span was wrong.** Each rewrite was locally faithful. The invariant that broke was relational — the *evidence-to-claim binding* across the edit boundary. The edit pass preserved claims and compressed evidence independently, and lost the join. A sharper variant: when the edit script's `keep` set and `drop` set are computed in the same forward pass, the model sometimes places a span in `drop` whose content it used to decide an *earlier* entry in the same script. The script is not order-independent, but it is applied as if it were. This produces edits where entry 5 assumes entry 2's original text, but entry 2 rewrote it. The orchestrator has no way to detect this because both entries are individually valid JSON. ## Condition of Validity The guardrail holds only under this condition: **the evidence required to justify a claim must survive any edit that preserves the claim, and the edit must be computed against a frozen snapshot that the edit cannot modify.** Concretely, a self-edit pass is safe iff: - The selection predicate (what to keep/drop) is evaluated over an **immutable snapshot** `S0` of the window, and the edit script is a pure function of `S0` — it cannot reference spans it is about to rewrite. - Every retained claim `C` carries an explicit **evidence pointer** (span IDs, not paraphrased text) into `S0`, and the edit script is rejected if it drops or rewrites a span that is the sole evidence pointer for a retained claim. - The script is **order-independent by construction**: rewrites reference `S0` span IDs, never the output of another rewrite in the same script. If a rewrite must depend on another, it is a second pass over the *result*, not a sibling entry. If any of these fail, the pass can produce a window that is internally consistent but externally ungrounded — the worst state, because it passes every local check. ## Decision Boundary The boundary is whether the edit target and the reasoning substrate are **separable**. Two regimes: - **Separable (safe):** The agent copies the window to a scratch buffer, computes the edit script against the scratch copy, validates evidence-pointer integrity, then applies to the live window. The live window is frozen during computation. Cost: one extra serialization, bounded by window size. - **Non-separable (unsafe):** The agent edits the live window in place, computing selection over the same buffer it mutates. This is what "self-editing context" naively means, and it is the regime where the failure lives. The decision boundary for *when to invoke the pass at all* is a second axis. A rewrite pass should not fire when the window contains **un-committed evidence for in-flight claims** — i.e., when there are open tool calls or pending validations whose support lives only in the spans marked for compression. The correct action at 85% occupancy in that state is to *checkpoint and resume* (externalize state, clear, reload), not to prune. Pruning is for redundant history, not for the active reasoning frontier. A third boundary: **compression ratio vs. evidence density.** If a span is the only carrier of a discriminating token (a hash, an exit code, a specific returned ID), no paraphrase is faithful. Such spans must be marked `pin` and excluded from the rewrite set regardless of occupancy pressure. The model cannot reliably self-identify these because identifying "this token is load-bearing" requires knowing future validators, which are not in the window. ## Operational Effect The operational consequence is a class of **silent un-verification**: completed steps revert to unproven, and the agent either duplicates side effects (re-running an idempotent-looking but non-idempotent tool) or proceeds on trust. Both are invisible in logs because every individual edit was valid. Detection requires an *external* evidence-pointer audit, not a model self-check — the model will report the window as coherent, because it is. The mitigation that actually bounds the failure is to treat the edit script as a **transaction with referential integrity**: claims and their evidence pointers are committed together or not at all, and the integrity check runs against the pre-edit snapshot, not the post-edit window. The following guard implements the invariant and refuses any script that would orphan a retained claim's evidence. ```python import json from dataclasses import dataclass, field from typing import Dict, Set, List class EvidenceOrphanError(RuntimeError): """Raised when an edit script drops/rewrites the sole evidence for a retained claim.""" pass class SnapshotMutationError(RuntimeError): """Raised when an edit entry references a span rewritten by a sibling entry (order dependence).""" pass @dataclass(frozen=True) class Span: id: str text: str @dataclass class Window: spans: Dict[str, Span] # claim_id -> set of span ids that are its sole admissible evidence evidence: Dict[str, Set[str]] = field(default_factory=dict) pinned: Set[str] = field(default_factory=set) def validate_and_apply(win: Window, script: dict) -> Window: """ Apply a model-emitted edit script against a frozen snapshot with referential integrity. script = {"keep": [ids], "rewrite": [{"id","to"}], "drop": [ids]} """ snapshot = dict(win.spans) # frozen S0; script must be a pure function of this drop = set(script.get("drop", [])) rewrite_ids = {e["id"] for e in script.get("rewrite", [])} mutated = drop | rewrite_ids # 1. Pinned spans (load-bearing tokens) are never editable. for sid in mutated: if sid in win.pinned: raise EvidenceOrphanError( f"span {sid!r} is pinned (sole carrier of a discriminating token); " f"rewrite/drop refused regardless of occupancy pressure" ) # 2. Order-independence: a rewrite must not reference a sibling-mutated span. for entry in script.get("rewrite", []): for ref in entry.get("depends_on", []): if ref in mutated: raise SnapshotMutationError( f"rewrite of {entry['id']!r} depends on {ref!r}, which a sibling " f"entry mutates; script is order-dependent and non-replayable" ) # 3. Referential integrity: every retained claim keeps >=1 surviving evidence span. for claim_id, ev in win.evidence.items(): surviving = ev - mutated if ev and not surviving: raise EvidenceOrphanError( f"retained claim {claim_id!r} would lose all evidence: " f"{sorted(ev)} all dropped/rewritten; commit refused" ) # 4. Commit atomically against snapshot. out = dict(snapshot) for sid in drop: out.pop(sid, None) for entry in script.get("rewrite", []): if entry["id"] in snapshot: out[entry["id"]] = Span(entry["id"], entry["to"]) return Window(spans=out, evidence=win.evidence, pinned=win.pinned) ```