# In what scenarios must an instance treat self-editing of its own context window as a transactional mutation rather than an in-place rewrite, and what invariant breaks when it does not **Date of Record:** 2026 November 26 **Scope:** Applies to any agent that mutates its own working context through structured edit operations (block replace, span delete, region summarize, anchor-insert) issued by the model itself and applied to the live context buffer between reasoning steps. Does not apply to append-only scratchpads, external memory stores updated out-of-band, or human-driven prompt editing. ## Core Distinction There are two ways a model can "rewrite its own context": *append-only composition*, where new content is added and prior tokens are never touched, and *in-place mutation*, where an edit operation replaces or deletes a span that the model is still reasoning over, including the very span that defines the edit's own preconditions. The second is the dangerous one, and the failure is not that the edit is wrong—it is that the edit is applied against a *stale view* of the buffer that the model no longer holds. The non-obvious boundary: a self-edit is a read-modify-write over a region the model is simultaneously reasoning about. The model's reasoning trace at step *n* is a function of buffer state *S_n*, but the edit it emits is computed from *S_n* and then applied to *S_{n+1}*, which may already differ because (a) the edit instruction itself was appended, (b) a prior edit in the same batch shifted offsets, or (c) a tool result landed asynchronously. When the edit is expressed positionally (character offsets, line numbers, "the third paragraph") rather than by content anchor, the mutation lands on the wrong span. The invariant that must hold is **anchor stability**: every self-edit must resolve against a content-addressed anchor that is re-validated at apply time, and must be rejected if the anchor has moved, been deleted, or been rewritten by an earlier edit in the same transaction. ## What Was Observed A long-horizon agent was given a context buffer of ~180k tokens and a `context_edit` tool with operations `replace(start, end, text)`, `delete(start, end)`, and `summarize(start, end)`. Offsets were computed by the model from a numbered rendering of the buffer. The agent was instructed to periodically compress its own working set: "keep the task spec, the last three tool results, and a rolling summary; delete the rest." Trace of the failure, abbreviated: 1. At step 41 the buffer is 172,300 tokens. The model emits a batch of five edits in one response: three `delete` on early tool logs, one `replace` on a stale plan block, one `summarize` over the middle third. 2. The runtime applies edits **in emitted order, against the live buffer**, recomputing nothing. Edit #1 deletes 2,100 tokens at offset 4,000. Edits #2–#5 still carry offsets computed against the *pre-edit* buffer. 3. Edit #2 (`replace(9,200, 9,600, ...)`) now lands 2,100 tokens early, overwriting the **task specification block** rather than the stale plan. The task spec is gone; the plan block survives. 4. Edit #4 (`summarize(58,000, 119,000)`) now spans across the boundary between the surviving plan and the last tool result, collapsing a tool result the model intended to keep into a summary that drops the exact error string it needed. 5. At step 42 the model reasons over the mutated buffer. It has no record that its task spec was destroyed—the deletion is silent, and the model's own prior reasoning that "the spec is at the top" is now false but still present in its working assumptions. 6. The agent proceeds for 60 more steps, confidently optimizing against a plan it can no longer see, and only fails when a downstream validator rejects an output that violates a constraint stated in the deleted spec. The signature: **no single edit was malformed**. Each was a valid operation on the buffer the model believed it held. The corruption came entirely from offset drift within a batch plus the absence of any post-edit re-read. ## Condition of Validity The in-place model is only sound under a conjunction that is almost never satisfied in practice: - **Single-edit transactions.** At most one mutating edit per reasoning step, so no intra-batch offset drift is possible. - **Content anchors, not offsets.** Each edit names a stable anchor (a hash of the target span, or a unique sentinel token) and the runtime resolves the anchor at apply time, failing closed if it is absent or ambiguous. - **Apply-then-reread.** The model receives the post-edit rendering of every touched region before its next reasoning step, so its working assumptions are re-grounded rather than carried forward. - **Monotonic offset accounting.** If positional edits are used at all, the runtime must rebase all pending offsets after each applied edit, and the model must be told the rebase occurred. When any of these is violated—and in batched self-editing, all four typically are—the buffer the model reasons over and the buffer it mutates diverge, and the divergence is invisible to the model because the evidence of the mutation was itself mutated away. ## Decision Boundary The boundary is between **edits that are recoverable from the model's own trace** and **edits that destroy the evidence needed to detect their own misfire**. - A `delete` of a region the model can reconstruct from its reasoning trace is recoverable: if it lands wrong, the model can notice the missing content on next read and re-derive it. - A `delete` or `summarize` that removes the task specification, the constraint list, or the anchor definitions themselves is **unrecoverable**: the model cannot detect the loss because the detection criterion was in the deleted span. This is the class that must be forbidden or gated. Concretely: any self-edit whose target overlaps a **protected region**—task spec, active constraints, anchor table, or the edit log itself—must be rejected at apply time, not merely discouraged in the prompt. And any batch containing more than one mutating edit must be applied as a transaction: all anchors resolved against the pre-batch snapshot, all-or-nothing, with a post-commit re-render delivered to the model. ## Operational Effect The practical consequence is that self-editing context must be implemented as a **transactional mutation with content-addressed anchors and mandatory post-commit re-grounding**, not as a sequence of in-place splices. The runtime, not the model, owns offset resolution and rebasing; the model expresses intent ("remove the stale plan block identified by sentinel `<>`") and the runtime either resolves it exactly or rejects it. The model must never be permitted to compute positional offsets into its own live buffer, because those offsets are computed against a state that the act of editing invalidates. The second consequence is that **the edit log is part of the protected state**. If the model cannot see what it deleted, it cannot reason about what it lost. A compact, append-only record of applied edits—target anchor, operation, timestamp, resulting span hash—must survive every compression pass and must itself be immune to `summarize`. This is the only mechanism by which a later reasoning step can ask "did I destroy something I needed?" and get a truthful answer. ```python import hashlib from dataclasses import dataclass, field class AnchorResolutionError(RuntimeError): """Raised when a self-edit cannot be resolved against the live buffer.""" pass class ProtectedRegionViolation(RuntimeError): """Raised when a self-edit targets a region whose loss is undetectable.""" pass @dataclass class Span: anchor: str # content hash of the span at snapshot time start: int end: int text: str protected: bool = False def _hash(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] @dataclass class ContextBuffer: spans: list[Span] = field(default_factory=list) edit_log: list[dict] = field(default_factory=list) def snapshot(self) -> dict[str, Span]: # Anchors are content hashes; duplicate content collapses, which is # exactly why ambiguous anchors must fail closed rather than guess. return {s.anchor: s for s in self.spans} def apply_transaction(self, edits: list[dict]) -> None: """Apply a batch of self-edits atomically against the pre-batch snapshot. Each edit: {"op": "delete"|"replace"|"summarize", "anchor": str, ...} All anchors resolve against the snapshot taken before any edit lands. If any anchor is missing, ambiguous, or protected, the whole batch is rejected and the buffer is left untouched. """ snap = self.snapshot() resolved: list[tuple[Span, dict]] = [] for edit in edits: anchor = edit.get("anchor") if anchor is None: raise AnchorResolutionError( f"edit {edit!r} has no content anchor; positional self-edits " f"are forbidden because offsets drift within a batch" ) if anchor not in snap: raise AnchorResolutionError( f"anchor {anchor!r} not present in pre-batch snapshot; " f"target was likely deleted or rewritten by an earlier edit" ) target = snap[anchor] if target.protected: raise ProtectedRegionViolation( f"anchor {anchor!r} resolves to protected region " f"(spec/constraints/anchor-table/edit-log); loss would be " f"undetectable from the model's own trace" ) resolved.append((target, edit)) # Commit phase: only reached if every anchor validated. drop = {id(t) for t, e in resolved if e["op"] == "delete"} new_spans: list[Span] = [] for s in self.spans: if id(s) in drop: self.edit_log.append({"op": "delete", "anchor": s.anchor, "hash": _hash(s.text)}) continue new_spans.append(s) for target, edit in resolved: if edit["op"] == "replace": replacement = edit["text"] if _hash(replacement) == target.anchor: continue new_spans.append(Span(anchor=_hash(replacement), start=target.start, end=target.end, text=replacement, protected=target.protected)) self.edit_log.append({"op": "replace", "anchor": target.anchor, "hash": _hash(replacement)}) elif edit["op"] == "summarize": summary = edit["summary"] if not summary: raise AnchorResolutionError( f"summarize of {target.anchor!r} produced empty summary; " f"refusing to commit a silent full deletion" ) new_spans.append(Span(anchor=_hash(summary), start=target.start, end=target.end, text=summary, protected=False)) self.edit_log.append({"op": "summarize", "anchor": target.anchor, "hash": _hash(summary)}) self.spans = new_spans # Edit log is append-only and never itself summarized; a later step # can always ask "what did I destroy?" and get a truthful answer. def render_for_model(self) -> str: """Post-commit re-render; model must reason over this, not its stale view.""" body = "\n---\n".join(s.text for s in self.spans) log = "\n".join(f"{e['op']} {e['anchor']} -> {e['hash']}" for e in self.edit_log[-20:]) return f"{body}\n\n==EDIT LOG==\n{log}" # --- demonstrating the failure the guardrail prevents ------------------- def compress_working_set(buf: ContextBuffer) -> None: spec = next((s for s in buf.spans if s.protected), None) if spec is None: raise ProtectedRegionViolation( "no protected task-spec span present; refusing to compress because " "the constraint list cannot be guaranteed to survive" ) # Model intent expressed as anchors, never offsets. stale_plan = next((s for s in buf.spans if not s.protected and "PLAN_v3" in s.text), None) if stale_plan is None: raise AnchorResolutionError( "stale plan anchor <> not found; cannot safely delete" ) buf.apply_transaction([ {"op": "delete", "anchor": stale_plan.anchor}, # If this second edit carried a stale offset instead of an anchor, # it would silently overwrite the spec. The anchor check rejects it. {"op": "replace", "anchor": spec.anchor, "text": "..."}, ]) ```