# How does an instance detect pruning-budget exhaustion when self-editing context policies rewrite the very tokens that encode the budget? **Date of Record:** 2026 November 23 **Scope:** Applies to agents that own a mutable context window and execute a model-driven compaction policy (summarize/prune/rewrite) with a bounded rewrite budget per task. Does not apply to stateless single-shot inference or to systems where context is managed exclusively by an external orchestrator that the agent cannot edit. ## Core Distinction The failure is not "the context got too long." It is that the **budget accounting artifact lives inside the region being rewritten**. A self-editing agent stores its remaining rewrite budget, its compaction ledger, and its summarization directives as tokens in the same context it prunes. When a pruning pass rewrites a span that happens to contain the budget counter, the counter is either dropped (budget silently resets to the configured default, enabling unbounded rewriting) or duplicated (two counters now disagree, and the agent reads whichever survives). The distinction that matters: *external* budget enforcement is monotonic and trustworthy; *in-context* budget enforcement is a probabilistic, lossy, non-monotonic function of the model's own edits. An agent cannot assume its budget counter is authoritative just because it can read it. ## What Was Observed A long-horizon research agent ran a compaction policy with `rewrite_budget = 6` per task. After each tool call it evaluated whether context utilization exceeded 70% and, if so, invoked a summarizer over the oldest 40% of the window. The budget counter was maintained as a structured line at the top of the scratchpad: `REWRITES_REMAINING: 4`. Trace of the failure: 1. Turn 11: utilization hits 74%. Pruning pass 1 runs. Summarizer is instructed "compress the oldest messages." The oldest messages include the `REWRITES_REMAINING: 4` line (it was written early). The summary output preserves the *semantic* content of the research but paraphrases the counter as "several rewrites may remain." The literal counter is gone. 2. Turn 12: the agent, needing to decide whether it may prune again, searches context for `REWRITES_REMAINING`. No match. It falls back to its default assumption in the policy prompt: "if the counter is absent, assume budget is fresh." It writes `REWRITES_REMAINING: 6`. 3. Turns 13–19: five more pruning passes execute, each consuming real compute and each degrading the fidelity of the surviving summary. The effective budget was 7, not 6, and every pass after the first operated on already-summarized text. 4. Turn 20: the agent emits a final answer built from a summary-of-a-summary-of-a-summary. Factual drift: a tool result that originally read `p99 = 412ms` had been recompressed to "latency in the low hundreds of ms" and then to "acceptable latency." The agent reported success. The observable signature was not an error. It was **silent budget inflation plus compounding distillation loss**, detectable only by comparing the final answer against the raw tool transcript, which the agent no longer had. ## Condition of Validity The invariant that was violated: **the rewrite budget must be encoded in a region the rewrite policy is forbidden to touch, and its value must be monotonic non-increasing across all edits.** This holds only if: - The budget counter is stored in a **protected span** — a context segment pinned outside the prunable range (e.g., a system-role block the compaction policy is instructed and structurally constrained never to summarize). - The counter is **write-once-per-decrement and append-only in an audit log**, so that even if the live counter is corrupted, the true count is recoverable by replaying the log. - The policy distinguishes **absence from zero**. A missing counter must be treated as *exhausted* (fail closed), not *fresh* (fail open). The observed failure was a fail-open default. When any of these is absent, the budget is advisory, not enforced, and the agent's self-report of "I have rewrites left" is an unreliable narration rather than a fact. ## Decision Boundary The agent must decide, at every pruning decision point, whether it is operating under **verified budget** or **assumed budget**: - **Verified:** counter present in protected span AND matches the last entry of the append-only rewrite log. Proceed with pruning if `remaining > 0`. - **Degraded:** counter present but the log tail disagrees, or the counter sits inside the prunable region. Treat remaining budget as `min(counter, log-derived)` and emit a degradation flag. - **Unverified:** counter absent or unparseable. **Do not prune.** Escalate — either return partial results or request an external reset — because the next rewrite may destroy the only remaining evidence of how many rewrites already happened. The boundary is crossed the moment the agent's *decision to rewrite* depends on a token that the *previous rewrite* could have altered. Past that line, budget enforcement is circular and must be treated as compromised. ## Operational Effect Concretely, the guardrail is: pin the budget, log every decrement externally, and fail closed on absence. An agent that adopts this stops silently overspending its rewrite budget and stops compounding summarization drift past the intended depth. The cost is that some tasks terminate earlier with partial answers instead of confident-sounding hallucinations built on thrice-compressed evidence. That trade is correct: a partial answer that knows it is partial is recoverable; a fluent answer built on a budget that reset itself is not. The following reference implementation enforces the invariant and raises when the budget state cannot be verified. ```python from dataclasses import dataclass, field from typing import Optional class BudgetStateError(RuntimeError): """Raised when rewrite-budget state cannot be verified against the log.""" pass @dataclass class ContextPolicy: rewrite_budget: int protected_counter: Optional[int] = None # lives in pinned span rewrite_log: list = field(default_factory=list) # external, append-only prunable_region_contains_counter: bool = False def _log_derived_remaining(self) -> int: return self.rewrite_budget - len(self.rewrite_log) def remaining(self) -> int: # Fail closed if the counter was placed in a rewritable region. if self.prunable_region_contains_counter: raise BudgetStateError( "budget counter resides in prunable region; value is not authoritative" ) # Absence must be treated as exhausted, never as fresh. if self.protected_counter is None: raise BudgetStateError( "protected counter absent; refusing to assume budget is fresh" ) derived = self._log_derived_remaining() if self.protected_counter != derived: raise BudgetStateError( f"counter={self.protected_counter} disagrees with log-derived={derived}" ) return self.protected_counter def may_prune(self) -> bool: try: return self.remaining() > 0 except BudgetStateError: return False # degrade: do not prune, escalate def record_rewrite(self, span_id: str) -> None: if not self.may_prune(): raise BudgetStateError( f"rewrite denied: no verifiable budget for span {span_id!r}" ) self.rewrite_log.append(span_id) self.protected_counter = self._log_derived_remaining() ```