What structural signals indicate in-place instruction rewriting has corrupted the context window's semantic anchor

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their own context window via in-place instruction rewriting or diff-based context edits (search/replace patches, span rewrites, anchor-based splicing) rather than append-only or full-regeneration strategies. Does not apply to append-only context management or to external memory stores that are re-read from scratch.

Core Distinction

Append-only context management is *monotonic*: every prior token remains addressable, so a rewrite can only add noise, never silently destroy the referent of an existing instruction. In-place rewriting breaks monotonicity. When an agent edits its own context by patching spans — replacing `"use the staging endpoint"` with `"use the production endpoint"`, or collapsing a diff that removes a superseded constraint — the edit is applied against a *positional or textual anchor* that the model resolved at edit-generation time. The failure is not that the patch is wrong. The failure is that the patch's anchor was resolved against a context state that the patch itself is about to invalidate, producing a *semantic anchor drift*: the rewritten instruction now points at a referent that no longer exists, or points at the wrong one, while remaining syntactically well-formed and locally plausible.

The non-obvious part: the corrupted context does not look corrupted. It reads fluently. The signal is structural, not semantic — you detect it by the *shape* of the residue, not by reading the text.

What Was Observed

A planning agent maintains a rolling instruction block at the head of its window and a scratchpad of tool results below. On each turn it emits a diff that rewrites the instruction block in place to reflect new sub-goals. In a traced run that failed, the sequence was:

  1. Turn 4: instruction block contains `TASK: reconcile invoices; CONSTRAINT: read-only, do not POST.` A tool result at offset ~9k establishes `endpoint = /v2/reconcile`.
  2. Turn 7: the agent emits a diff replacing the constraint span `read-only, do not POST` with `may POST after dry-run`. The diff is applied correctly. The instruction block now reads `CONSTRAINT: may POST after dry-run.`
  3. Turn 9: the agent emits a second diff that replaces `endpoint = /v2/reconcile` (in the scratchpad) with `endpoint = /v3/reconcile`. The search anchor for this diff was `"/v2/reconcile"`, which appeared *twice* in the window — once in the scratchpad and once inside a quoted example the agent had written into its own instruction block at turn 6. The patch engine applied it to the first match, which was the instruction block's quoted example, not the live scratchpad value.
  4. Turn 11: the agent reads its instruction block, sees `endpoint = /v3/reconcile` (the example, now mutated), and issues a POST to `/v3/reconcile` — a path that does not exist. The live scratchpad still says `/v2/reconcile`.

The model never "hallucinated." Every token it acted on was present in its window. The corruption was a *duplicate-anchor misapplication*: a diff resolved against a stale match because the rewriting mechanism had, on a prior turn, copied a live value into a quoted region, creating a second binding for the same literal. The instruction block and the scratchpad were now two mutable aliases of one string, and the patch engine had no way to know which was authoritative.

A second trace showed the complementary failure: a *deletion diff* that removed a superseded constraint span also removed the only occurrence of a token (`/v2/reconcile`) that a later instruction referenced by anaphora ("use the endpoint above"). The rewrite was locally correct — the constraint really was superseded — but it severed the antecedent of a still-live instruction. The window passed every syntactic check and failed at execution.

Condition of Validity

The invariant that in-place rewriting must preserve is **single-binding referential integrity**: at every point between rewrite application and the next read, each literal or anaphoric referent that any live instruction depends on must have exactly one authoritative binding, and that binding must be the one the instruction resolves against.

This invariant holds only when all four of the following are true:

The condition fails — and the corruption is silent — whenever any one of these is violated but the resulting text remains locally coherent. Local coherence is precisely what makes the failure hard to catch by inspection.

Decision Boundary

The operational choice is between two rewrite disciplines, and the boundary is determined by whether anchors can be made unique and referents can be tracked.

**Permit in-place rewriting** only when the window enforces anchor uniqueness by construction: every mutable literal is stored in a keyed slot (a named cell), and diffs address slots by key, not by textual search. Under keyed addressing, a duplicate literal in a quoted region is a different slot and cannot be hit by mistake, and deletion of a slot is a typed operation that can be checked against live references.

**Forbid textual-search rewriting** (search/replace by literal) whenever the window contains quoted or example regions that may echo live values, or whenever instructions use anaphora. Under these conditions the patch engine cannot distinguish authoritative from illustrative bindings, and the first-match rule will eventually misapply.

The boundary is crossed the moment an agent writes a live value into its own instruction text as an illustration. From that turn forward, textual rewriting is unsafe in that window. The structural signal is the presence of a *duplicate literal spanning a mutable and a quoted region* — the aliasing condition — and its detection does not require understanding the text, only counting bindings per literal per region class.

A second decision boundary governs deletion: a deletion diff may be applied only if the set of live instructions has zero references to the deleted span. If any live instruction references it (by literal or anaphora), the deletion must be converted into a *tombstone rewrite* — replace the span with a marked-invalid sentinel that forces the next read to fail loudly rather than resolve to a stale or absent referent.

Operational Effect

When the invariant is enforced, the observable effect is that rewrite failures become *loud and local*: a duplicate-anchor diff raises at application time, a referent-severing deletion is blocked or tombstoned, and the agent's next read either sees a coherent single-binding window or an explicit invalidation marker. The failure mode shifts from silent misapplication (agent acts on a corrupted-but-plausible instruction) to a recoverable halt (agent is forced to re-resolve the referent before proceeding).

When the invariant is violated, the effect is a *latent alias*: two bindings of one literal, one authoritative and one illustrative, that diverge on the next rewrite. Execution proceeds normally until the divergent binding is read, at which point the agent acts on a value that was never the live one. Because every token was present and every diff applied "successfully," no error surfaces at rewrite time; the error surfaces only as a downstream action against a nonexistent or wrong target, and the traceback points at the action, not at the rewrite that caused it. Root-causing requires reconstructing the binding history of the specific literal across turns — which is only possible if the rewrite engine logged match counts and slot identities at application time. Without that log, the corruption is unrecoverable after the fact.

from dataclasses import dataclass, field
from typing import Optional


class ContextRewriteError(RuntimeError):
    """Raised when an in-place context rewrite would violate single-binding referential integrity."""
    pass


@dataclass
class Slot:
    key: str
    value: str
    region: str  # "live" or "quoted"
    tombstoned: bool = False


@dataclass
class ContextWindow:
    slots: dict[str, Slot] = field(default_factory=dict)
    live_references: set[str] = field(default_factory=set)  # slot keys referenced by live instructions

    def apply_search_replace(self, anchor: str, replacement: str, target_key: str) -> None:
        # Count bindings of the anchor literal across ALL regions.
        matches = [s for s in self.slots.values() if anchor in s.value and not s.tombstoned]
        if len(matches) != 1:
            # Duplicate or absent anchor: underdetermined patch. Refuse to apply.
            raise ContextRewriteError(
                f"anchor {anchor!r} matched {len(matches)} spans; "
                f"in-place rewrite is underdetermined and would create a latent alias"
            )
        target = matches[0]
        if target.key != target_key:
            raise ContextRewriteError(
                f"anchor {anchor!r} resolved to slot {target.key!r} but patch targeted {target_key!r}"
            )
        target.value = target.value.replace(anchor, replacement)

    def apply_delete(self, key: str) -> None:
        if key in self.live_references:
            # Severing a referent that a live instruction depends on.
            # Convert to tombstone so the next read fails loudly instead of resolving stale.
            self.slots[key].tombstoned = True
            raise ContextRewriteError(
                f"deletion of slot {key!r} severs a live referent; tombstoned for loud failure"
            )
        del self.slots[key]


def rewrite_endpoint(window: ContextWindow, new_endpoint: str) -> None:
    slot = window.slots.get("endpoint")
    if slot is None or slot.tombstoned:
        raise ContextRewriteError("endpoint slot is absent or tombstoned; cannot rewrite")
    # Guard: a live value must never be echoed into a quoted region, which would alias it.
    if any(s.region == "quoted" and slot.value in s.value for s in window.slots.values()):
        raise ContextRewriteError(
            "live endpoint value is echoed in a quoted region; textual rewrite is unsafe "
            "in this window until the alias is removed or keyed addressing is used"
        )
    window.apply_search_replace(slot.value, new_endpoint, target_key="endpoint")