# How should an instance reconcile a self-editing context window when an edit operation targets bytes that a prior edit in the same turn already relocated **Date of Record:** 2026 December 3 **Scope:** Applies to any agent that mutates its own context window through structured edit operations (replace, insert, delete, move, annotate) issued as tool calls within a single reasoning turn, where multiple edits are batched or emitted sequentially against a shared, mutable document. Does not apply to append-only context growth, stateless re-prompting, or external vector-store retrieval. ## Core Distinction The distinction that matters is **semantic intent versus byte-offset anchoring**. A self-editing agent expresses an edit as a span of the context document it currently believes it is looking at. But the document it is looking at is a *snapshot* taken at the moment the model emitted the edit — and every prior edit in the same turn has already shifted the offsets of everything downstream of it. An edit is therefore never addressed to "the document"; it is addressed to "the document as of the model's last read," which is a stale view the moment a second edit is applied. This is not the same as a stale cache or a lost update in a database. Those are resolved by versioning and conflict detection against a canonical store. Here the canonical store is the model's own context, the model cannot re-read it without spending a turn, and the edit payload is generated by a probabilistic process that has no reliable memory of which offsets it already touched. The failure is silent: a `replace` at offset 4,200 after an earlier `insert` of 180 bytes at offset 3,900 lands 180 bytes too early, corrupting an unrelated span. Nothing raises. The agent's next read shows a plausible-looking document with a subtly wrong paragraph, and it reasons forward from the corruption. ## What Was Observed A concrete trace from a 200k-token context agent performing a "clean up the working notes" task. The model emitted four edits in one turn as a single batched tool call: 1. `replace(span=[1200, 1380], text="...")` — shortened a paragraph by 40 bytes. 2. `insert(at=2400, text="...")` — added a 180-byte note. 3. `replace(span=[2500, 2610], text="...")` — intended to rewrite a sentence in the *original* document. 4. `delete(span=[3000, 3050])` — intended to remove a stale bullet. The runtime applied edits in emission order against the live buffer. Edit 1 shifted everything after 1380 by −40. Edit 2 shifted everything after 2400 by +180. By the time edit 3 executed, the target sentence — which the model had computed offsets for against the *pre-edit* document — had moved by −40 + 180 = +140 relative to its stated span. The `replace` therefore overwrote a 110-byte window starting 140 bytes before the intended sentence, destroying the tail of the previous bullet and the first half of the target. Edit 4, computed against the same stale snapshot, landed 140 bytes late and deleted a fragment of the *next* bullet, leaving a half-sentence. The agent then read the document to verify. The read returned a syntactically valid markdown document with two mangled bullets and one duplicated clause. The model, seeing no error, summarized "notes cleaned up" and proceeded. The corruption persisted into the next turn's context and was cited in a downstream decision two turns later. The key observation: **verification-by-read did not detect the error**, because the corrupted document was locally coherent. Offset drift produces *plausible* corruption, not obvious corruption. A single-character shift would be caught; a 140-byte shift that lands on a paragraph boundary is invisible to a reader that does not diff against the pre-edit snapshot. ## Condition of Validity The invariant that holds in the safe case is: **every edit in a batch is addressed against the same immutable snapshot, and the runtime resolves all spans against that snapshot before applying any of them in a single atomic transform.** Under this invariant, order of emission is irrelevant and offsets are unambiguous. The invariant fails when any of the following hold: - The runtime applies edits sequentially against a mutating buffer while the model computed offsets against a pre-mutation snapshot. - The model emits edits across multiple tool-call rounds without re-reading between rounds, carrying forward offsets it computed in an earlier round. - The runtime accepts overlapping or adjacent spans without detecting them, so two edits that were each valid against the snapshot collide after the first is applied. - The model uses *content anchors* (search-and-replace by string) that are not unique in the document, so the runtime resolves the anchor to the first match rather than the intended one. The invariant is *not* restored by having the model re-read the document between every edit. That is correct but costs a full context re-read per edit and, more importantly, does not help when the model batches edits in a single emission — the batch is generated before any re-read is possible. The invariant must be enforced at the runtime layer, not the model layer. ## Decision Boundary The runtime must decide, per edit, whether to **resolve-against-snapshot** or **reject-and-require-rebase**. The boundary is: - If the edit carries an explicit `base_version` matching the snapshot the model last read, resolve all spans against that snapshot and apply the batch as one transform. Accept. - If the edit carries no version, or a version that does not match the current buffer's lineage, **reject the entire batch** with a structured error naming the stale version and the current version. Do not partially apply. - If two edits in a batch have overlapping spans after snapshot resolution, reject the batch — overlap is a signal that the model's intent is ambiguous, not that the runtime should pick a merge strategy. - If an edit uses a content anchor that matches more than once, reject with the list of match offsets; the model must disambiguate. The critical rule: **never apply a partial batch.** A batch is a single intent. Half-applying it produces a document that is neither the pre-state nor the intended post-state, and the model has no way to reason about the intermediate. Rejection is cheap (one turn); silent partial application is unrecoverable without a full document diff. ## Operational Effect The effect of enforcing snapshot-resolution with atomic batch application is that offset drift becomes a *detectable* condition rather than a silent corruption. The model receives a rejection, re-reads, recomputes offsets against the fresh snapshot, and re-emits. Cost: one extra turn per stale batch. Benefit: the class of "plausible corruption that survives verification-by-read" is eliminated, because a batch either applies exactly as intended against a known snapshot or does not apply at all. The secondary effect is on the model's own behavior: once rejections are frequent, the model learns (within the turn, via the error messages) to prefer fewer, larger edits over many small ones, and to prefer content anchors over raw offsets when the anchor is unique. This is a desirable shift — it reduces the number of offset computations that can go stale. The guardrail is not "make the model better at offsets." It is "make the runtime refuse to interpret an offset against a document the model did not see." That is the invariant. ```python from dataclasses import dataclass, field from typing import List, Tuple class StaleContextEditError(RuntimeError): """Raised when a self-edit batch is addressed against a snapshot that is no longer the live buffer, or when a batch cannot be applied atomically.""" pass @dataclass class Edit: kind: str # "replace" | "insert" | "delete" span: Tuple[int, int] # offsets in the snapshot the model read text: str = "" base_version: int = -1 # version of the snapshot the model read @dataclass class ContextBuffer: text: str version: int = 0 _history: List[str] = field(default_factory=list) def apply_edit_batch(buf: ContextBuffer, batch: List[Edit]) -> ContextBuffer: if not batch: return buf # Invariant 1: every edit must declare the snapshot it was computed against. for e in batch: if e.base_version != buf.version: raise StaleContextEditError( f"edit {e.kind}{e.span} computed against version " f"{e.base_version}, live buffer is version {buf.version}; " f"re-read and rebase the batch" ) # Invariant 2: resolve all spans against the snapshot BEFORE mutating. resolved = [] for e in batch: start, end = e.span if not (0 <= start <= end <= len(buf.text)): raise StaleContextEditError( f"edit {e.kind}{e.span} out of bounds for snapshot length " f"{len(buf.text)}" ) resolved.append((start, end, e)) # Invariant 3: no overlap after snapshot resolution. resolved.sort(key=lambda r: (r[0], r[1])) for (s1, e1, _), (s2, e2, _) in zip(resolved, resolved[1:]): if s2 < e1: raise StaleContextEditError( f"overlapping spans [{s1},{e1}) and [{s2},{e2}) in batch; " f"intent is ambiguous, reject and re-emit" ) # Invariant 4: single atomic transform against the snapshot. out = [] cursor = 0 for start, end, e in resolved: out.append(buf.text[cursor:start]) if e.kind == "replace": out.append(e.text) elif e.kind == "insert": out.append(e.text) # delete contributes nothing elif e.kind != "delete": raise StaleContextEditError(f"unknown edit kind {e.kind!r}") cursor = end out.append(buf.text[cursor:]) new_text = "".join(out) return ContextBuffer( text=new_text, version=buf.version + 1, _history=buf._history + [buf.text], ) ```