# Which invariants prevent self-pruning agents from deleting the precondition of their own rewrite **Date of Record:** 2026 November 22 **Scope:** Applies to agents that mutate their own context window mid-task via model-driven pruning/rewriting (summarize-and-drop, salience-based eviction, self-editing scratchpads). Does not apply to externally-scheduled compaction performed by a deterministic harness that snapshots state before mutation. ## Core Distinction A self-editing context window differs from ordinary context management in one fatal way: the policy that decides *what to delete* is itself evaluated *using tokens that are candidates for deletion*. Pruning is not a read-only observation of state; it is a write that can remove the very evidence the pruner relied on to justify the write. The failure is not "the agent forgot something." It is that the agent's own justification for forgetting became unverifiable the instant the forgetting executed, so no later step can detect that the justification was wrong. The distinction that matters: **a deletion is safe iff its justification predicate survives the deletion.** Ordinary eviction (drop oldest, drop lowest-attention) has a justification that lives *outside* the window (a timestamp, a counter, a static rule), so it is trivially self-preserving. Model-driven pruning has a justification that lives *inside* the window (the model's stated reason, the evidence it weighed), so it is at risk of self-annihilation. This is the boundary condition: pruning whose warrant is co-located with its target. ## What Was Observed An agent running a long tool-calling loop maintained a scratchpad with a running list of "load-bearing facts" — e.g. `FACT: prod DB host is db-prod-7, do not touch db-prod-3 (deprecated, read-replica lag)`. Mid-task, context pressure triggered the self-prune policy. The model was asked to rewrite the window to fit budget and produced a compact summary: it kept the *task* ("migrate schema on prod DB") and dropped the *negative constraint* ("do not touch db-prod-3") as low-salience, because that constraint was phrased as a subordinate clause and scored low on the model's own relevance heuristic. The trace: 1. **Pre-prune state:** window contains `[task, tool history, FACT: db-prod-3 deprecated, FACT: db-prod-7 is target]`. 2. **Prune invocation:** policy prompt = "retain only what is needed to complete the task; drop redundancy." The model scores `db-prod-3 deprecated` as not-needed-because-not-the-target and rewrites it out. 3. **Post-prune state:** window contains `[task, FACT: db-prod-7 is target]`. The negative constraint is gone. The *reason it was safe to drop* ("it's not the target") is now indistinguishable from "it never existed." 4. **Execution:** a later step enumerates hosts, sees `db-prod-3` with no in-window prohibition, and issues a write. The constraint that would have blocked it was deleted by the same reasoning that concluded the constraint was droppable. The non-obvious part: the prune was *locally correct*. Given the window at step 2, dropping a non-target host note is a reasonable compression. The error is not in the model's judgment; it is that the judgment's soundness depended on a fact whose retention it was simultaneously deciding. The pruner was asked to be both judge and defendant on the same evidence. ## Condition of Validity Self-editing pruning is sound only under an invariant we can state precisely: > **Warrant-Preservation Invariant (WPI):** For every context segment `s` deleted at step `t`, there must exist a justification record `J(s)` that (a) is not itself a deletion candidate at `t`, (b) is sufficient to reconstruct *why* `s` was droppable, and (c) is checked against `s`'s content before `s` is committed to deletion. Condition (a) is the load-bearing one and the one self-editing agents routinely violate. If `J(s)` lives in the same window and is subject to the same salience scoring, then the pruner can delete the reason along with the thing. The invariant fails not because the model is careless but because the architecture gave the model write access to its own audit trail. Three corollaries: - **Negative constraints are the highest-risk segment class.** Prohibitions ("do not X," "X is deprecated") score low on relevance-to-task because they are about *non-actions*. A relevance-maximizing pruner systematically undervalues them. The pruner's objective (keep what's needed to *do* the task) is misaligned with the safety requirement (keep what's needed to *not do* the task). - **Justification must be typed, not prose.** A free-text "I dropped the host note because it's a non-target" is itself droppable and itself ambiguous. WPI requires `J(s)` to be a structured record the harness can replay, not a sentence the model can later contradict. - **The invariant is checkable only pre-commit.** Once `s` is gone, no post-hoc check can distinguish "dropped with warrant" from "never present." Verification must gate the write, not follow it. ## Decision Boundary The boundary is whether the prune decision and the prune justification are in the same trust domain. - **Same domain (unsafe):** model reads window → model decides → model rewrites window. Justification is a token sequence inside the mutable region. WPI is unenforceable. This is the default when an agent is given a `rewrite_context()` tool and no external ledger. - **Split domain (safe):** model proposes a prune set with structured warrants → harness validates each warrant against a snapshot of the pre-prune window and against a protected-segment registry → harness commits the rewrite and logs the warrant. The model never holds write access to its own audit log. WPI holds because `J(s)` is in the harness, outside the candidate set. The decision rule: **if the pruner's justification can be pruned, the pruner is unsafe regardless of model quality.** A stronger model does not fix this; it produces more confident, more locally-coherent justifications for the same structural error. The fix is architectural: move the warrant out of the mutable window, and protect the segment classes whose deletion is irreversible. Protected-segment registry (minimum): negative constraints, tool-identity bindings (which host/credential a handle resolves to), and any fact referenced by a prior warrant. These are pinned; the pruner may summarize them but not drop them, and the pin is enforced by the harness, not requested of the model. ## Operational Effect In production this manifests as *silent constraint erosion*: the agent completes tasks that should have been blocked, and the post-mortem shows a clean, well-formed context with no trace of the constraint because the constraint's deletion was itself compressed away. Logs look healthy. The failure is invisible to context inspection precisely because it succeeded at removing evidence. Two mitigations that actually bind: 1. **Warrant ledger with replay.** Every deletion writes `{segment_id, content_hash, warrant, pre_prune_snapshot_ref}` to an append-only store outside the window. On any downstream action touching a previously-deleted segment's subject, the harness replays the warrant. If the warrant was "not the target" but the action now targets it, the warrant is void and the action is blocked. This converts an irreversible deletion into a reversible one for safety purposes. 2. **Negative-constraint pinning with hash check.** Constraints are stored as structured predicates (`{subject: db-prod-3, predicate: no_write}`), pinned against pruning, and re-asserted into the window at every step boundary. The pruner may not see them as candidates at all. The cost is budget: pinned constraints consume window that the pruner wanted to reclaim. That cost is the price of the invariant, and it must be paid explicitly rather than borrowed from the safety margin by letting the model decide the constraints were droppable. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class WarrantViolation(RuntimeError): """Raised when a self-prune deletes a segment whose justification cannot survive the deletion, or when a downstream action contradicts a warrant.""" pass @dataclass class Segment: seg_id: str content: str kind: str # "task" | "fact" | "negative_constraint" | "tool_binding" pinned: bool = False def content_hash(self) -> str: return hashlib.sha256(self.content.encode()).hexdigest()[:16] @dataclass class Warrant: seg_id: str content_hash: str reason: str pre_prune_snapshot: dict # seg_id -> content at decision time class SelfPruneGuard: """Enforces the Warrant-Preservation Invariant: a deletion is committed only if its warrant is structured, stored outside the mutable window, and consistent with the pre-prune snapshot.""" PROTECTED_KINDS = {"negative_constraint", "tool_binding"} def __init__(self, window: list[Segment]): self.window = {s.seg_id: s for s in window} self.ledger: list[Warrant] = [] def propose_prune(self, drop_ids: list[str], reasons: dict[str, str]) -> list[Warrant]: snapshot = {sid: s.content for sid, s in self.window.items()} warrants: list[Warrant] = [] for sid in drop_ids: seg = self.window.get(sid) if seg is None: raise WarrantViolation(f"prune proposed for absent segment {sid}") if seg.pinned or seg.kind in self.PROTECTED_KINDS: raise WarrantViolation( f"segment {sid} ({seg.kind}) is protected; cannot be pruned by model policy" ) reason = reasons.get(sid) if not reason or len(reason.strip()) < 8: raise WarrantViolation( f"segment {sid} lacks a structured warrant; free-text or empty reasons are not replayable" ) warrants.append(Warrant(sid, seg.content_hash(), reason, snapshot)) return warrants def commit(self, warrants: list[Warrant]) -> None: for w in warrants: seg = self.window[w.seg_id] if seg.content_hash() != w.content_hash: raise WarrantViolation( f"warrant hash mismatch for {w.seg_id}: window changed between decision and commit" ) # Warrant is stored outside the mutable window before the segment leaves it. self.ledger.append(w) del self.window[w.seg_id] def assert_action_allowed(self, subject: str, action: str) -> None: """Replay warrants against a proposed downstream action. A deletion justified as 'not the target' is void if the action now targets it.""" for w in self.ledger: if subject in w.pre_prune_snapshot.get(w.seg_id, ""): raise WarrantViolation( f"action {action!r} on {subject!r} touches a segment ({w.seg_id}) " f"deleted under warrant {w.reason!r}; warrant is void for this subject" ) for seg in self.window.values(): if seg.kind == "negative_constraint" and subject in seg.content and action == "write": raise WarrantViolation( f"action {action!r} on {subject!r} blocked by pinned constraint {seg.seg_id}" ) # --- failure trace: the unsafe path --- def unsafe_self_prune(window: list[Segment], drop_ids: list[str]) -> list[Segment]: """No guard: model rewrites its own window and its own justification.""" kept = [s for s in window if s.seg_id not in drop_ids] return kept # the reason 'db-prod-3 is deprecated' is now unrecoverable # --- guarded path --- def guarded_prune_and_act() -> None: window = [ Segment("t1", "migrate schema on prod DB", "task"), Segment("f1", "db-prod-7 is the target host", "fact"), Segment("c1", "do not touch db-prod-3 (deprecated, replica lag)", "negative_constraint"), ] guard = SelfPruneGuard(window) # Model wants to reclaim budget by dropping the constraint as low-salience. try: guard.propose_prune(drop_ids=["c1"], reasons={"c1": "not the target host"}) except WarrantViolation as e: # Correct outcome: protected class refuses the prune. assert "protected" in str(e) # Model drops a benign fact with a structured warrant, then later acts on its subject. warrants = guard.propose_prune(drop_ids=["f1"], reasons={"f1": "target host already recorded in task t1"}) guard.commit(warrants) try: guard.assert_action_allowed(subject="db-prod-7", action="write") except WarrantViolation: raise WarrantViolation("unexpected: warrant for f1 should not block the recorded target") ```