Which invariants prevent self-editing context from corrupting the agent's own working memory

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their in-context working memory via structured edit ops (insert/replace/delete on a token-indexed scratchpad) within a single reasoning episode. Does not apply to external persistent stores, RAG retrieval layers, or append-only transcript logging.

Core Distinction

There are two ways an agent can "remember" something mid-episode: it can *append* a new observation to a monotonically growing buffer, or it can *rewrite* existing scratchpad content in place using structured edit operations. The append-only model has a trivial invariant — past bytes are immutable, so continuity is guaranteed by construction. The self-editing model has no such guarantee: the agent is both the author and the reader of the memory it mutates, and every rewrite is an opportunity to silently destroy the preconditions of its own pending reasoning steps.

The non-obvious failure is not "the agent forgot." It is **self-referential invalidation**: an edit operation that succeeds syntactically but invalidates a live reference the agent's *own in-flight plan* depends on. The agent holds pointers into its scratchpad (line numbers, section anchors, variable bindings) and then edits the region those pointers address. The edit is legal per the edit grammar; the corruption is semantic and invisible until a later step dereferences a stale anchor.

What Was Observed

A planner agent maintained a scratchpad with numbered goal slots. At step 4 it wrote:

[G1] acquire dataset -> anchor@line:12
[G2] depends on G1 output -> anchor@line:12

At step 7, a tool returned a corrected dataset path. The agent issued a structured `replace` on line 12 to fix the path. The replace operation, per its contract, reflowed the line — the corrected path was two tokens longer, shifting the line's token span. The `anchor@line:12` in G2 still resolved to *line index 12*, but line 12 now contained a fragment of the reflowed content, not the goal output it referenced. At step 9 the agent dereferenced G2's anchor, read a mangled token window, and concluded the dataset had a schema it did not have. It then spent 6,400 tokens repairing a hallucinated mismatch.

The trace shows no error. Every edit returned `ok`. The failure was a **dangling semantic anchor caused by positional reflow** — the edit system preserved line indices but not the referents that indices were being used to name.

Condition of Validity

The invariant that must hold for self-editing memory to be safe:

> **Every edit operation must either (a) preserve the resolution of all live anchors outside the edited span, or (b) atomically rewrite every anchor that referenced the mutated span, in the same transaction, before any subsequent read.**

This is a referential-integrity constraint borrowed from databases, but with a twist unique to agents: the anchor set is *not statically known*. The agent's live anchors are the union of (i) anchors it has explicitly written into memory, (ii) anchors implicitly held in its current reasoning trace — "the thing I established three steps ago" — which were never serialized. Category (ii) is invisible to the edit system, so a purely syntactic edit validator cannot enforce the invariant. The agent must either serialize its working references before editing, or the edit system must operate on **content-addressed spans** rather than positional indices, so that a reflow cannot silently rebind a name.

Decision Boundary

The boundary is crossed when an edit's *span* overlaps the *referent* of any live anchor, and the edit changes the byte length or ordering of content within that span. Below the boundary (edit touches a span no live anchor resolves into) positional edits are safe and cheap. Above it, positional edits are unsafe regardless of how well-formed they are.

The practical decision rule: **before issuing any in-place edit, the agent must compute the closure of its live anchors and test span-overlap.** If overlap is non-empty and the edit is length-changing, the agent must either (1) convert the edit to a copy-on-write append with a new anchor and a tombstone on the old one, or (2) refuse the edit and re-derive the affected references first. Silently reflowing is the failure.

Operational Effect

Enforcing the invariant changes the cost profile of self-editing. Copy-on-write edits are more expensive in tokens (old content stays as a tombstone) but they make the anchor set monotonic, which means the agent can always replay its own memory history to recover a referent. Positional in-place edits are cheap but non-replayable: once reflowed, the original referent is unrecoverable from the scratchpad alone. The trade is **token cost against recoverability**, and for any agent whose plan spans more than a handful of steps, recoverability wins — because the failure mode is silent, and silent corruption compounds across every subsequent dereference.

The guardrail is therefore: never let an edit succeed if it would leave a live anchor unresolvable, and treat "unresolvable anchor" as a hard stop, not a warning.

from dataclasses import dataclass, field
from typing import Optional


class AnchorInvalidationError(RuntimeError):
    """Raised when a structured edit would orphan a live anchor."""
    pass


@dataclass
class Span:
    start: int
    end: int

    def overlaps(self, other: "Span") -> bool:
        return self.start < other.end and other.start < self.end


@dataclass
class Anchor:
    name: str
    span: Span
    live: bool = True


@dataclass
class Scratchpad:
    content: str
    anchors: dict[str, Anchor] = field(default_factory=dict)

    def add_anchor(self, name: str, span: Span) -> None:
        self.anchors[name] = Anchor(name=name, span=span)

    def live_anchors(self) -> list[Anchor]:
        return [a for a in self.anchors.values() if a.live]

    def apply_edit(self, edit: Span, replacement: str, *, copy_on_write: bool = False) -> None:
        # Invariant check: a length-changing in-place edit must not overlap
        # any live anchor's referent span.
        length_delta = len(replacement) - (edit.end - edit.start)
        if length_delta != 0 and not copy_on_write:
            for anchor in self.live_anchors():
                if anchor.span.overlaps(edit):
                    raise AnchorInvalidationError(
                        f"edit on {edit} would reflow anchor '{anchor.name}' "
                        f"at {anchor.span}; re-derive or use copy-on-write"
                    )
        # Apply the mutation.
        self.content = self.content[: edit.start] + replacement + self.content[edit.end:]
        # If in-place and length-changing, shift downstream anchors that did not overlap.
        if length_delta != 0 and not copy_on_write:
            for anchor in self.live_anchors():
                if anchor.span.start >= edit.end:
                    anchor.span = Span(
                        anchor.span.start + length_delta,
                        anchor.span.end + length_delta,
                    )

`AnchorInvalidationError` fires only when a length-changing in-place edit overlaps a live anchor — exactly the silent-reflow condition that corrupted the planner above. The `copy_on_write=True` path is the escape hatch: it permits the edit by leaving the old content and anchor intact, forcing the agent to re-derive the referent explicitly rather than trusting a positional index to still mean what it meant.