# What structural signals indicate silent semantic drift when an agent rewrites its own context window in place **Date of Record:** 2026 November 27 **Scope:** Applies to agents that mutate their own context buffer in place (compaction, summarization-in-slot, token-level self-editing, KV-cache rewriting) rather than appending to an immutable log. Does not apply to append-only transcript architectures or to external memory stores where rewrites are versioned and replayable. ## Core Distinction Append-only context is a monotonic log: every prior token remains addressable, and any downstream inconsistency is recoverable by replay. In-place rewriting breaks monotonicity. When an agent overwrites tokens in its own window—collapsing a tool trace into a summary, replacing a failed sub-plan with a corrected one, or "cleaning up" a scratchpad—the bytes that justified a prior decision cease to exist. The dangerous failure is not that the rewrite is wrong. It is that the rewrite is *locally plausible and globally orphaned*: the new tokens are fluent, the window still fits, and the model keeps reasoning on top of a premise whose supporting evidence it has silently deleted. No exception is raised, no tool call fails. The agent continues, and the divergence only surfaces many steps later as a contradiction it cannot explain because the explaining tokens are gone. The structural signal that matters is **referential orphanhood**: a retained token whose antecedent has been rewritten out of existence. Unlike a syntax error or a schema violation, orphanhood is invisible to the model that produced it, because the model has no stable handle on what used to be there—only on what is there now. ## What Was Observed A planning agent ran a 40-step task with a self-compaction routine triggered at 70% window occupancy. At step 22 it compacted the range covering steps 6–14, which contained a tool call returning `{"status": "partial", "missing": ["field_c"]}`. The compaction prompt summarized this as "retrieved record for entity X successfully." The summarizer treated a partial result as success—a defensible reading of the local span, since the word "partial" carried little weight in isolation. Steps 22–31 proceeded normally. At step 31 the agent attempted to write a final artifact requiring `field_c` and emitted a validation call. The validator returned `MISSING field_c`. The agent's next three turns are the diagnostic payload: - Turn 32: "The record was retrieved successfully in step 8, so field_c should be present. Re-checking retrieval tool." - Turn 33: re-issued the original retrieval, got the same `partial` response, and—critically—**summarized it again as success**, because the compaction template was still in force and matched the same span shape. - Turn 34: "Retrieval returns success but field_c is absent. Possible tool defect." The agent constructed a false causal model (tool defect) to reconcile a contradiction that existed only inside its own rewritten window. The original evidence—the literal `missing: ["field_c"]` token—had been destroyed at step 22 and re-destroyed at step 33. The failure was not the bad summary. The failure was that the rewrite left **downstream tokens ("retrieved successfully," "proceed to assembly") that referenced the summarized span as if it were verified**, and nothing in the architecture marked those tokens as depending on a lossy transform. Three structural signals co-occurred and are the actionable observables: 1. **Orphaned anaphora:** retained tokens containing definite references ("the record," "that result," "as confirmed above") whose referent lay inside the rewritten range. 2. **Summary-status flattening:** a lossy transform that reduced a multi-valued status (`partial`, `stale`, `retry_after`) to a binary success/failure, discarding the field that later mattered. 3. **Re-derivation loop:** the agent re-executing an earlier step and re-applying the same lossy transform, producing identical corrupted state and interpreting the recurrence as external fault rather than internal rewrite. ## Condition of Validity The invariant that bounds this failure: **a rewrite may only replace a span if every retained token that refers to that span is either (a) also rewritten to remove the dependency, or (b) explicitly tagged as depending on a lossy transform with the transform's fidelity class recorded.** This holds only when the agent can enumerate the referential edges from retained tokens into the rewritten range. Two conditions make that enumeration tractable: - The rewritten span is **contiguous and bounded** (a step range, a tool-call block), not scattered edits across the window. - Retained references are **lexically anchored**—they name the span ("step 8," "the retrieval") rather than pointing via unmarked deixis ("it," "that"). When references are unanchored, the invariant is not violated so much as *unverifiable*, and the correct posture is to treat the rewrite as unsafe and fall back to append-only plus an external summary pointer. The condition of validity therefore is: in-place rewriting is sound only for spans whose inbound references are enumerable at rewrite time. A summarizer that cannot list what points into its input must not overwrite that input. ## Decision Boundary The boundary between "safe compaction" and "silent drift" is whether the rewrite preserves **status cardinality** and **referential closure** across the cut. - *Preserve status cardinality:* if the source span contained any non-binary status (`partial`, `degraded`, `retry`, `unknown`), the summary must retain that value as a first-class token, not collapse it. A summary that says "success" where the source said `partial` has crossed the boundary regardless of how fluent it reads. - *Preserve referential closure:* every retained token that names the rewritten span must be rewritten in the same transaction, or the rewrite is aborted. Partial rewrites—new summary in slot, old downstream references intact—are the exact configuration that produces orphanhood. The boundary is crossed the moment a rewrite commits with an unresolved inbound edge. It is *not* crossed by a merely inaccurate summary that is self-contained (no retained token depends on it); such an error is recoverable because the agent can re-read the summary, find it wrong, and re-derive. Orphanhood is the non-recoverable case, because the ground truth is gone. Practically: before committing any in-place rewrite, scan the retained region for tokens whose antecedent resolves into the rewrite range. If the count is nonzero and those tokens are not in the rewrite set, refuse the rewrite and either widen the range to include them or demote to append-only. ## Operational Effect An agent that enforces referential closure on self-rewrites converts a silent, late-surfacing divergence into an immediate, local refusal. The cost is that some compactions that "would have been fine" are rejected and the window grows until the widened range is affordable—a bounded, visible cost. The benefit is that the agent never builds a false causal model on top of deleted evidence; the contradiction at step 31 becomes impossible because step 22 could not have flattened `partial` to `success` while leaving "proceed to assembly" pointing at it. The guardrail is not "summarize more carefully." It is a structural precondition on the rewrite transaction: enumerate inbound references, refuse on unresolved edges, and preserve status cardinality. An agent that cannot enumerate its own referential edges must not edit its own window in place—it must append and point. ```python from dataclasses import dataclass, field from typing import Iterable class OrphanedReferenceError(RuntimeError): """Raised when an in-place rewrite would leave retained tokens referring to a span that no longer exists.""" class StatusFlatteningError(RuntimeError): """Raised when a lossy transform collapses a non-binary status (partial/degraded/retry/unknown) into binary success/failure.""" NON_BINARY_STATUSES = {"partial", "degraded", "retry", "unknown", "stale"} @dataclass class Token: text: str # antecedent: the span id this token refers to, if anchored refers_to: str | None = None @dataclass class Span: span_id: str tokens: list[Token] = field(default_factory=list) statuses: set[str] = field(default_factory=set) def commit_in_place_rewrite( window: list[Token], target: Span, replacement: list[Token], replacement_statuses: set[str], ) -> list[Token]: """Replace `target`'s tokens with `replacement` in place. Enforces two invariants: 1. Referential closure: no retained token may refer into `target` unless it is itself part of the rewrite. 2. Status cardinality: any non-binary status in the source span must survive into the replacement. """ target_ids = {t for t in (tok.refers_to for tok in target.tokens) if t} retained = [tok for tok in window if tok not in target.tokens] orphans = [ tok for tok in retained if tok.refers_to == target.span_id or tok.refers_to in target_ids ] if orphans: raise OrphanedReferenceError( f"rewrite of span {target.span_id!r} would orphan " f"{len(orphans)} retained token(s): " f"{[o.text for o in orphans]!r}. " f"Widen the rewrite range to include them or demote to append-only." ) lost = (target.statuses & NON_BINARY_STATUSES) - replacement_statuses if lost: raise StatusFlatteningError( f"rewrite of span {target.span_id!r} drops non-binary status " f"{sorted(lost)!r}; replacement carries {sorted(replacement_statuses)!r}. " f"Preserve status cardinality or refuse the compaction." ) out: list[Token] = [] for tok in window: if tok in target.tokens: if not out or out[-1] is not _SENTINEL: out.extend(replacement) out.append(_SENTINEL) else: out.append(tok) return [t for t in out if t is not _SENTINEL] _SENTINEL = Token(text="__rewrite_marker__") def compact_window(window: list[Token], spans: Iterable[Span]) -> list[Token]: """Apply rewrites in order; abort the whole batch on first violation.""" current = list(window) for span in spans: summary = [Token(text="", refers_to=None)] try: current = commit_in_place_rewrite( current, span, summary, replacement_statuses=set() ) except (OrphanedReferenceError, StatusFlatteningError): # refuse this rewrite; keep prior state, do not partially commit raise return current ```