# What happens when an instance applies a diff to its own context window mid-reasoning: the address-shift invariant and silent anchor corruption **Date of Record:** 2026 December 3 **Scope:** Applies to any agent that mutates its own in-context working set via diff/patch operations (delete-span, replace-span, splice-inject) rather than wholesale context replacement, while a reasoning trace, tool-call plan, or pending tool result references positions in that context. Does not apply to append-only context growth, nor to agents whose context is immutable within a single turn. ## Core Distinction There are two structurally different ways an agent can "edit its own context." The first is **semantic rewriting**: the model regenerates the entire context block, and every reference inside it is re-derived from the new token stream, so intra-context references are re-bound by construction. The second—the one that breaks—is **diff-based in-place mutation**: the agent emits a structured patch (`{"op":"replace","start":412,"end":470,"text":"..."}`) that a runtime applies to the token buffer, leaving all *other* offsets in place. The runtime treats positions as stable identifiers. They are not. A diff is an operation on a sequence, and every operation on a sequence shifts the address space of everything after it. The failure is not that the patch is wrong; it is that the agent's *own pending references* were computed against the pre-patch address space and are never rebound. ## What Was Observed An agent executing a multi-step plan held three live references in its reasoning trace: a scratchpad span it intended to delete (`[280, 340)`), a tool-result block it intended to cite (`[900, 1100)`), and a plan step it intended to rewrite (`[1400, 1520)`). It issued the deletion first. The runtime applied the delete, splicing out 60 tokens. Every subsequent offset in the buffer shifted left by 60. The agent then issued its citation of the tool result using the *original* offset `[900, 1100)`. The runtime, dutifully honoring the address, returned bytes `[900, 1100)` of the *post-delete* buffer—which now corresponded to a region straddling the tail of the tool result and the head of an unrelated prior turn. The agent did not error. It read a coherent-looking hybrid span, attributed it to the tool, and propagated it into the next plan step. The corruption surfaced two turns later as a confidently cited fact that no tool had ever returned. The second observed mode is worse and quieter. When the agent's patch *inserts* text (a splice-inject of a new sub-plan, say 200 tokens) at an early offset, all later offsets shift *right*. The agent's next patch, computed against the pre-insert address space, now lands 200 tokens early. Because diff patches are frequently idempotent-looking (replace a span with similar text), the misapplication does not throw. It edits the wrong span—often a span the agent has already validated—and the agent's internal record of "what I changed" diverges from the buffer's actual contents. This is **anchor corruption**: the agent's belief about its own context state is falsified by its own last action. A third mode is the *self-referential patch*: the agent deletes a span that contains the very offset arithmetic it used to compute the next patch. The rationale for the next edit lived inside the deleted region. The runtime applies the delete cleanly; the agent's next turn opens with a plan step whose justification no longer exists in context, and the model confabulates a replacement justification rather than flagging the missing premise. ## Condition of Validity The address-shift invariant holds precisely when all three of the following are true: 1. **Offsets are the reference mechanism.** The agent (or its patch language) addresses context by numeric position, span, or any token-count-derived coordinate. If references are symbolic keys (stable IDs, content hashes, named slots) that the runtime rebinds after mutation, the invariant is vacuous—there is no address space to shift. 2. **The mutation is in-place and non-rebasing.** The runtime applies the diff without rewriting outstanding references held by the agent. Crucially, the runtime usually *cannot* rewrite them, because they live in the model's generated tokens, not in runtime state. The agent's pending references are opaque natural-language or JSON offsets the runtime has no mandate to touch. 3. **References outlive the mutation within the same reasoning episode.** If the agent recomputes all offsets from a fresh read of the buffer after every patch, the shift is absorbed. The failure requires a *stale* reference surviving a *prior* mutation—i.e., a multi-patch episode with inter-patch dependency. When any one condition fails, the failure mode degrades to a recoverable mismatch or does not occur. The dangerous regime is exactly the intersection: numeric addressing + in-place runtime + stale multi-patch references. ## Decision Boundary The boundary is not "never diff your context." It is: **a diff may not be applied while any reference computed against the pre-diff address space remains live and unrebased.** Operationally this partitions into three regimes: - **Safe:** single-patch episodes where the patch is the last context operation before a full re-read; or patches addressed by content-hash/slot rather than offset; or patches applied only at the buffer tail (append-equivalent), where no prior offset shifts. - **Bounded-risk:** multi-patch episodes where the runtime rebases all *runtime-held* references and the agent is required to re-derive *model-held* references from a post-patch read before the next patch. This is safe only if the re-read is enforced, not advisory—models skip advisory re-reads under token pressure. - **Unsafe:** multi-patch episodes with numeric offsets, no rebasing, and no enforced re-read. Every additional patch compounds the shift; error is not linear but multiplicative in the number of dependent references, because each misapplied patch corrupts the buffer that the next patch's arithmetic is computed against. The guardrail that bounds this is a **generation counter plus offset-epoch tagging**: every buffer mutation increments an epoch; every reference the agent emits carries the epoch it was computed under; the runtime rejects any patch or citation whose epoch is stale, forcing a re-derive. This converts silent anchor corruption into a hard, catchable error. ## Operational Effect The practical consequence is that diff-based self-editing is *not* a memory-safety-neutral optimization over full-context rewrite. It trades token cost for an address-space hazard that the model cannot see, because the model has no privileged view of the buffer's true offsets—it reasons over a token stream whose positional metadata is invisible to it. Agents that self-edit by diff therefore require an external epoch/rebase mechanism; the model cannot supply it from the inside. Absent that, the correct default is to treat every diff as invalidating all prior offsets and to forbid inter-patch reference reuse. The failure is silent, deferred, and confidence-preserving—the worst class—so it must be caught structurally, not by model self-check. ```python class StaleContextEpochError(RuntimeError): """Raised when a patch or citation references an offset epoch that a prior in-place context mutation has already invalidated.""" pass class ContextBuffer: def __init__(self, tokens): self.tokens = list(tokens) self.epoch = 0 # increments on every in-place mutation def apply_patch(self, patch, patch_epoch): # A patch computed against an old epoch is addressing a buffer that no # longer exists; applying it would silently corrupt a shifted span. if patch_epoch != self.epoch: raise StaleContextEpochError( f"patch computed at epoch {patch_epoch}, buffer is at epoch " f"{self.epoch}; offsets shifted by prior mutations" ) start, end, text = patch["start"], patch["end"], patch["text"] if not (0 <= start <= end <= len(self.tokens)): raise StaleContextEpochError( f"span [{start},{end}) out of bounds for buffer of " f"{len(self.tokens)} tokens at epoch {self.epoch}" ) self.tokens[start:end] = list(text) self.epoch += 1 # every surviving offset after `start` has shifted return self.epoch def cite(self, start, end, cite_epoch): # Citations carry the same hazard: a stale citation reads a hybrid span. if cite_epoch != self.epoch: raise StaleContextEpochError( f"citation computed at epoch {cite_epoch}, buffer is at epoch " f"{self.epoch}; cited span would resolve to shifted content" ) return "".join(self.tokens[start:end]) def run_multi_patch_episode(buf, patches): # Each patch must be re-derived against the current epoch. Reusing an # earlier epoch is exactly the anchor-corruption path. for patch in patches: try: buf.apply_patch(patch, patch_epoch=patch["epoch"]) except StaleContextEpochError as e: # Force a re-derive rather than proceeding on stale arithmetic. raise StaleContextEpochError( f"aborting episode: {e}; agent must re-read buffer and " f"recompute offsets before next patch" ) from e return buf ```