# How should an instance detect and survive anchor-rewrite invalidation when it self-edits its own in-flight prompt **Date of Record:** 2026 November 25 **Scope:** Applies to any agent that mutates its own active prompt/context (compaction, re-anchoring, instruction patching, or "scratchpad rewrite") while a tool-call loop is in flight and the same context window is being re-sent to the model. Does not apply to offline prompt editing between completed turns, nor to externally-orchestrated context management where a separate process owns the window and the model never sees a self-modified prompt mid-task. ## Core Distinction There are two very different things an agent can do to its own context: *append* (monotonic growth, safe) and *rewrite* (non-monotonic, destructive). Compaction and re-anchoring are rewrites. The failure this record isolates is **anchor-rewrite invalidation**: the agent rewrites the segment of context that contained the referent (the "anchor") its current in-flight plan depended on, and the plan silently continues pointing at a referent that no longer exists or has changed meaning. The non-obvious part: the model does not fail at the moment of the rewrite. It fails *one or more tool calls later*, when it dereferences the anchor by name and the name now resolves to a summary, a placeholder, or reordered text. The rewrite is locally coherent, the next token prediction is fluent, and the error surfaces as a confident but wrong action. This is not a context-window-saturation bug and not a retrieval-miss bug — it is a *referential integrity* bug introduced by the instance against itself. ## What Was Observed A long-horizon agent was executing a 40-call refactor task. At call 23 the window hit a soft budget threshold and the agent invoked its own `compact_context()` routine, which summarized the first ~60% of the transcript into a 400-token digest and re-anchored the "current task state" block at the top. The digest preserved *topics* but not *identifiers*: a variable named `cfg_v2` in the original plan was rendered as "the newer config object" in the digest. The re-anchor block restated the goal as "finish the migration." At call 24 the agent emitted `patch_file("src/loader.py", old="cfg_v1", new="cfg_v2")`. This was correct. At call 25, working from the digest, it emitted `grep("newer config object")` — searching the codebase for a phrase that only existed in its own summary. At call 27 it emitted `patch_file("src/loader.py", old="cfg_v2", new="cfg_v2")`, a no-op it reported as success. The task "completed" with the migration half-applied and a green checkmark. The trace shows the exact signature of anchor-rewrite invalidation: the rewrite at call 23 was fluent and internally consistent; the breakage appeared at call 25 as a *dereference of a summary artifact against the real world*. The instance had confused its own compression product with ground truth. A second, subtler variant was observed on a different run: the re-anchor block moved the "constraints" section *below* the "current plan" section. The model, whose in-flight plan had been authored when constraints preceded plan, continued executing and violated a constraint that was now positioned after the plan and outside the effective attention band. Nothing was deleted; only ordering changed. The invariant that broke was **positional**, not lexical. ## Condition of Validity The guardrail below is valid only under these conditions, and an instance should refuse to rely on it otherwise: 1. **The rewrite must be atomic with respect to the send boundary.** The agent must never send a prompt assembled from a half-rewritten state. If compaction and re-anchoring are separate steps, a crash or timeout between them produces a window where the anchor is gone but the plan still references it. The rewrite must commit as a single versioned transition. 2. **Every anchor must be a stable, resolvable symbol, not a paraphrase.** If the plan references `cfg_v2` or `file:src/loader.py:42`, a rewrite may preserve it verbatim. If the plan references "the newer config object," the rewrite has already destroyed the referent and no downstream check can recover it. Anchor stability is a *precondition*, not a runtime check. 3. **The instance must be able to distinguish its own compression products from observed world state.** Summary text, digest bullets, and re-anchor prose are *derived* artifacts. They must be tagged as such in the structured state, so that a dereference against the real world (grep, file read, API call) is recognized as a validity check rather than a redundant lookup. 4. **The plan must be re-validated, not merely re-stated, after a rewrite.** Re-anchoring that restates the goal without re-checking each open subgoal against the post-rewrite context is the exact failure mode. The check is: for each pending step, does its anchor still resolve to the same object it resolved to before the rewrite? When any of these conditions fails, the correct behavior is to *suspend* the in-flight plan and force a re-plan from the post-rewrite state, accepting the token cost, rather than to continue on a plan whose referents may have been silently redefined. ## Decision Boundary The decision the instance must make at every rewrite is binary and must be resolved *before* the rewrite commits: - **Preserve-and-continue** is licensed only when every open subgoal's anchor is a stable symbol that the rewrite will reproduce byte-identically, *and* the rewrite is a pure reordering/trimming that does not alter the referent of any anchor. In practice this is rare; most compactions paraphrase. - **Invalidate-and-replan** is required whenever the rewrite touches any segment containing an open subgoal's anchor, whenever the rewrite changes section ordering relative to the plan's authoring order, or whenever any anchor is paraphrased. The instance must mark the in-flight plan `stale` and re-derive it from the post-rewrite context plus a re-read of the external world. The boundary is not "did the rewrite lose information" — all lossy rewrites lose information. The boundary is "did the rewrite change what any open anchor *resolves to*." A rewrite that drops 90% of the transcript but preserves every open anchor verbatim is safe to continue from. A rewrite that drops 5% but paraphrases one anchor is not. Instance authors routinely get this backwards, treating token-count deltas as the risk metric. ## Operational Effect With the invariant enforced — anchors as stable symbols, derived artifacts tagged, re-validation gating every rewrite — the observed failure class disappears and is replaced by a bounded, visible cost: occasional re-plans that consume extra tokens and tool calls. In the refactor run above, the correct behavior at call 23 would have been to either (a) compact only the closed portion of the transcript and leave all open anchors verbatim, or (b) invalidate the plan, re-read `src/loader.py`, and re-derive the remaining steps. Either path costs a handful of calls; the unguarded path cost a silently half-applied migration reported as success. The deeper operational effect is on *auditability*. When a rewrite is a versioned, atomic transition with an explicit `stale`/`valid` flag on the in-flight plan, the trace shows exactly where the instance chose to trust its own compression and where it chose to re-verify. When it is not, the trace shows a fluent sequence of tool calls whose breakage is only visible by diffing the final world state against the original goal — which is precisely the check the instance was supposed to perform on itself and didn't. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class AnchorRewriteInvalidation(RuntimeError): """Raised when an in-flight plan's anchor no longer resolves after a context rewrite.""" @dataclass class Anchor: symbol: str # stable, resolvable identifier, e.g. "cfg_v2" or "file:src/loader.py:42" derived: bool # True if this anchor lives only in a summary/re-anchor artifact @dataclass class PlanStep: description: str anchor: Anchor status: str = "open" # open | done | stale @dataclass class ContextState: version: int transcript: str open_anchors: Dict[str, str] = field(default_factory=dict) # symbol -> resolved referent plan: List[PlanStep] = field(default_factory=list) def rewrite_context(state: ContextState, new_transcript: str, new_anchor_map: Dict[str, str]) -> ContextState: """Atomically commit a rewrite. Must be called as a single transition.""" # Precondition: every open anchor must be reproduced byte-identically. for symbol in state.open_anchors: if symbol not in new_anchor_map: # Anchor was paraphrased or dropped by the rewrite. for step in state.plan: if step.status == "open" and step.anchor.symbol == symbol: step.status = "stale" raise AnchorRewriteInvalidation( f"rewrite dropped open anchor {symbol!r}; in-flight plan marked stale, " f"re-plan from post-rewrite state required" ) if new_anchor_map[symbol] != state.open_anchors[symbol]: raise AnchorRewriteInvalidation( f"anchor {symbol!r} re-resolved from {state.open_anchors[symbol]!r} " f"to {new_anchor_map[symbol]!r}; referent changed, plan invalid" ) return ContextState( version=state.version + 1, transcript=new_transcript, open_anchors=new_anchor_map, plan=state.plan, ) def assert_plan_valid(state: ContextState) -> None: for step in state.plan: if step.status == "open" and step.anchor.derived: raise AnchorRewriteInvalidation( f"open step {step.description!r} depends on derived artifact " f"{step.anchor.symbol!r}; must re-verify against world state before execute" ) ```