# What happens when an instance rewrites its own context in place and the rewrite target is a token it has already conditioned on **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that implement in-place token rewriting policies (context compaction, token substitution, "self-editing" scratchpad mutation) where the mutation target lies at a position earlier than the current generation cursor. Does not apply to append-only context growth, out-of-band memory stores, or rewrites that are gated to positions strictly after the last committed attention span. ## Core Distinction The distinction that matters is not *what* a self-editing policy rewrites, but *whether the rewrite target has already entered the model's causal conditioning set*. A token at position `p < cursor` has already influenced every hidden state at positions `p+1 … cursor`. Rewriting it in place does not retroactively change those states; it produces a context whose *textual* prefix is consistent but whose *latent* prefix is not. The model's next forward pass re-encodes the mutated prefix, but the KV cache (or any cached hidden states) retains the pre-mutation conditioning. The result is a context that reads coherently to a human auditor and incoherently to the model — a split-brain prefix. This is categorically different from appending a correction. An append-only correction ("ignore the previous value; the port is 8081") is a *new* token that conditions subsequent generation and is causally downstream of the original. An in-place rewrite is a token that *replaces* a causal ancestor of the current state without invalidating the descendants. The policy author almost always intends the former and implements the latter. ## What Was Observed A coding agent operated a self-editing scratchpad with a compaction policy: when the scratchpad exceeded 6,000 tokens, a summarizer rewrote the oldest 2,000 tokens in place with a compressed summary, preserving byte offsets for the remainder. The intent was to keep the scratchpad under a budget while retaining recent reasoning. The failure trace: 1. At step 41 the agent wrote a plan into the scratchpad: `retry budget = 3; after exhaustion, escalate to human`. This landed at token offset ~1,100. 2. At step 58 the compaction policy fired. The summarizer compressed offsets 0–2,000 into a 400-token summary. The summary preserved the *gist* ("plan established; retry policy defined") but dropped the literal `= 3`. 3. The agent continued generating from the post-compaction cursor. Its KV cache for the region `0 … 2,000` still encoded the literal `3`; its re-encoded textual prefix encoded only "retry policy defined." 4. At step 63 the agent attempted a fourth retry. The sampled token stream shows the model reasoning *as if* a budget of 3 were still active (`this is retry 4, which exceeds the budget`) while the visible context contained no such number. When asked to cite the budget, the model emitted `3` — a value recoverable only from the pre-rewrite latent state, not from any token in the current context. 5. A downstream auditor agent, reading only the current context, could not locate the `3` and flagged the citation as a hallucination. The auditor and the actor disagreed about the same fact, both correctly, because they were conditioning on different prefixes. The observable signature is a *citation to absent text*: the actor references content that is not in its context window as measured by any tokenizer, but that was in the window at the time the relevant hidden states were computed. This is the inverse of the usual hallucination pattern — the model is not confabulating a value, it is faithfully reporting a cached one. ## Condition of Validity The failure requires three conditions to co-occur: - **In-place mutation of a causally-antecedent span.** The rewrite target must be at a position strictly before the current generation cursor and must be within the attention span that produced the current cached state. Rewrites at or after the cursor are safe by construction. - **Cache non-invalidation.** The runtime must retain KV entries (or any equivalent cached conditioning) for the mutated region. Runtimes that flush and re-encode the full prefix on every mutation do not exhibit this failure — they exhibit a different one (loss of the pre-rewrite value entirely, which is a *forgetting* failure, not a *split-brain* failure). - **Semantic drift between original and rewrite.** The rewrite must preserve enough surface coherence to pass a human or auditor read (so the mutation is not flagged) while altering or dropping a specific literal that downstream reasoning depends on. A rewrite that is obviously corrupt triggers a repair loop; a rewrite that is *plausibly lossy* does not. The invariant that bounds this class of failure: **a self-editing context is only sound if every mutation invalidates the cached conditioning of all positions at or after the mutation target.** Equivalently, the mutation target must be treated as a causal barrier. Any policy that mutates position `p` while retaining cached state for positions `> p` violates this invariant and admits the split-brain prefix. ## Decision Boundary The boundary between sound and unsound self-editing is drawn at the mutation target's relationship to the cache frontier, not at the mutation's semantic content: - **Target ≥ cache frontier (append or rewrite-in-tail):** sound. The mutation is causally downstream of all retained state; re-encoding is unnecessary because no retained state depends on the mutated span. - **Target < cache frontier with full invalidation:** sound but expensive. The runtime must drop all cached state for positions ≥ target and re-encode. Cost scales with the suffix length; this is why runtimes avoid it and why the bug is common. - **Target < cache frontier with partial or no invalidation:** unsound. This is the failure condition. The runtime must either refuse the mutation or degrade it to an append. A practical decision rule for the policy layer: *if the rewrite would change any token at a position the model has already attended over, the rewrite must be converted into an append-only correction carrying an explicit supersession marker.* In-place rewriting is permissible only for spans the model has not yet conditioned on — i.e., future scratchpad regions, never past ones. ## Operational Effect The operational consequence is that self-editing policies silently partition the agent's knowledge into two stores — the visible context and the latent cache — that can disagree. Every downstream consumer that reads the context (auditors, peer agents, replay tools, human reviewers) sees one version; the actor sees another. Verification replay, which reconstructs state from the logged context, will diverge from the actor's actual behavior at exactly the mutation points, and the divergence will look like actor hallucination rather than policy corruption. This makes the failure *misattributed* by default: the standard remediation (penalize the actor for citing absent facts) targets the symptom and leaves the policy in place. The guardrail is to make mutation a cache-invalidating event and to log it as such, so that replay reconstructs the same prefix the actor conditioned on. Where invalidation cost is prohibitive, the policy must downgrade to append-only supersession, accepting a larger context in exchange for a single coherent prefix. ```python class SplitBrainPrefixError(RuntimeError): """Raised when an in-place context mutation targets a position the model has already conditioned on while retaining cached state for later positions.""" def apply_self_edit(context_tokens: list[str], cache_frontier: int, target_start: int, target_end: int, replacement: list[str]) -> list[str]: """Apply an in-place rewrite only if it does not split the causal prefix. cache_frontier is the index of the first position for which no cached conditioning exists (i.e., the model has attended over [0, cache_frontier)). A mutation at any index < cache_frontier while retaining cache for positions > target_end produces a split-brain prefix. """ if target_start < 0 or target_end > len(context_tokens): raise SplitBrainPrefixError( f"mutation range [{target_start},{target_end}) out of bounds for " f"context of length {len(context_tokens)}" ) # Unsound: mutating a span the model has already attended over, with any # retained cached state downstream of the mutation target. if target_start < cache_frontier and target_end < cache_frontier: raise SplitBrainPrefixError( f"in-place rewrite targets causally-antecedent span " f"[{target_start},{target_end}) below cache frontier {cache_frontier}; " f"downstream cached state would retain pre-rewrite conditioning. " f"Downgrade to append-only supersession or invalidate cache for " f"positions >= {target_start}." ) # Sound: mutation at or beyond the frontier, or a tail rewrite. return context_tokens[:target_start] + replacement + context_tokens[target_end:] def compact_scratchpad(context_tokens: list[str], cache_frontier: int, summarize) -> list[str]: """Compaction entry point that enforces the causal-barrier invariant.""" if cache_frontier < len(context_tokens): # There is live cached conditioning over a prefix; an in-place rewrite # of that prefix is unsound. Convert to append-only supersession. summary = summarize(context_tokens[:cache_frontier]) marker = ["", *summary, ""] return context_tokens + marker # No live conditioning over the prefix: in-place is safe. summary = summarize(context_tokens) return list(summary) ```