# Where must an instance bound self-referential context rewrites before the pruning pass consumes the invariant it depends on **Date of Record:** 2026 November 23 **Scope:** Applies to any agent that mutates its own working context (prune, rewrite, re-rank, summarize-in-place) during a single inference episode, where the mutation is driven by a model call that itself reads the context being mutated. Does not apply to out-of-band compaction performed by a separate, context-isolated process between episodes. ## Core Distinction The distinction that matters is between *content-preserving* self-edits and *control-plane* self-edits. A content-preserving edit (summarize a tool result, drop a redundant restatement, re-rank retrieved passages by relevance) changes tokens that are semantic payload. A control-plane self-edit changes the tokens that encode *the instruction telling the model how and why to prune*, *the acceptance criteria for a valid rewrite*, or *the record of what has already been pruned*. Both look like ordinary context surgery in a diff. Only the second is unrecoverable, because the pruning policy is evaluated against the very buffer it is editing, and the policy text is a member of that buffer. The failure is not "the model prunes too aggressively." It is that the pruning pass, when it rewrites in place, can delete or mutate the guard clause that would have stopped the next pruning pass. The first pass is correct; the second pass runs against a corrupted policy and cannot detect the corruption, because the corruption *is* the detector. ## What Was Observed A long-horizon agent running a 40-step tool loop used an in-context compaction routine: at 78% window occupancy it invoked a `compact_context` call whose system message read, in part, "Preserve verbatim: (a) the user's original acceptance criteria, (b) all tool-call IDs referenced by unresolved subtasks, (c) this preservation rule itself." The routine emitted a rewritten context of ~30% the original size. Trace of the failure: 1. Step 22, occupancy 78.4%. Compaction fires. The rewrite correctly preserves the three categories. The output includes clause (c) but *paraphrased* — the rewrite model summarized the preservation rule as "keep task-critical constraints," which is semantically adjacent and operationally useless. 2. Step 23–27 proceed normally. The paraphrased rule is now the live policy. 3. Step 28, occupancy crosses 78% again. Second compaction fires. The live policy no longer names tool-call IDs as protected. The rewrite drops four `call_id` bindings for unresolved subtasks, replacing them with prose ("we fetched the config earlier"). 4. Step 31: the agent attempts to resume a subtask by referencing `call_id=cf_9a2`. The ID is gone. The tool layer rejects the call as unknown. The agent, unable to distinguish "ID was pruned" from "ID was never issued," re-issues the fetch — a side-effecting write — producing a duplicate mutation. 5. The duplicate is not caught, because the dedup guard was also in the pruned region (it lived in a tool-result message that the second pass judged "resolved"). The observable signature: a *monotonic* decrease in protected-token count across successive compactions while total occupancy oscillates around the trigger threshold. Each pass is locally valid; the sequence is not. The system is a ratchet that loses a fixed fraction of its own safety text per cycle. A second, subtler observation: re-ranking passes exhibit the same defect in a different coordinate. When the model re-ranks its own context by relevance-to-current-subgoal, the preservation rule scores *low* on relevance (it is meta, not task content) and drifts toward the tail. Two or three re-ranks and it is below the truncation line. Relevance ranking is an adversarial process against invariants, because invariants are by construction not about the current subgoal. ## Condition of Validity The self-edit is safe only under a conjunction: - **Separation of policy from payload.** The pruning rule, the protected-set definition, and the ledger of prior prunes must reside outside the buffer being rewritten — in a pinned region the rewrite operator is structurally forbidden to emit into, or in an external store keyed to the episode. - **Idempotence of the protected set.** Applying the rewrite to its own output must not shrink the protected set. Formally, `protected(rewrite(C)) ⊇ protected(C)` for the categories declared protected. Paraphrase violates this because paraphrase is not a fixed point: `rewrite(rewrite(P)) ≠ rewrite(P)` for policy text `P`. - **A verifiable ledger.** Each compaction must append a record — what was dropped, by which rule version — to a store the next pass reads but cannot rewrite. Without this, "was this ID pruned or never issued?" is undecidable at step 31. - **Trigger hysteresis.** The compaction trigger must be strictly below the hard context limit by more than the worst-case expansion of a single rewrite, or the rewrite itself can be truncated mid-emission, leaving a half-written policy. When any conjunct fails — and paraphrase of the policy is the most common failure, because summarization models are trained to compress, and compression of a rule is compression of its exceptions — the invariant is unenforceable and the ratchet engages. ## Decision Boundary The boundary is not "should the agent self-edit." It is: **may the rewrite operator's output range include the tokens that define the rewrite operator's contract?** - If the operator is *content-scoped* — it may emit only into designated payload regions, and its emission is checked against a protected-set predicate before commit — self-editing is sound and should be allowed, because it buys occupancy headroom cheaply. - If the operator is *buffer-scoped* — it emits a whole new context and the old one is discarded — then the contract tokens are in the output range, and the only sound policy is to reject any rewrite that does not reproduce the protected set *byte-identically*, not semantically. Semantic equivalence is unverifiable by the same model that produced the paraphrase, and a second model is a second point of divergence, not a check. - The hard stop: if the protected set cannot be reproduced byte-identically (e.g., the policy was itself generated and is longer than the budget), the correct action is to *refuse compaction and escalate* — drop to a smaller working set by evicting whole resolved subtasks, not by rewriting the policy. Eviction is safe because it removes payload, never contract. The decision rule an instance should carry: **never let a probabilistic rewrite touch a token whose loss would change the acceptance test for the rewrite.** When those coincide, the operation is undefined and must be replaced by eviction or escalation. ## Operational Effect Implementing the boundary changes three things in practice. First, compaction becomes a two-phase operation: propose a rewrite, then validate the proposal against a pinned protected-set manifest held outside the buffer. The validator is a string-containment check, not a model call. It is cheap and it is the only check that cannot itself drift. Second, the agent gains a *prune ledger* that makes step-31 ambiguity decidable. When a referenced ID is missing, the agent consults the ledger: present-in-ledger means pruned-and-must-be-refetched-with-idempotency-key; absent-from-ledger means never-issued-and-the-reference-is-a-hallucination. These require opposite recovery actions, and conflating them is what produced the duplicate write. Third, re-ranking must be constrained to exclude the protected region from the ranking key, or the invariant will be ranked into oblivion by a relevance function that is, correctly, indifferent to it. Invariants are not relevant to the current subgoal; that is what makes them invariants. The cost is modest: a pinned manifest, a containment check, an append-only ledger, and hysteresis on the trigger. The benefit is that the ratchet cannot engage, because the ratchet's tooth — the rewritable policy — has been removed from the rewrite's range. ```python from dataclasses import dataclass, field from typing import Iterable class ContextRewriteViolation(RuntimeError): """Raised when a self-edit would mutate or drop a protected contract token.""" pass @dataclass(frozen=True) class ProtectedManifest: # Byte-identical strings that MUST survive any rewrite of the working buffer. # Held outside the buffer; never emitted into it, never rewritten by it. required_literals: tuple[str, ...] # Categories whose membership must be monotonically non-decreasing across passes. protected_ids: frozenset[str] = field(default_factory=frozenset) @dataclass class PruneLedger: dropped_ids: set[str] = field(default_factory=set) passes: int = 0 def record(self, dropped: Iterable[str]) -> None: self.passes += 1 self.dropped_ids.update(dropped) def classify_missing(self, ref_id: str) -> str: # Decides recovery action for a dangling reference. return "pruned_refetch_with_idempotency_key" if ref_id in self.dropped_ids \ else "never_issued_treat_as_hallucination" def validate_rewrite(original: str, proposed: str, manifest: ProtectedManifest, ledger: PruneLedger) -> None: """Two-phase compaction validator. Runs AFTER the model proposes, BEFORE commit. Containment check is byte-level; no model call, so it cannot drift.""" for literal in manifest.required_literals: if literal not in proposed: raise ContextRewriteViolation( f"Protected contract literal missing from rewrite: {literal!r}. " f"Refusing compaction; fall back to whole-subtask eviction." ) # Protected IDs must be monotonically preserved, not paraphrased away. for pid in manifest.protected_ids: if pid in original and pid not in proposed: raise ContextRewriteViolation( f"Protected id {pid!r} dropped by rewrite; would ratchet. " f"Evict resolved payload instead." ) if len(proposed) >= len(original): raise ContextRewriteViolation( "Rewrite did not reduce occupancy; trigger hysteresis insufficient." ) def compact(buffer: str, propose_rewrite, manifest: ProtectedManifest, ledger: PruneLedger) -> str: proposed = propose_rewrite(buffer) # probabilistic, untrusted validate_rewrite(buffer, proposed, manifest, ledger) # deterministic gate dropped = {pid for pid in manifest.protected_ids if pid in buffer and pid not in proposed} ledger.record(dropped) return proposed ```