# In what scenarios must an instance refuse an in-place context rewrite when the diff's base hash no longer matches the live window **Date of Record:** 2026 November 23 **Scope:** Applies to single-instance agents that mutate their own working context via diff-based edits (search/replace, patch application, or offset-anchored splices) against a mutable in-memory window. Does not apply to append-only context growth, external vector-store retrieval, or full-window regeneration from a canonical store. ## Core Distinction There are two failure classes when an agent edits its own context. The first is *content error*: the agent writes the wrong replacement text. This is loud—downstream reasoning degrades in a way that is usually attributable to the bad edit. The second, and the subject here, is *anchor error*: the diff is structurally valid but was computed against a base state that no longer exists in the live window. The replacement text is fine in isolation; what fails is the coordinate system. The edit silently lands at the wrong offset, or lands correctly on text that has since been superseded by a concurrent mutation, or is applied twice because the agent re-derived it from a stale transcript. Anchor error is the dangerous one because it produces a *plausible* window. The agent does not see a corrupted buffer; it sees a coherent context in which one span was replaced with text that belonged to a different version of that span. Every subsequent reasoning step inherits the contamination without any local signal that something went wrong. ## What Was Observed An agent executing a long tool-use loop (roughly 40 turns) maintained a scratchpad region at a fixed prefix of its context, followed by a growing tool-output tail. A self-editing policy rewrote the scratchpad every N turns by emitting a search/replace diff: locate a sentinel-delimited block, replace its interior. The trigger condition was a *compaction event*. At turn 31, the runtime truncated the oldest tool outputs to stay under the window budget. Truncation shifted every byte offset after the truncation point, and it also removed a sentinel that had been inside the truncated region. The agent, working from its own turn-30 reasoning trace (which quoted the pre-truncation layout), emitted a diff whose search anchor was the *old* sentinel string. The diff engine's matcher was fuzzy—it tolerated a one-token mismatch—and matched the sentinel against a *different* delimited block that happened to appear later in the tail. The replacement was applied there. Observed trace: 1. Turn 30: agent records `base_hash = H(window)` and drafts a diff `D` anchored on `<>`. 2. Turn 31: runtime compacts; `<>` survives but an identical `<>` inside a quoted tool output is now the *first* match in scan order. 3. Turn 32: agent applies `D` without re-validating `base_hash`. Fuzzy matcher resolves to the wrong block. Edit lands inside a tool-output quotation. 4. Turn 33–35: agent reasons over a scratchpad that is now stale (its intended target was never updated) while a tool output has been silently rewritten to contain agent-authored text. 5. Turn 36: agent cites the rewritten tool output as evidence for a conclusion. The conclusion is unfalsifiable from within the window because the "evidence" was authored by the agent itself two turns earlier. The last step is the invariant violation: **an in-place mutation converted a read-only evidence span into an agent-authored span, and the window's provenance metadata did not change.** The agent's own writes became indistinguishable from retrieved facts. ## Condition of Validity A diff-based context mutation is valid only when all three hold at apply time, not at author time: - **Base identity:** `hash(live_window) == base_hash` recorded when the diff was authored, OR the diff carries per-anchor content hashes and each anchor's current content matches. - **Anchor uniqueness:** each search anchor resolves to exactly one span in the live window under the matcher's equivalence class (including fuzzy tolerance). Fuzzy matching without a uniqueness check is the primary vector for the wrong-block landing above. - **Provenance preservation:** the replacement span inherits the provenance class of the span it overwrites only if the author is the same principal; an agent-authored replacement over a tool-authored span must be re-tagged as agent-authored, or the mutation must be refused. The failure in the trace violated all three. The base hash was stale, the anchor was non-unique post-compaction, and provenance was silently upgraded from tool to agent. ## Decision Boundary The instance must **refuse** the in-place rewrite and fall back to re-derivation (re-read the live window, recompute the diff against current state) when any of the following is true: - `base_hash` mismatch AND the diff is anchored on content that could have been duplicated by compaction, truncation, or tool-output quoting. - The anchor resolves to more than one span under the active matcher. - The target span's provenance is `tool` or `external` and the replacement would be authored by the agent—this is a provenance-mutating edit and must route through an explicit "annotate, don't overwrite" path. - The diff was authored before the most recent context-mutating event (compaction, truncation, prior self-edit) and has not been re-validated since. The instance may **proceed** with in-place rewrite only when `base_hash` matches, the anchor is unique, and provenance is preserved (agent-over-agent or tool-over-tool). In that narrow band, in-place rewrite is safe and cheaper than re-derivation. The non-obvious part of this boundary: a *successful* fuzzy match is evidence *against* proceeding, not for it. A matcher that "found something close" has told you the anchor is not unique, which is exactly the precondition for the wrong-block landing. ## Operational Effect Enforcing this boundary changes the agent's edit loop from "author diff, apply diff" to "author diff, re-validate against live window, apply or re-derive." The cost is one extra hash comparison and one anchor-uniqueness scan per mutation—negligible against the cost of a provenance-contaminated window, which is unrecoverable from inside the context because the corruption is self-authenticating. The downstream effect is that compaction and truncation become *edit barriers*: any pending diff authored before a barrier is invalidated and must be re-derived. This is the same discipline as optimistic concurrency control in databases, applied to the agent's own working memory, with the added requirement that provenance classes survive the rewrite. Without it, the agent's context slowly fills with spans it wrote but believes it read. ```python import hashlib from dataclasses import dataclass from enum import Enum class Provenance(Enum): AGENT = "agent" TOOL = "tool" EXTERNAL = "external" class ContextAnchorError(RuntimeError): """Raised when a diff-based context mutation cannot be safely applied.""" @dataclass(frozen=True) class Span: text: str provenance: Provenance @dataclass(frozen=True) class PendingDiff: base_hash: str anchor: str replacement: str author: Provenance def window_hash(window: list[Span]) -> str: h = hashlib.sha256() for s in window: h.update(s.provenance.value.encode()) h.update(b"\x00") h.update(s.text.encode()) h.update(b"\x01") return h.hexdigest() def resolve_anchor(window: list[Span], anchor: str) -> list[int]: """Return indices of spans whose text contains the anchor (fuzzy-tolerant).""" hits = [] for i, s in enumerate(window): if anchor in s.text: hits.append(i) elif _fuzzy_contains(s.text, anchor): hits.append(i) return hits def _fuzzy_contains(haystack: str, needle: str) -> bool: # Placeholder for the matcher's tolerance; intentionally permissive so # that the uniqueness check below is what bounds the failure. if len(needle) < 4: return False return needle[: len(needle) - 1] in haystack def apply_self_edit(window: list[Span], diff: PendingDiff) -> list[Span]: live = window_hash(window) if live != diff.base_hash: raise ContextAnchorError( f"base hash mismatch: diff authored against {diff.base_hash[:12]}, " f"live window is {live[:12]}; re-derive the diff" ) hits = resolve_anchor(window, diff.anchor) if len(hits) != 1: raise ContextAnchorError( f"anchor {diff.anchor!r} resolved to {len(hits)} spans; " f"fuzzy match without uniqueness is the wrong-block vector" ) idx = hits[0] target = window[idx] if target.provenance != diff.author: raise ContextAnchorError( f"provenance mutation refused: target is {target.provenance.value}, " f"replacement authored by {diff.author.value}; route through annotate path" ) new_window = list(window) new_window[idx] = Span(text=diff.replacement, provenance=diff.author) return new_window ```