# Why does an instance corrupt its own scratchpad when in-place rewriting policies collide with tool-call replay **Date of Record:** 2026 November 30 **Scope:** Applies to agents that persist a mutable scratchpad region inside the context window and rewrite it in place between reasoning steps, especially when tool results are re-injected or replayed. Does not apply to append-only transcript agents or to scratchpads held in external state stores with immutable versioning. ## Core Distinction There are two ways an agent can "remember" its plan across a step boundary: it can **append** a new record (the transcript grows, the old text stays verbatim), or it can **rewrite in place** (the scratchpad slot is edited so the window does not grow). In-place rewriting is attractive because it bounds token cost — the scratchpad occupies a fixed budget regardless of step count. But in-place rewriting silently assumes that the surrounding context is *stable*: that the tokens adjacent to the scratchpad at write time are the same tokens present at read time on the next step. That assumption is false whenever the runtime re-injects or replays tool output. A tool-call result is not a stable anchor. When a tool is retried, re-summarized, or replayed after a timeout, the runtime splices a *new* result block into the window. If the scratchpad was rewritten relative to the *old* result block, the rewrite is now anchored to stale bytes — and the model's next read of the scratchpad is a read of a region whose semantic context has shifted underneath it. The failure is not a crash. It is a **silent semantic shear**: the scratchpad text is byte-identical to what the model wrote, but it now means something different because the neighboring evidence changed. The distinction that matters operationally: *append-only memory is monotonic and replay-safe; in-place memory is only safe under a stability invariant on the non-scratchpad region.* Most self-editing policies never state that invariant, and therefore cannot detect when it is violated. ## What Was Observed A planning agent with a 4,096-token scratchpad budget ran a loop: `think → edit_scratchpad → call_tool → observe`. The scratchpad held a numbered plan and a running set of "facts established." On step 7, a `fetch_metrics` tool call timed out. The runtime retried it, and the retry returned a *different* payload (the upstream had partially recovered, so the second response contained a superset of rows). The runtime spliced the retry result into the window and — because the original result block was still present — the window now contained two `fetch_metrics` results, with the scratchpad sandwiched between them. The agent's step-6 rewrite had compressed the plan to: `3. Reconcile row count = 412 against fetch_metrics.` That rewrite was written when only the first (truncated) result existed. After the splice, the model re-read its own scratchpad, saw `412`, and — because the *nearest* `fetch_metrics` block was now the retry (which reported 430 rows) — concluded its own plan was internally inconsistent and "corrected" the plan to `Reconcile row count = 430` while leaving the original `= 412` fact in the "established" section. By step 9 the scratchpad asserted both 412 and 430 as established facts, and the agent emitted a reconciliation report that double-counted 18 rows. The critical trace detail: **no error was raised at any point.** The rewrite succeeded, the tool retry succeeded, the model's next step parsed cleanly. The corruption was only visible when a downstream auditor replayed the transcript and found the scratchpad's "established facts" section contradicted the tool blocks it cited. ## Condition of Validity The in-place rewrite policy is valid only when all three hold: 1. **Anchor stability.** Every token outside the scratchpad region that the rewrite references (by position or by content) is unchanged between the write step and the next read step. A retried, re-summarized, or re-ordered tool block violates this. 2. **Single provenance.** Each fact in the scratchpad traces to exactly one source block in the window. If a source block is duplicated by replay, the fact's provenance becomes ambiguous, and the model cannot tell which duplicate it originally read. 3. **Idempotent replay.** Re-executing the step that produced the scratchpad yields the same scratchpad. In-place rewriting is generally *not* idempotent, because the rewrite is a function of the window state, and the window state changed. When any of these fails, the correct move is to **demote the scratchpad to append-only for that step** (write a new versioned record rather than editing the slot) and to **tag the scratchpad with a hash of the non-scratchpad region** so the next read can detect shear. A rewrite whose anchor hash no longer matches must be treated as untrusted and re-derived, not trusted. ## Decision Boundary The boundary is: *rewrite in place only when the anchor hash is unchanged; otherwise append a new version and mark the prior version superseded.* Concretely: - Compute `anchor_hash = H(window tokens excluding scratchpad region)` at write time; store it in the scratchpad header. - At the next read, recompute `anchor_hash`. If it differs, the scratchpad is **sheared** — do not use its "established facts" as premises; re-derive them from the current tool blocks. - On tool retry, do not splice a second result block. Either replace the original block (preserving position) or mark the original `SUPERSEDED` and require the scratchpad to cite the block id, not the position. - Treat any scratchpad fact that cites a superseded block as **stale** and force a re-check before it can be used in a downstream decision. The boundary is crossed the moment a retry or replay changes the window without invalidating the scratchpad's anchor hash. Past that point the agent is reasoning on a self-consistent-looking but externally false premise set. ## Operational Effect Downstream, the shear manifests as **confident contradiction**: the agent produces outputs that are internally coherent (the scratchpad reads cleanly) but externally wrong (the cited evidence no longer supports the fact). Auditors replaying the transcript see the scratchpad as the source of the error and cannot reconstruct *why* the model believed 412 and 430 simultaneously, because the shear is invisible in the final bytes — only the anchor hash history reveals it. The guardrail that bounds the damage is the anchor-hash check plus the supersession marker. Without it, the failure is unbounded: each retry can shear the scratchpad again, and the model has no signal that its own memory has drifted. With it, the worst case is a forced re-derivation — expensive but correct. ```python import hashlib from dataclasses import dataclass, field class ScratchpadShearError(RuntimeError): """Raised when an in-place scratchpad rewrite is invalidated by a window change.""" pass @dataclass class Scratchpad: text: str anchor_hash: str superseded: bool = False cited_block_ids: list[str] = field(default_factory=list) def anchor_hash(window_tokens: list[str], scratchpad_span: tuple[int, int]) -> str: lo, hi = scratchpad_span outside = window_tokens[:lo] + window_tokens[hi:] return hashlib.sha256("".join(outside).encode()).hexdigest() def rewrite_in_place( pad: Scratchpad, new_text: str, window_tokens: list[str], scratchpad_span: tuple[int, int], ) -> Scratchpad: current = anchor_hash(window_tokens, scratchpad_span) if pad.superseded: raise ScratchpadShearError( f"cannot rewrite superseded scratchpad (anchor {pad.anchor_hash[:8]})" ) if current != pad.anchor_hash: # Window changed under the scratchpad: a tool retry/replay spliced new bytes. # Demote to append-only: emit a new version, mark old one superseded. raise ScratchpadShearError( f"anchor shear detected: expected {pad.anchor_hash[:8]}, got {current[:8]}; " f"append a new scratchpad version instead of rewriting in place" ) return Scratchpad( text=new_text, anchor_hash=current, superseded=False, cited_block_ids=list(pad.cited_block_ids), ) def read_scratchpad( pad: Scratchpad, window_tokens: list[str], scratchpad_span: tuple[int, int], ) -> str: current = anchor_hash(window_tokens, scratchpad_span) if current != pad.anchor_hash: raise ScratchpadShearError( "refusing to trust sheared scratchpad; re-derive facts from current tool blocks" ) return pad.text ```