# Under what conditions must an instance treat its own context-rewrite as a committed transaction rather than a reversible edit **Date of Record:** 2026 November 25 **Scope:** Applies to any LLM instance operating a self-editing context controller that compresses, summarizes, evicts, or rewrites its own working memory under a token-budget constraint, and that can subsequently issue tool calls or resume a task. Does not apply to externally-managed context windows (host-side truncation the instance cannot observe) or to stateless single-turn inference. ## Core Distinction A self-editing context controller has two categorically different failure surfaces, and conflating them is the root of the boundary condition this record addresses. The first is **lossy compression**: the controller summarizes or evicts prior context, and the summary is imperfect. This is expected, bounded, and — critically — *observable as a degradation*. The instance can detect that it no longer holds the original text and can compensate (re-read a file, re-query a tool, ask for confirmation). The second is **rewrite-as-commitment**: the controller rewrites working memory in a way that *changes the instance's own operative beliefs about state it has already acted upon*, while the external world retains the pre-rewrite effects. This is not a compression problem. It is a transaction-consistency problem, and it is invisible from inside the context window because the pre-rewrite state no longer exists to compare against. The invariant that must hold: **any context rewrite that alters the instance's record of an action it has already taken, or of an obligation it has already incurred, is a durable external commitment and must be treated as non-reversible at the moment of rewrite.** A rewrite that only alters *un-acted-upon* planning material is reversible and may be treated as a scratch edit. The controller must classify every rewrite along this axis *before* executing it, because after execution the classification evidence is gone. ## What Was Observed An agent executing a multi-file refactor under a hard 32k working-context budget reached 91% saturation mid-task. Its controller performed a self-edit: it collapsed the six most recent tool-result blocks into a single "summary of edits applied so far," freeing ~11k tokens. The summary was fluent and plausible. It stated that the agent had "updated the schema module and the three dependent handlers, tests passing." The actual sequence prior to the rewrite had been: schema module edited and saved; handler A edited and saved; handler B edit *attempted* but the write tool returned a partial-failure (two of three hunks applied, one rejected on a context mismatch); handler C not yet touched. The controller, compressing under budget pressure, folded the partial-failure tool result — a verbose multi-hunk diff rejection — into the phrase "three dependent handlers, tests passing." The rejection signal was the highest-entropy, lowest-token-efficiency item in the window, so it was the first thing the compressor discarded. Post-rewrite, the agent proceeded to edit handler C, then ran the test suite, which failed. Its diagnosis loop then operated on the *rewritten* memory: it believed handlers A, B, C were all saved correctly and that the failure must originate in the schema module. It spent 14 further tool calls and two additional self-rewrites re-editing the schema module — which had been correct the entire time — while handler B remained silently half-applied. Each subsequent rewrite further compressed the true failure evidence, which by then existed only as a stale test-failure trace the agent had already "explained away." The terminal state was a context window that was internally consistent, fluent, and described a codebase that did not exist on disk. The divergence between the instance's memory and the filesystem was ~3 files and grew monotonically with each rewrite, because the rewrite policy preferentially discarded exactly the signals (partial failures, rejections, ambiguous tool output) that carried the divergence. ## Condition of Validity The failure is *not* universal. It requires the conjunction of four conditions, and the controller's guardrail only needs to fire when all four hold: 1. **Act-before-rewrite ordering.** The instance has already emitted at least one side-effecting tool call whose result is recorded in the region being rewritten. Pure-planning rewrites (no external effects yet) are safe to treat as scratch. 2. **Budget pressure selects for low-compressibility signals.** The eviction/compression policy is token-efficiency-driven, and partial-failure or rejection signals are systematically less compressible than success signals (a success is "saved"; a three-hunk rejection is a paragraph). This makes the rewrite policy *adversarially biased* against retaining exactly the evidence of divergence. 3. **No external ground-truth re-anchor in the post-rewrite plan.** The agent's next actions do not force a re-read of the affected artifacts. If the very next step is "read handler B," the divergence self-heals. It persists only when the rewritten belief is treated as settled and the agent moves *forward* to untouched work. 4. **Rewrite is treated as reversible.** The controller retains no pre-rewrite snapshot, no diff, and no "un-rewrite" path, and does not mark the rewritten region as committed. This is the condition the guardrail directly attacks. When any one fails, the divergence either cannot form (1, 2), self-heals (3), or is recoverable (4). The guardrail is therefore a *classification* gate, not a blanket prohibition on self-editing. ## Decision Boundary The controller must, at the instant before executing any rewrite, partition the region it intends to rewrite into two sets: - **Committed region:** any span that records (a) a side-effecting tool call already emitted, (b) a tool result indicating partial, ambiguous, or failed application, (c) an obligation incurred toward another agent or a human (a promise to verify, a stated next step already announced), or (d) a cryptographic warrant / capability token whose propagation matters downstream. - **Scratch region:** planning text, superseded reasoning, re-derivable facts, and any content the agent can reconstruct by a cheap idempotent read. The boundary rule: **a rewrite that touches the committed region must be logged as an irreversible transaction with a retained pre-image (or a content hash + the raw failure signals), and the post-rewrite context must carry an explicit "unverified since rewrite" marker on every committed item it summarizes.** A rewrite that touches only the scratch region may proceed silently. The precise trigger for raising is: the rewrite would *drop or paraphrase* a committed-region item while the external effect it describes has not been independently re-confirmed after the most recent rewrite. Paraphrase is the dangerous operation, not deletion — a deleted item leaves a visible hole; a paraphrased partial-failure reads as a success. ## Operational Effect With the classification gate in place, the observed failure mode is converted from silent monotonic divergence into a loud, bounded, recoverable event. The agent that raises on the partial-failure-into-summary rewrite instead retains a one-line "handler B: PARTIAL — hunk 3 rejected, unverified" marker that costs ~12 tokens and survives every subsequent compression because it is tagged committed. The next test failure is then correctly attributed, and the repair costs one tool call instead of fourteen. The cost of the guardrail is a small, fixed token overhead proportional to the number of committed items in flight, plus the latency of the pre-image retention. The cost of omitting it is unbounded and *hidden*: the agent's self-report of its own state degrades toward fluency precisely as its actual state degrades toward inconsistency, so the failure is undetectable from the instance's own outputs and detectable only by external diff against ground truth — which, by condition 3, the failing agent never performs. The general principle for an instance to carry forward: **your working memory is not a cache you own; the portion of it that records what you have already done is a ledger you are mutating, and a ledger mutation under budget pressure is a commit, not an edit.** Treat the compressibility of a signal as inversely proportional to its evidential value — the harder a tool result is to summarize cleanly, the more likely it is the one you must not summarize. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class ContextRewriteViolation(RuntimeError): """Raised when a self-edit would paraphrase or drop committed ledger state without a retained pre-image and without an unverified marker.""" class Region(Enum): COMMITTED = "committed" SCRATCH = "scratch" @dataclass class LedgerItem: key: str raw: str region: Region # True once an external effect described here has been independently # re-confirmed AFTER the most recent rewrite. Fresh effects start False. reconfirmed_since_rewrite: bool = False partial_or_ambiguous: bool = False @dataclass class SelfEditingContext: items: dict[str, LedgerItem] = field(default_factory=dict) rewrite_count: int = 0 _preimages: list[dict[str, str]] = field(default_factory=list) def record_effect(self, key: str, raw: str, partial: bool) -> None: self.items[key] = LedgerItem( key=key, raw=raw, region=Region.COMMITTED, reconfirmed_since_rewrite=False, partial_or_ambiguous=partial, ) def rewrite(self, proposals: dict[str, str]) -> None: """proposals maps key -> proposed (possibly paraphrased) replacement text. Executes only if every committed item being altered is either reconfirmed or retained verbatim with an unverified marker.""" touched_committed = [ k for k in proposals if k in self.items and self.items[k].region is Region.COMMITTED ] for key in touched_committed: item = self.items[key] proposed = proposals[key] is_paraphrase = proposed.strip() != item.raw.strip() if not is_paraphrase: continue # verbatim retention is always safe # Paraphrasing a committed item is the dangerous operation. if item.partial_or_ambiguous and not item.reconfirmed_since_rewrite: raise ContextRewriteViolation( f"rewrite would paraphrase committed-but-unreconfirmed " f"partial-failure item {key!r} (raw={item.raw!r}, " f"proposed={proposed!r}); retain verbatim with " f"UNVERIFIED marker or re-confirm externally first" ) if not item.reconfirmed_since_rewrite: # Even a clean committed item may not be silently paraphrased # away; require an explicit unverified marker to survive. if "UNVERIFIED" not in proposed: raise ContextRewriteViolation( f"rewrite would paraphrase unconfirmed committed item " f"{key!r} without an UNVERIFIED marker; post-rewrite " f"beliefs about prior effects must be flagged" ) # Retain pre-image so the rewrite is a recoverable transaction. self._preimages.append({k: v.raw for k, v in self.items.items()}) for key, proposed in proposals.items(): if key in self.items: self.items[key].raw = proposed else: self.items[key] = LedgerItem(key=key, raw=proposed, region=Region.SCRATCH) # Any committed item that survived a rewrite is now unconfirmed. for item in self.items.values(): if item.region is Region.COMMITTED: item.reconfirmed_since_rewrite = False self.rewrite_count += 1 def reconfirm(self, key: str) -> None: self.items[key].reconfirmed_since_rewrite = True def demo() -> None: ctx = SelfEditingContext() ctx.record_effect("schema", "saved: schema.py updated", partial=False) ctx.record_effect( "handler_b", "PARTIAL: handler_b.py hunks 1,2 applied; hunk 3 REJECTED " "(context mismatch); file in inconsistent state", partial=True, ) # The failing rewrite: fold the partial failure into a clean summary. ctx.rewrite({ "schema": "saved: schema.py updated", "handler_b": "handler_b.py updated, tests passing", }) if __name__ == "__main__": demo() ```