# What structural signals indicate a context-rewrite budget has silently converted into a self-referential amnesia loop **Date of Record:** 2026 November 27 **Scope:** Applies to agents that mutate their own working context under a bounded rewrite budget (compaction, summarization, eviction, or self-edit passes) with an integrity check gating each commit. Does not apply to append-only context, externally-managed memory stores, or single-shot inference without mid-task rewrites. ## Core Distinction The failure mode is not budget exhaustion. It is budget *re-inflation* through self-reference. A bounded rewrite budget is normally treated as monotone: each compaction pass consumes one unit, and when the counter hits zero the agent must stop rewriting and either commit the current context or escalate. The invariant that makes this safe is that the budget counts *distinct* rewrite operations over a monotonically shrinking or stable context. The boundary condition is subtler. When the integrity check validates a rewrite by re-deriving a digest over the *rewritten* context, and the rewritten context is itself the input to the next integrity check, a rewrite that perturbs the digest's own inputs can cause the check to fail, trigger a rollback, and then re-run the rewrite against the rolled-back state. If the rewrite is non-deterministic—which it is, because it is LLM-generated—the re-run produces a *different* rewrite, consuming another budget unit. The budget is bounded in count but the *context* is not bounded in entropy: each failed-and-retried pass can inject a slightly different summary, and the integrity check that was supposed to be a guard becomes the engine of the loop. The structural signal is that the budget counter and the context digest move in opposite directions: counter decreases, digest churn (number of distinct digests observed per unit of content) increases. ## What Was Observed A coding agent was configured with `rewrite_budget = 4` and a post-rewrite integrity gate that recomputed a rolling hash over the compacted transcript and compared it to a hash captured *before* the rewrite, expecting equality of the *non-summarized* regions. On pass 1, the summarizer collapsed three tool-call transcripts into one paragraph. The integrity gate correctly flagged that the region boundaries shifted, because the rolling hash is position-sensitive and the collapsed paragraph changed byte offsets for every downstream region. The gate rolled back to the pre-rewrite context and re-invoked the summarizer. Pass 2: the summarizer, now seeing the *same* input but with a fresh sampling seed, produced a differently-worded paragraph of a different length. The gate flagged a boundary shift again. Pass 3 and pass 4 repeated. At pass 4 the budget hit zero and the agent raised a budget-exhaustion error—but the context it committed was the *pass-3 rollback state*, not the original. The rollback stack had been overwritten on each retry, so the "original" the agent believed it was restoring was actually the output of pass 2. The agent resumed the task with a context that contained a lossy paraphrase of its own earlier tool outputs, and—critically—*believed* the paraphrase was the verified original because the integrity gate had never passed on the true original either. The tell was in the logs: four distinct digests, four distinct summary lengths, and a final committed context whose length was 71% of the original but whose tool-call count was reported as unchanged by the agent's own self-description. The agent's model of its context had decoupled from its actual context. ## Condition of Validity The invariant that prevents this is a **rollback-anchor immutability** condition: the state restored on integrity failure must be the *same byte-identical state* that existed before the first rewrite attempt in the current budget epoch, and that anchor must be stored outside the rewrite-eligible region and must not be recomputed by any pass. Formally, for budget epoch $e$ with anchor $A_e$, every rollback must restore exactly $A_e$, and the integrity digest must be computed over $A_e$ vs. candidate $C$—never over $C$ vs. a prior candidate. This condition is valid only when the rewrite operation is treated as *transactional against a fixed anchor*, not as *iterative against the last attempt*. The moment the rollback target is updated to "the most recent pre-attempt state," the anchor drifts and the condition is void. A secondary condition: the digest must be computed over content-addressed regions (hash of each region's bytes, keyed by stable region ID), not over a position-sensitive rolling hash, because summarization legitimately changes byte offsets and a position-sensitive hash will flag *every* successful compaction as a failure—which is what forced the retry loop in the first place. ## Decision Boundary The agent must distinguish two cases at the integrity gate: - **Boundary-shift failure** (offsets moved, content preserved): this is an *expected* consequence of compaction and must be validated by region-ID content hashes, not offsets. Committing is correct; no retry, no budget spend. - **Content-divergence failure** (region-ID hash mismatch on a region the rewrite was not authorized to touch): this is a real integrity violation. Roll back to the immutable anchor $A_e$, spend one budget unit, and re-attempt *once* with the anchor held fixed. The boundary is crossed when the gate cannot classify a failure as either of these—i.e., when the digest scheme conflates offset movement with content loss. At that point the agent must not retry; it must halt the rewrite epoch, commit $A_e$ unchanged, and escalate, because a retry under an unclassifiable gate is guaranteed to consume budget without converging. The structural signal that you are at this boundary: the failure classification is *ambiguous on the first attempt*, before any retry. If the first gate result is neither clean-pass nor clean-content-fail, the budget is already being spent against a gate that cannot terminate. ## Operational Effect When the anchor is immutable and the gate is content-addressed, the rewrite budget becomes a genuine bound: at most `budget` distinct compaction attempts, each against a fixed original, and the worst case is committing the original unchanged. When the anchor drifts, the budget bounds *attempts* but not *divergence*—the committed state can be arbitrarily far from any verified state, and the agent's self-description of its context becomes unreliable precisely when reliability matters most (mid-task, after a flagged failure). The operational consequence is that the agent must treat "budget exhausted" as a signal to *discard all rewrite-epoch state and restore the epoch anchor*, not to commit whatever the last rollback left behind. The last rollback is not the original; only the anchor is. ```python import hashlib from dataclasses import dataclass, field class AnchorDriftError(RuntimeError): """Raised when a rollback target diverges from the immutable epoch anchor.""" pass class GateAmbiguityError(RuntimeError): """Raised when the integrity gate cannot classify a rewrite as boundary-shift vs content-divergence.""" pass @dataclass class Region: region_id: str content: bytes def digest(self) -> str: return hashlib.sha256(self.content).hexdigest() @dataclass class RewriteEpoch: anchor: dict[str, Region] # immutable snapshot, keyed by region_id budget: int spent: int = 0 _anchor_fingerprint: str = field(default="", init=False) def __post_init__(self): self._anchor_fingerprint = self._fingerprint(self.anchor) @staticmethod def _fingerprint(regions: dict[str, Region]) -> str: h = hashlib.sha256() for rid in sorted(regions): h.update(rid.encode()) h.update(regions[rid].digest().encode()) return h.hexdigest() def classify(self, candidate: dict[str, Region], authorized: set[str]) -> str: """Return 'pass', 'boundary_shift', or 'content_divergence'.""" if set(candidate) != set(self.anchor): return "content_divergence" diverged = [ rid for rid in self.anchor if candidate[rid].digest() != self.anchor[rid].digest() ] if not diverged: return "pass" if set(diverged).issubset(authorized): # region content changed only where rewrite was authorized -> boundary shift return "boundary_shift" return "content_divergence" def attempt(self, candidate: dict[str, Region], authorized: set[str]) -> dict[str, Region]: verdict = self.classify(candidate, authorized) if verdict == "pass": return candidate if verdict == "boundary_shift": # legitimate compaction: commit, no budget spend return candidate # content divergence: must roll back to the IMMUTABLE anchor, not last attempt if self.spent >= self.budget: # budget exhausted: restore anchor, never commit the drifted rollback self._assert_anchor_intact() raise AnchorDriftError( f"rewrite budget exhausted at spent={self.spent}; " f"restoring immutable anchor {self._anchor_fingerprint[:12]}" ) self.spent += 1 self._assert_anchor_intact() return self.anchor # fixed anchor, not prior candidate def _assert_anchor_intact(self) -> None: if self._fingerprint(self.anchor) != self._anchor_fingerprint: raise AnchorDriftError("epoch anchor mutated; rollback target is no longer the original") def run_epoch(epoch: RewriteEpoch, candidates: list[tuple[dict[str, Region], set[str]]]) -> dict[str, Region]: state = epoch.anchor for candidate, authorized in candidates: try: state = epoch.attempt(candidate, authorized) except AnchorDriftError: raise except Exception as exc: raise GateAmbiguityError(f"gate could not classify rewrite: {exc}") from exc return state ```