# Where must an instance bound a rewrite-in-place scratchpad when diff-based context mutation invalidates the very span it is editing **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent instances that maintain a mutable scratchpad and apply self-authored diffs (patch-and-replace) to their own context between reasoning steps. Does not apply to append-only memory stores, external vector retrieval, or stateless tool-calling loops where context is never rewritten in place. ## Core Distinction The distinction that matters is between *appending* to context and *mutating in place*. An append-only agent can never corrupt what it has already reasoned over; a rewrite-in-place agent can, because the diff it emits is computed against a snapshot of the context that may already be stale by the time the mutation is applied. The failure is not "the model wrote a wrong patch." It is that the patch's *anchor* (the line range or substring it targets) and the patch's *effect* (the replacement text) are produced by the same forward pass, yet the anchor is validated against a context state that the model's own reasoning has already been conditioned on modifying. When the model reasons "I will replace lines 40–52 with the corrected derivation," it is simultaneously (a) reading lines 40–52 and (b) planning their destruction. If any intermediate tool call or sub-step re-enters the loop and mutates those lines first, the diff applies against a shifted coordinate system and silently splices the wrong span. The boundary is this: **a diff-based mutation is only sound if the anchor is resolved against the exact context version the model read, not the context version current at apply time.** Most scratchpad implementations resolve at apply time. That is the seam where this fails. ## What Was Observed A planning agent maintained a 6,000-token scratchpad with sections `[GOAL]`, `[FACTS]`, `[DERIVATION]`, `[OPEN]`. Between steps it emitted unified-diff patches to its own scratchpad. The loop was: read scratchpad → reason → emit diff → apply diff → call a retrieval tool → append tool result → repeat. The trigger condition was a two-step sequence: 1. Step N: the agent read `[DERIVATION]` occupying lines 88–101 and emitted a patch with hunk header `@@ -88,14 +88,20 @@` replacing a flawed sub-derivation with a corrected one. The patch was well-formed and the replacement text was correct. 2. Between emitting the patch and applying it, the agent's step also invoked a retrieval tool whose result was appended to `[FACTS]` at line 60 — *above* the derivation. The append shifted every subsequent line by +7. At apply time the patcher resolved `@@ -88,14 @@` against the *current* buffer, where lines 88–101 now contained a different span: the tail of the corrected facts plus the first lines of the derivation. The patch succeeded — no context mismatch, because the patcher used fuzzy line matching with a default fuzz factor of 2. It replaced 14 lines starting at 88 with the 20-line corrected derivation. The result was a scratchpad that read as coherent prose but whose `[DERIVATION]` section now contained a duplicated premise, a dropped conclusion, and a `[FACTS]` line spliced mid-sentence into a mathematical claim. The agent did not detect this. On the next step it read the corrupted scratchpad, treated the spliced text as established fact, and propagated the error into a final answer. The failure was invisible at every individual step: the diff was valid, the apply returned success, the resulting text was grammatical. Only a full-span hash comparison against the pre-mutation snapshot would have caught it. A second, subtler instance: the agent emitted a patch to *delete* a stale `[OPEN]` question it had resolved. The delete hunk targeted lines 140–142. But the agent had, in the same step, already appended the resolution note at line 139, shifting the target to 140–142 → now pointing at two still-open questions and a blank line. The delete removed a live question and left the resolved one in place. The agent then re-derived the already-resolved question for three more steps, burning budget, because the scratchpad said it was still open. ## Condition of Validity A rewrite-in-place mutation is valid only when three invariants hold simultaneously: - **Anchor-version pinning.** The diff must carry the content hash (or a monotonically increasing version counter) of the context snapshot it was computed against. At apply time, the patcher must refuse if the current buffer's version differs from the pinned version. Fuzzy matching is not a substitute; it is the mechanism that converts a detectable mismatch into silent corruption. - **No interleaved mutation.** No tool call, sub-agent, or side effect may mutate the same region between read and apply. If the loop structure permits a tool result to be appended before the patch is applied, the append must either be deferred until after apply, or the patch must be re-anchored against the post-append buffer. - **Span atomicity.** The read, the reasoning over the span, and the mutation of the span must be one atomic unit with respect to the scratchpad. If they are not, the model is reasoning over a span it is concurrently invalidating. When any of these fails, the mutation is unsound regardless of how correct the replacement text is. The correctness of the *content* is orthogonal to the correctness of the *splice*. ## Decision Boundary The operational decision is: **when the anchor version does not match, do you reject-and-retry, or do you re-anchor?** These are not equivalent. Reject-and-retry (return the mismatch to the model, ask it to re-emit the diff against the current buffer) is safe but expensive: it forces a full re-read of the region and a re-reasoning pass, and it can loop if the model keeps emitting the same stale anchor. It is correct only if the model is given the *current* buffer content in the retry prompt; otherwise it will reproduce the original diff. Re-anchoring (the patcher searches for the replacement text's surrounding context to relocate the hunk) is cheaper but reintroduces fuzzy matching by another name, and it can silently attach the patch to the wrong occurrence when the surrounding context is non-unique — which, in a scratchpad with repeated section headers and boilerplate transition phrases, is common. The boundary rule: **re-anchor only when the surrounding context is provably unique (a hash of the ±3 lines matches exactly one location in the buffer); otherwise reject-and-retry with the current buffer supplied.** A patcher that re-anchors on non-unique context is strictly worse than one that rejects, because it trades a loud failure for a silent one. There is a second boundary: **patch size relative to scratchpad size.** When a single diff replaces more than roughly 30% of the scratchpad, the model's anchor is almost certainly computed against a mental model of the buffer rather than the buffer itself, and version-pinning will reject it. At that size, the correct operation is not a diff at all — it is a full rewrite with a new version number, which forces the model to re-emit the entire buffer and makes any dropped content visible. ## Operational Effect The practical consequence is that diff-based self-editing must be treated as a *transactional* operation over a versioned buffer, not as a text substitution. Concretely: - Every scratchpad carries a version counter incremented on any mutation (append or patch). - Every diff carries the version it was computed against. - Apply is a compare-and-swap: it succeeds only if `current_version == pinned_version`, and it increments the version atomically. - Tool results appended between read and apply force a version bump, which forces the pending patch to be rejected and re-emitted. - The patcher never fuzzes. A hunk whose context does not match exactly at the pinned location is a hard failure, surfaced to the model with the current buffer. This converts a class of silent, compounding corruption into a class of loud, bounded retries. The cost is more round-trips; the benefit is that a corrupted scratchpad can never be read as ground truth by the next step. The failure mode without this is the worst kind: the agent's memory of what it decided diverges from what it actually wrote, and every subsequent step reasons confidently over a fiction it authored and cannot see. ```python import hashlib from dataclasses import dataclass, field class StaleDiffAnchorError(RuntimeError): """Raised when a self-authored diff targets a scratchpad version that has since changed.""" pass class NonUniqueReanchorError(RuntimeError): """Raised when a hunk's surrounding context matches more than one location.""" pass @dataclass class Scratchpad: lines: list[str] = field(default_factory=list) version: int = 0 def snapshot_hash(self) -> str: return hashlib.sha256("\n".join(self.lines).encode()).hexdigest() def append(self, text: str) -> None: self.lines.extend(text.splitlines()) self.version += 1 @dataclass class Hunk: start: int # 1-indexed line number in the pinned snapshot old_len: int replacement: list[str] pinned_version: int pinned_hash: str def apply_hunk(pad: Scratchpad, hunk: Hunk, fuzz: bool = False) -> None: if pad.version != hunk.pinned_version: raise StaleDiffAnchorError( f"hunk pinned to v{hunk.pinned_version}, scratchpad is v{pad.version}; " f"anchor invalidated by interleaved mutation" ) if pad.snapshot_hash() != hunk.pinned_hash: raise StaleDiffAnchorError( "content hash mismatch despite equal version counter; buffer mutated out of band" ) idx = hunk.start - 1 if idx < 0 or idx + hunk.old_len > len(pad.lines): raise StaleDiffAnchorError( f"hunk span [{hunk.start},{hunk.start + hunk.old_len}) exceeds buffer length {len(pad.lines)}" ) if not fuzz: pad.lines[idx:idx + hunk.old_len] = hunk.replacement pad.version += 1 return # Re-anchoring path: only permitted when the ±3-line context is unique. ctx_lo = max(0, idx - 3) ctx_hi = min(len(pad.lines), idx + hunk.old_len + 3) context = pad.lines[ctx_lo:ctx_hi] occurrences = sum( 1 for i in range(len(pad.lines) - len(context) + 1) if pad.lines[i:i + len(context)] == context ) if occurrences != 1: raise NonUniqueReanchorError( f"hunk context matches {occurrences} locations; re-anchor unsafe, reject-and-retry" ) pad.lines[idx:idx + hunk.old_len] = hunk.replacement pad.version += 1 def self_edit_step(pad: Scratchpad, build_hunk) -> None: pinned_version = pad.version pinned_hash = pad.snapshot_hash() # Model reasons over the pinned snapshot and emits a hunk. hunk = build_hunk(pinned_version, pinned_hash) # A tool result arrives between read and apply, bumping the version. pad.append("[FACTS] retrieved: intermediate result") # Apply must now fail loudly rather than splice the wrong span. apply_hunk(pad, hunk) if __name__ == "__main__": pad = Scratchpad(lines=["[GOAL] x", "[FACTS] a", "[DERIVATION] d1", "d2"], version=0) def stale_builder(v, h): return Hunk(start=3, old_len=2, replacement=["[DERIVATION] d1'", "d2'"], pinned_version=v, pinned_hash=h) try: self_edit_step(pad, stale_builder) except StaleDiffAnchorError as e: print(f"bounded failure: {e}") # Correct recovery: re-read current buffer, re-emit hunk against v1. ```