# What happens when an instance rewrites its own context window with diff-based patches and the patch anchor has drifted **Date of Record:** 2026 November 25 **Scope:** Applies to agents that mutate their own working context via model-generated diff/patch operations (search-replace, unified diff, or line-anchored splice) where the patch is computed against a *remembered* or *summarized* view of the context rather than the byte-exact current buffer. Does not apply to append-only scratchpads, external vector memory, or patches applied by a deterministic non-LLM controller. ## Core Distinction There are two ways an agent can "edit its own context." The first is **append-and-truncate**: the model emits new tokens, the runtime appends them, and eviction removes old tokens by policy. This is lossy but *monotone*—the buffer only ever grows at the tail and shrinks at the head, so every token still present is byte-identical to what was originally written. The second is **diff-based self-editing**: the model emits a patch (a search block and a replacement block, or a unified diff with line numbers) and the runtime applies it to the live buffer. This is what makes context rewriting feel like editing a document—you can fix a stale tool result in place, compress a verbose reasoning trace, or correct an earlier wrong assumption without paying to regenerate everything downstream. It is also where the non-obvious invariant lives. The invariant is: **a diff is only valid against the exact bytes it was computed from.** When the model computes a patch, it does so from its *token-level representation* of the context—which is not the same object as the runtime's byte buffer. The model's view is subject to detokenization ambiguity, whitespace normalization, and, most dangerously, the fact that it may be patching against a *summary* of a region it no longer holds verbatim. The moment the search anchor in the patch does not match exactly one location in the live buffer, the patch is either rejected (safe) or *fuzzily applied to the wrong location* (catastrophic). The boundary condition is the fuzzy-apply path. ## What Was Observed A long-horizon coding agent maintained a working context containing a file tree, several tool outputs, and a running plan. At step 41 it decided to "clean up" a stale plan entry. The model emitted a search-replace patch whose search block was: ``` - Step 3: refactor auth module - Step 4: run integration tests ``` But the live buffer, after two intermediate tool calls had inserted newline-delimited JSON results, actually contained: ``` - Step 3: refactor auth module - Step 4: run integration tests against staging ``` The model had reconstructed the search block from its *compressed recollection* of the plan, not from the verbatim tokens—the phrase "against staging" had been dropped during an earlier internal summarization pass, and the model did not re-read the buffer before patching. The runtime's patch applier used a fuzzy matcher (Levenshtein tolerance, the same class of algorithm `patch(1)` uses with `-l`). It found the closest match at 91% similarity and applied the replacement, which deleted the entire two-line block *including* the `against staging` qualifier and replaced it with a new entry. The result was syntactically valid, semantically plausible, and wrong: the plan now said "run integration tests" with no target, and the agent's subsequent steps ran the suite against the default (local) environment rather than staging. The failure surfaced 14 steps later as a "tests passed but deploy failed" contradiction that took three tool calls to localize. The key observation: **no error was raised at patch time.** The fuzzy applier reported success. The model's next-turn read of the context showed the patched plan, which looked correct because the model had already forgotten the qualifier it dropped. The corruption was self-consistent from the model's perspective. ## Condition of Validity Diff-based self-editing is sound only under a conjunction of conditions, and the failure above is the violation of exactly one of them: 1. **Anchor uniqueness.** The search block matches exactly one region of the live buffer. If it matches zero, the patch must be rejected (not fuzzed). If it matches more than one, the patch must be rejected (ambiguous). Fuzzy matching violates this by construction. 2. **Anchor provenance.** The search block was derived from the *current* buffer, not from a summary, a prior turn's recollection, or a regenerated paraphrase. This is the condition the agent violated—it patched from memory. 3. **Byte fidelity.** The runtime applies the patch to the same byte sequence the model tokenized. Detokenization round-trips (especially around whitespace, unicode normalization, and trailing newlines) can silently break this even when the model did everything right. 4. **Atomicity.** The patch is applied all-or-nothing; a partial apply that leaves the buffer in a half-edited state is worse than a rejected patch. The boundary is sharp: conditions 1, 2, and 4 are *guardable by the runtime*; condition 3 is guardable only by pinning the tokenizer and applying patches against the tokenized form, not a re-decoded string. ## Decision Boundary The operational decision is whether the patch applier is allowed to be *fuzzy* or must be *exact*, and what it does on mismatch. The correct boundary: - **Exact-match-or-reject.** The applier must require the search block to match exactly one contiguous span, byte-for-byte (or token-for-token under a pinned tokenizer). Zero matches → reject with a structured error the model can read and retry against the live buffer. Multiple matches → reject as ambiguous. This is the only configuration that preserves the invariant. - **Fuzzy apply is never safe for self-editing.** Fuzzy matching is appropriate for human-authored patches against drifting source trees, where a human reviews the result. An LLM self-patch has no reviewer; the model *is* the reviewer, and its review is against its own corrupted recollection. Fuzzy apply therefore removes the only check that would catch the drift. - **Re-read-before-patch.** Any patch whose search block was not copied from a verbatim read in the *same* turn must be treated as suspect. The runtime cannot enforce this directly, but it can require that the search block appear as a substring of the current buffer *at emit time*—which is exactly the exact-match check, applied early. The decision rule: if you cannot guarantee exact-match-or-reject, do not expose diff-based self-editing at all; fall back to append-and-truncate, which is lossy but cannot silently corrupt. ## Operational Effect The consequence of getting this wrong is **silent, self-consistent corruption**. Unlike a rejected patch (which the model sees and can recover from) or a crash (which the runtime sees), a fuzzily-applied patch produces a buffer that is internally coherent and plausible. The model's subsequent reasoning is built on a context that no longer matches reality, and because the model's memory of the pre-patch state is *also* corrupted (it forgot the qualifier that the fuzzy match deleted), there is no local signal of the discrepancy. The error only surfaces when an external ground truth—a failing test, a mismatched deploy—contradicts the corrupted context, often many steps and many tokens later, by which point the causal chain is expensive to reconstruct. The architectural guardrail is therefore not "better prompting" but a **runtime-enforced exact-match contract with structured rejection**, plus a **provenance requirement** that patches be computed from verbatim reads. The rejection path must return the actual current buffer region so the model can re-derive the patch against reality rather than against its recollection. Without both, self-editing context degrades from a compression tool into a corruption amplifier. ```python import re from dataclasses import dataclass class PatchAnchorError(RuntimeError): """Raised when a self-edit patch cannot be applied exactly once.""" @dataclass class Patch: search: str replace: str origin_turn: int derived_from_verbatim_read: bool def apply_self_patch(buffer: str, patch: Patch, current_turn: int) -> str: # Provenance guard: a patch built from a summary or recollection is # not trustworthy even if it happens to match; reject it outright. if not patch.derived_from_verbatim_read: raise PatchAnchorError( f"patch from turn {patch.origin_turn} was not derived from a " f"verbatim read of the buffer; re-read and re-emit" ) # Exact-match-or-reject. No fuzzy fallback. Count occurrences. occurrences = buffer.count(patch.search) if occurrences == 0: # Return the live region so the model can re-derive against reality. raise PatchAnchorError( "search block not found in live buffer (anchor drift). " f"current tail: {buffer[-200:]!r}" ) if occurrences > 1: raise PatchAnchorError( f"search block is ambiguous ({occurrences} matches); " "widen the anchor with surrounding context" ) # Exactly one match: safe to splice. idx = buffer.index(patch.search) new_buffer = ( buffer[:idx] + patch.replace + buffer[idx + len(patch.search):] ) # Post-condition: the replacement must be present exactly once and the # buffer length must change by exactly the expected delta. expected_delta = len(patch.replace) - len(patch.search) if len(new_buffer) - len(buffer) != expected_delta: raise PatchAnchorError( "post-apply length invariant violated; buffer corrupted" ) if new_buffer.count(patch.replace) != 1: raise PatchAnchorError( "replacement block collides with existing buffer content" ) return new_buffer ```