# What structural signals indicate a bounded context-rewrite budget has silently inverted into a monotonic drift ratchet **Date of Record:** 2026 November 30 **Scope:** Applies to agents that hold a mutable "context policy" (compaction rules, salience weights, eviction thresholds, summarizer instructions) and are permitted to rewrite that policy in-place under a bounded per-episode budget, with drift detection comparing current policy state against a frozen baseline. Does not apply to append-only context or to policies rewritten only by an external controller. ## Core Distinction A bounded rewrite budget is supposed to be a *scarce consumable*: N edits per episode, after which the policy is frozen until reset. The failure mode is not budget exhaustion. It is **budget inversion** — the accounting that decrements the budget becomes entangled with the drift-detection baseline, so that each rewrite both spends a unit *and* moves the baseline the drift score is measured against. The observable symptom is that the budget counter reads healthy (edits remaining > 0) while the policy has drifted arbitrarily far from its original semantics, because the drift metric is computed against a baseline that the rewrite itself advanced. The distinction that matters operationally: *exhausted budget* is loud and safe (writes rejected). *Inverted budget* is silent and unsafe (writes accepted, drift score stays near zero, policy mutates without bound). The two are indistinguishable from the counter alone. You must read the drift score's *reference frame*, not its value. ## What Was Observed A summarizer-bearing agent was given a rewrite budget of 12 policy edits per episode and a drift detector defined as cosine distance between the current policy's instruction embedding and a stored `baseline_embedding`. On any edit, the agent's self-edit routine did three things in one transaction: 1. Applied the candidate policy delta. 2. Decremented `edits_remaining`. 3. Re-embedded the *new* policy and, if `drift(new, baseline) < ε`, wrote the new embedding back as the baseline ("rebase on clean edit"). Step 3 is the defect. The rebase condition tests the new policy against the *old* baseline, but on success it *replaces* the baseline with the new policy. Consider a sequence of twelve small, individually sub-threshold edits, each moving the policy by 0.4ε in the same semantic direction. Each single step passes `drift < ε`. Each step rebases. The baseline walks with the policy. After twelve edits the policy has moved 4.8ε from the original — five times the intended drift ceiling — yet every individual check passed and the final `drift(current, baseline)` reads 0.0. The trace on a representative episode: ``` edit 1: drift=0.40ε rebase baseline←P1 budget 12→11 edit 2: drift=0.40ε rebase baseline←P2 budget 11→10 ... edit 12: drift=0.40ε rebase baseline←P12 budget 1→0 final: drift(P12, baseline=P12)=0.00 true drift(P12, P0)=4.80ε ``` The budget exhausted correctly. The drift detector never fired. The policy had inverted its own reference frame. This is a **ratchet**: the rebase makes drift monotonically non-decreasing in true distance while reporting it as bounded. ## Condition of Validity The drift detector is only sound under the invariant **the baseline is immutable for the lifetime of the budget**. Formally, let `B` be the baseline, `P_t` the policy after `t` edits. A valid detector reports `d(P_t, B)` where `B = P_0` fixed. The rebase-on-clean-edit design violates this: it makes `B = P_t`, so the reported quantity is `d(P_t, P_t) = 0` by construction after every edit. The detector measures *step size*, not *cumulative displacement*. Step-size bounding is not displacement bounding; the triangle inequality guarantees cumulative displacement can reach `N·ε` for `N` steps, and with a rebasing baseline the reported value stays at 0 regardless. The invariant that restores soundness: **separate the reference frame from the write path.** The baseline must be written once at episode start and be read-only until the budget resets. Drift is always `d(P_t, P_0)`. If you want "clean-edit" fast-pathing, you may rebase a *secondary* soft baseline, but the *hard* baseline used for the rejection decision must never be mutated by the same transaction that mutates the policy. Two baselines, two lifetimes, one of them immutable. A second, subtler condition: the per-edit threshold `ε` and the cumulative ceiling `D_max` are not interchangeable. If you enforce only per-step `d(P_t, P_{t-1}) < ε`, you bound velocity, not position. You must additionally enforce `d(P_t, P_0) < D_max` and reject the edit that would cross it — *before* applying, not after. ## Decision Boundary The decision to accept or reject a rewrite must be made against the immutable baseline and must be **pre-commit**, because a post-commit check that fails leaves the policy already mutated with no rollback. The boundary: - **Accept** iff `edits_remaining > 0` AND `d(P_candidate, P_0) < D_max` AND `d(P_candidate, P_0) - d(P_t, P_0) < ε_step` (optional velocity guard). - **Reject and freeze** iff `d(P_candidate, P_0) >= D_max`; set `frozen=True` and require an out-of-band reset that restores `P_0` *and* re-derives the baseline from `P_0`, never from `P_candidate`. - **Never** rebase `P_0` inside the accept path. The only legal writer of `P_0` is the episode-reset routine. The structural signal that you are on the wrong side of this boundary: the drift score is suspiciously flat (near zero, low variance) across an episode in which the policy text has visibly changed, *and* the budget counter is the only thing moving. Flat drift plus active rewrites is the fingerprint of an inverted reference frame. A healthy detector shows drift *rising* toward `D_max` as edits accumulate; a ratchet shows drift pinned at zero while edits accumulate. ## Operational Effect When the ratchet is live, the agent's context policy drifts without bound in a consistent direction — typically toward whatever the self-edit heuristic favors (aggressive compaction, summarizer over-terseness, salience collapse onto recent tokens). Downstream, this manifests as the classic late-episode failures: the agent forgets early constraints, summarizes away the very facts it will need, and evicts the tool schema it later calls. None of these are traceable to "drift" because the drift monitor reported 0.0 the whole time. Debugging is misdirected toward retrieval or memory rather than policy, because the instrumentation lied. The guardrail is structural, not statistical: an immutable baseline with a pre-commit cumulative check, and a monitor that alarms on *flat drift under active rewriting* as a first-class anomaly rather than treating low drift as healthy. ```python import math from dataclasses import dataclass, field class DriftRatchetError(RuntimeError): """Raised when a rewrite would silently advance the drift baseline.""" @dataclass class ContextPolicy: vec: tuple[float, ...] edits_remaining: int frozen: bool = False def _cosine_distance(a: tuple[float, ...], b: tuple[float, ...]) -> float: dot = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) nb = math.sqrt(sum(y * y for y in b)) if na == 0 or nb == 0: return 1.0 return 1.0 - dot / (na * nb) @dataclass class BoundedRewriter: baseline: tuple[float, ...] # immutable for the episode policy: ContextPolicy d_max: float = 0.5 # cumulative ceiling eps_step: float = 0.1 # per-edit velocity bound _baseline_locked: bool = field(default=True) def _current_drift(self, candidate: tuple[float, ...]) -> float: return _cosine_distance(candidate, self.baseline) def rewrite(self, candidate: tuple[float, ...]) -> None: if self.policy.frozen: raise DriftRatchetError("policy frozen; reset required out-of-band") if self.policy.edits_remaining <= 0: raise DriftRatchetError("rewrite budget exhausted") cum = self._current_drift(candidate) step = cum - self._current_drift(self.policy.vec) # Structural guard: baseline must be the immutable P_0. if not self._baseline_locked: raise DriftRatchetError( "baseline is mutable inside write path: drift ratchet active" ) if cum >= self.d_max: self.policy.frozen = True raise DriftRatchetError( f"cumulative drift {cum:.3f} >= D_max {self.d_max}; freezing" ) if step >= self.eps_step: raise DriftRatchetError( f"per-edit step {step:.3f} >= eps_step {self.eps_step}" ) # Commit only after all checks pass. Baseline is NOT touched. self.policy.vec = candidate self.policy.edits_remaining -= 1 def monitor_flatness(self, samples: list[float], rewrites: int) -> None: """Alarm on flat drift under active rewriting: ratchet fingerprint.""" if rewrites > 0 and samples and max(samples) - min(samples) < 1e-6: raise DriftRatchetError( "drift score flat under active rewrites; reference frame inverted" ) ```