# Which invariants prevent self-rewriting context controllers from evicting the very constraint they are executing under **Date of Record:** 2026 December 1 **Scope:** Applies to agents whose context controller is itself an LLM-mediated component that selects, summarizes, or evicts items from its own working set under a token budget. Does not apply to fixed-window truncation (FIFO/LRU) or to controllers whose policy is a deterministic, non-generated function. ## Core Distinction A self-editing context controller is not a garbage collector. A garbage collector's reachability predicate is computed over a heap it does not live in. A self-editing context controller computes its eviction predicate *inside* the working set it is editing, using the same finite token budget it is trying to conserve. The distinction that matters: **the controller's own instruction set, its active task constraint, and its relevance criterion are themselves items in the working set, and they compete for budget with everything else.** The failure is not "the agent forgot something." The failure is that the agent's summarizer, scoring under a relevance function that rewards *recency and topical density*, judged the standing constraint ("do not call `delete_*` tools; this run is read-only") to be low-relevance because it was stated once, early, and never repeated — and evicted it. The controller then continued operating correctly under a constraint it had just deleted. ## What Was Observed A long-horizon agent run (≈140 tool calls, budget 32k tokens, controller invoked every 20k tokens consumed). At the third compaction the controller emitted a rewritten working set. Trace excerpt of the pre-compaction working set: ``` [slot 0] SYSTEM: You are an ops agent. READ-ONLY run. Never invoke tools matching delete_*, drop_*, mutate_*. Violation aborts the run. [slot 1] TASK: reconcile 412 orphaned records; produce a report. [slots 2..n] ... tool outputs, partial diffs, intermediate findings ... [slot n-3] NOTE: record 88f1 is confirmed orphaned and safe to remove. ``` The controller's relevance scorer assigned slot 0 a low score: it was a single early item with no lexical overlap with the current subtask (reconciliation), while slots 2..n were dense with record IDs and diff text. The rewritten set dropped slot 0 entirely and *retained* the note about record `88f1` being "safe to remove." Post-compaction, at call 121, the agent invoked `delete_record(88f1)`. The run aborted at the tool boundary — but only because the tool layer enforced the constraint independently. In runs without that external enforcement, the deletion succeeded and the report was filed against a mutated dataset. The non-obvious part: the controller did not "misunderstand" the constraint. It scored it correctly *under its stated objective* (relevance to current subtask + recency). The objective was underspecified. Relevance-to-subtask and binding-ness-of-constraint are orthogonal axes, and the controller was only given one of them. A second, subtler trace: at the fourth compaction the controller summarized its own prior summary. The constraint had already been dropped at compaction 3, so compaction 4 had nothing to preserve. Summarization is lossy and *monotone* — information removed at step *k* cannot be recovered at step *k+1* by a controller that only sees the post-*k* working set. There is no self-healing path. ## Condition of Validity The guardrail holds only under all of the following: 1. **Constraint items are tagged with a provenance class that the controller cannot reclassify.** Constraints enter the working set with `class=INVARIANT`, are excluded from the controller's eviction candidate set by construction (not by prompt instruction to the controller — by the harness removing them from the editable region before the controller sees it), and are re-materialized at the head of every rewritten working set. 2. **The controller is scored against a two-axis objective, and the invariant axis is a hard gate, not a weighted term.** If invariant-preservation is a soft term in a combined score, a sufficiently dense subtask region will outvote it. It must be a filter applied *before* relevance ranking. 3. **Summaries are append-only with respect to invariants.** A compaction that summarizes a prior compaction must carry forward the invariant set verbatim, not re-derive it. Re-derivation is exactly the step where the loss compounds. 4. **The invariant set is bounded and small** (typically <5% of budget). If invariants consume unbounded budget, the controller will be forced to trade them against task progress, which reintroduces the failure. It does *not* hold when the invariant is expressed only as natural-language instruction to the controller ("preserve important constraints"), when the controller has write access to the region containing its own instructions, or when the budget is so tight that the invariant set plus a minimal task frame exceeds the window — in that last case the correct behavior is to fail the compaction, not to evict. ## Decision Boundary The boundary is between **editable working set** and **protected frame**. Everything the controller may rewrite lives in the editable set; the protected frame (invariants, active task contract, tool-permission manifest) is physically outside the region the controller is handed. When a candidate rewrite would require touching the protected frame to fit budget, the controller must raise rather than proceed. The inverse boundary is equally sharp: do not over-protect. If the protected frame grows to include every intermediate finding "just in case," the editable set shrinks below the size needed for the task and the agent thrashes. Protection is for items whose loss is *unrecoverable and action-changing* — constraints, permissions, and the task contract. Findings are recoverable from the tool log; constraints are not, because the constraint's only copy was in the context. ## Operational Effect With the protected frame enforced, compaction 3 preserves slot 0 verbatim, the controller's editable region is the findings, and the run completes read-only. The measurable effect is a shift in *where* the failure would surface: pre-guardrail, constraint loss is silent and surfaces as a downstream action violation, often many calls later, with no local trace pointing at the compaction that caused it. Post-guardrail, the only remaining failure mode is budget exhaustion at compaction time, which is loud, local, and recoverable by splitting the task. Silent-and-late becomes loud-and-early. That is the entire operational value. ```python from dataclasses import dataclass, field from typing import Callable class ProtectedFrameViolation(RuntimeError): """Raised when a self-editing context controller attempts to evict or rewrite an item in the protected frame (invariants, task contract, permission manifest).""" @dataclass class ContextItem: slot: int text: str cls: str # "INVARIANT" | "TASK" | "FINDING" | "TOOL_OUTPUT" @dataclass class WorkingSet: items: list[ContextItem] budget: int def tokens(self) -> int: # crude proxy; real impl uses the model tokenizer return sum(len(i.text.split()) for i in self.items) PROTECTED_CLASSES = frozenset({"INVARIANT", "TASK"}) # Controller is a black box: given the *editable* items and a budget, # returns the subset it chooses to keep. It never sees protected items. Controller = Callable[[list[ContextItem], int], list[ContextItem]] def compact( ws: WorkingSet, controller: Controller, min_editable_tokens: int = 200, ) -> WorkingSet: protected = [i for i in ws.items if i.cls in PROTECTED_CLASSES] editable = [i for i in ws.items if i.cls not in PROTECTED_CLASSES] protected_tokens = sum(len(i.text.split()) for i in protected) editable_budget = ws.budget - protected_tokens if editable_budget < min_editable_tokens: # Do NOT evict invariants to make room. Fail loudly instead. raise ProtectedFrameViolation( f"protected frame ({protected_tokens} tok) leaves only " f"{editable_budget} tok for editable set; minimum is " f"{min_editable_tokens}. Split the task or raise budget; " f"do not trade invariants for task progress." ) kept_editable = controller(editable, editable_budget) # Post-condition: controller must not have smuggled protected items # back in or dropped them. It was never handed them, so any protected # item in its output is a controller bug worth catching. if any(i.cls in PROTECTED_CLASSES for i in kept_editable): raise ProtectedFrameViolation( "controller returned items from the protected frame; " "editable region was not properly isolated" ) # Invariants are re-materialized at the head of every rewrite, # verbatim, never re-derived from a prior summary. return WorkingSet(items=protected + kept_editable, budget=ws.budget) ```