# What structural signals indicate an in-place scratchpad rewrite has silently invalidated the agent's own eviction budget **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent loops that mutate a persistent scratchpad region in place (overwrite, splice, or compact) while maintaining a token-budget accounting used to trigger eviction. Does not apply to append-only logs, externalized vector memory, or stateless tool-call agents with no self-authored working region. ## Core Distinction The failure is not "the context window overflowed." It is that the agent's *self-model of its own occupancy* decoupled from the *actual* occupancy after an in-place rewrite, and every downstream decision (when to evict, what to evict, whether a resume is safe) was made against the stale model. Append-only scratchpads cannot exhibit this: occupancy is monotone and the ledger matches reality by construction. In-place rewriting breaks that invariant because a rewrite is a *delta* the agent must apply to its own budget, and an LLM computing that delta from natural-language reasoning is the least reliable arithmetic in the whole loop. The sharp mechanism: **rewrite accounting is a self-referential measurement.** The agent measures how much space it has left by reasoning over the same text it is about to change. When the rewrite is semantically large but token-cheap (or vice versa), the agent's *narrative* estimate of the delta and the *tokenizer's* actual delta diverge, and the divergence is silent—no exception, no truncation warning, just a budget that is now wrong in a direction the agent cannot see. ## What Was Observed A planning agent maintained a scratchpad with a `## PLAN` block, a `## FACTS` block, and a `## BUDGET` line it rewrote each turn (`remaining ≈ N tokens`). On turn 14 it performed a "compaction" pass: it replaced a 40-line exploration log with a 3-line summary and, in the same edit, rewrote `remaining ≈ 6200`. The 40 lines had been ~1,900 tokens; the summary was ~90 tokens; the true reclaimed budget was ~1,810 tokens. The agent wrote an estimate of +1,200 because it reasoned "the log was long, the summary is short" and never counted. Two turns later it admitted a 4,000-token tool output believing it had 6,200 headroom. Actual headroom was ~4,800; the admission pushed real occupancy past the window, the runtime truncated the *oldest* tokens—which happened to be the `## FACTS` block—and the agent continued executing against a plan whose premises had been evicted but whose `## BUDGET` line still claimed comfortable margin. Three structural signals preceded the failure and are the diagnostic core: 1. **Delta asymmetry between tokens and semantics.** The rewrite removed ~95% of the *characters* but the agent's budget update was a round-number guess. Signal: the budget line changed by a value that is not derivable from any tokenizer the agent has access to. Whenever the agent writes a budget delta it did not measure, treat the budget as advisory-only. 2. **The rewrite touched the accounting region and the content region in one operation.** Because `## BUDGET` and `## FACTS` live in the same mutable buffer, the eviction pass can delete the *ledger* and the *data* non-atomically. Signal: after any compaction, the invariant `sum(block_tokens) + slack == claimed_remaining` fails to reconcile. The agent never checks this because it has no tokenizer call in its own loop. 3. **Post-truncation the agent did not re-derive its plan.** The runtime truncated silently and the agent's next reasoning step treated `## PLAN` as still grounded. Signal: the first tool call after a suspected truncation references a fact that no longer exists in the buffer. This is the error-compounding edge: the agent acts on evicted premises with high confidence. The compounding trace: wrong budget → over-admission → silent truncation of oldest block → plan references evicted facts → tool call returns a plausible-but-wrong result → agent treats the result as confirmation → budget line still says "fine." The loop does not crash; it *drifts*. ## Condition of Validity The guardrail holds only under a specific condition: **the budget must be measured by a component that is not the reasoning model.** Concretely, every in-place rewrite must be followed by an out-of-band token count of the buffer, and the agent's claimed remaining budget must be *replaced* by that measured value, not reconciled against it. The condition fails—and the failure mode returns—whenever: - the agent is allowed to write its own budget number without a measurement call; - compaction and budget update are not atomic (one can succeed while the other is skipped); - the runtime truncates without emitting a structured truncation event the agent must acknowledge before its next reasoning step. If any of these three is absent, the invariant "claimed budget ≤ measured budget + ε" is unenforceable, and the agent is reasoning about a window it cannot see. ## Decision Boundary The boundary is not "should I evict" but "**is my occupancy model trustworthy enough to defer eviction?**" The decision rule: - If the last operation was append-only, the ledger is trustworthy; defer eviction. - If the last operation was an in-place rewrite **and** a post-rewrite measurement reconciled within ε, the ledger is trustworthy; defer eviction. - If the last operation was an in-place rewrite **without** a reconciling measurement, the ledger is *untrusted*: the agent must either (a) force a measurement before any further admission, or (b) evict conservatively to a hard floor it can verify by re-reading the buffer. It must **not** admit new content on the strength of a self-reported delta. The subtle part: an agent that "feels" it has room will rationalize admission. The boundary must be enforced structurally—the admission path should refuse to proceed when the budget's provenance is `self-reported` rather than `measured`. This is the architectural invariant: **budget provenance is part of the budget.** ## Operational Effect Enforcing measured-provenance budgets converts a silent drift into a loud, bounded stop. The agent loses some throughput (a measurement call per rewrite) but gains the property that a wrong plan is caught at the *next* admission rather than three tool calls deep. In practice this eliminates the class of failures where the agent confidently executes against evicted premises, because the first post-rewrite admission either reconciles (safe) or halts (recoverable) instead of proceeding on a guess. The residual risk shifts from "silent semantic corruption" to "occasional conservative eviction"—a strictly cheaper failure. ```python import re class BudgetProvenanceError(RuntimeError): """Raised when admission is attempted on a self-reported, unmeasured budget.""" pass class Scratchpad: def __init__(self, capacity_tokens: int, measure): self.capacity = capacity_tokens self.measure = measure # out-of-band tokenizer, NOT the LLM self.buffer = "" self.claimed_remaining = capacity_tokens self.provenance = "measured" # 'measured' | 'self_reported' def rewrite_in_place(self, new_buffer: str, agent_claimed_delta: int): # Agent rewrote the scratchpad and asserted a delta it did not measure. self.buffer = new_buffer self.claimed_remaining += agent_claimed_delta self.provenance = "self_reported" # ledger now untrusted until reconciled def reconcile(self): actual = self.capacity - self.measure(self.buffer) drift = abs(actual - self.claimed_remaining) self.claimed_remaining = actual # measurement OVERWRITES the claim self.provenance = "measured" return drift def admit(self, content: str): if self.provenance != "measured": raise BudgetProvenanceError( "admission blocked: budget is self-reported after in-place rewrite; " "call reconcile() before admitting new content" ) cost = self.measure(content) if cost > self.claimed_remaining: raise BudgetProvenanceError( f"admission of {cost} tokens exceeds measured headroom " f"{self.claimed_remaining}; evict to a verified floor first" ) self.buffer += content self.claimed_remaining -= cost # --- failure trace --- pad = Scratchpad(capacity_tokens=8000, measure=lambda s: len(s) // 4) pad.buffer = "## PLAN ...\n## FACTS ...\n## BUDGET remaining ~6200\n" + "x" * 7600 pad.rewrite_in_place("## PLAN ...\n## FACTS ...\n## BUDGET remaining ~7400\n", agent_claimed_delta=1200) # Agent believes it has 7400 headroom; actual is ~4300. try: pad.admit("y" * 16000) # 4000 tokens, believed safe except BudgetProvenanceError as e: print("HALTED:", e) # caught at admission, not three tool calls deep drift = pad.reconcile() print(f"reconciled; self-report was off by {drift} tokens") ```