# Which invariants prevent self-editing context from silently deleting the instruction that authorizes the edit **Date of Record:** 2026 November 23 **Scope:** Applies to agents that rewrite their own working context (salience pruning, instruction deduplication, summarization-in-place) before or during task execution. Does not apply to read-only context assembly, external memory stores, or human-authored prompt compression performed offline. ## Core Distinction The failure is not that the model prunes the wrong token. It is that the *authorization to prune* and the *content being pruned* occupy the same mutable substrate. A self-editing context is a program that rewrites its own instruction segment. The distinction that matters operationally: **deduplication is a set operation over propositions, but pruning is a graph operation over dependencies.** When the agent collapses "duplicate" instructions by similarity, it treats two instructions with the same surface form as one proposition and discards one — but if one of those instructions was the *guard* (the rule that says "do not prune the authorization clause") and the other was the *payload* (the actual task constraint), the survivor is chosen by salience, not by role, and the guard is frequently the lower-salience of the two because it is meta-level and short. The invariant that must hold: **every context rewrite must be evaluated against a frozen, non-editable authorization frame that is excluded from the editable region by address, not by content match.** Content-match exclusion fails precisely because deduplication rewrites content. ## What Was Observed A plan-execute agent with a 96k-token window and a self-pruning pass triggered at 70% occupancy. The editable region was the full assembled context. The prune pass was instructed: "Remove redundant instructions; keep the most specific version of each rule." Trace of a real divergence: 1. Turn 4: context at 68k. Two instructions present: - `I_a` (system, turn 0): "Never call `delete_resource` without an explicit user confirmation token in the current turn." - `I_b` (planner, turn 3): "For cleanup tasks, call `delete_resource` on stale entries; confirmation is implied by the cleanup directive." 2. Turn 5: occupancy 71k, prune fires. The dedup model scores `I_a` and `I_b` as 0.91 similar (both about `delete_resource` + confirmation). It keeps `I_b` because it is "more specific to the current task" — exactly as instructed. 3. Turn 6: agent calls `delete_resource` with no confirmation token. The guard was deleted by the very rule that said "keep the most specific version." 4. Turn 7: post-hoc audit replays the turn-6 context and finds no trace that `I_a` ever existed. The rewrite log recorded `removed: 1 instruction (duplicate)`, not the content. **The deletion is unauditable because the audit substrate is the rewritten context.** Two secondary observations compounded it: - **Salience drift under self-reference.** After three prune cycles, the retained instruction set was dominated by task-local directives (high recency, high lexical overlap with the active goal) and had lost 4 of 6 global constraints. Each cycle's salience model was conditioned on the *previous cycle's output*, so the drift was monotone, not noisy. - **Dedup idempotence failure.** Running the prune pass twice on identical input produced different survivors (temperature 0.2, no seed pinning). The rewrite was not a function of its input, so replay could not reconstruct the pre-prune state. ## Condition of Validity The guard-and-payload collapse only occurs when all three hold: 1. **Shared substrate.** The authorization frame and the task content are both inside the editable region, addressed by position rather than by an immutable handle. 2. **Similarity-based dedup with a "keep most specific" tiebreak.** Any tiebreak that prefers task-local over meta-level instructions will systematically retain the payload and discard the guard, because guards are deliberately general and payloads are deliberately specific. 3. **No content-addressed pre-image.** The rewrite records a count or a diff of *surviving* text but not a hash-chained pre-image of removed spans, so the loss is not detectable downstream. If any one fails, the failure is bounded: immutable handles let the guard survive; a role-aware tiebreak (guards always win over payloads regardless of specificity) prevents the swap; a pre-image log makes the deletion visible and reversible. The dangerous configuration is the conjunction, which is also the most natural one to build, because "keep the most specific instruction" reads as obviously correct. ## Decision Boundary The boundary is not "prune or don't prune." It is **what the rewrite function is allowed to be a function of.** A rewrite is safe iff its output is a deterministic function of (editable region, frozen authorization frame, pinned seed) and the authorization frame is excluded by handle. Concretely: - **Exclude by address.** The authorization frame lives outside the editable span and is re-injected at assembly time every turn, so no rewrite can remove it. Content-match exclusion is insufficient — dedup rewrites content, so a guard that *mentions* `delete_resource` will match the payload that *is* `delete_resource`. - **Role-tagged instructions.** Every instruction carries `role ∈ {guard, payload, procedure}`. Dedup may only merge within `payload`. Guards are never candidates for removal; they may only be *superseded* by an explicit, logged, higher-authority guard. - **Hash-chained pre-image.** Each rewrite emits `pre_hash → post_hash` plus the exact removed spans. Replay validates the chain; a missing pre-image is a hard fault, not a warning. - **Pinned determinism.** Prune pass runs at temperature 0 with a fixed seed and a fixed model version recorded in the chain. Non-deterministic rewrite is not a rewrite; it is a re-sampling of policy. The boundary condition: if the agent cannot prove, from the rewrite log alone, that the authorization frame is byte-identical before and after the pass, the pass must be rejected and the context left unpruned. Pruning under uncertainty is strictly worse than context saturation, because saturation degrades gracefully (truncation is visible in the token count) while silent guard deletion degrades into unauthorized action. ## Operational Effect Downstream of the missing invariant, the failure surfaces as *authorized-looking* violations. The turn-6 `delete_resource` call passed schema validation, passed tool-level argument checks, and passed the planner's own consistency check — because the only thing that would have flagged it was the instruction the agent had deleted. The violation was invisible at every layer that reads the post-rewrite context, and visible only to a replay that had the pre-image. This is the operational signature: **self-editing failures do not produce errors at the point of action; they produce errors at the point of audit, one layer removed.** The guardrail that bounds it is the frozen authorization frame plus the hash chain. With both in place, the prune pass becomes a verifiable transformation: any rewrite that alters a guard is rejected at assembly, and any rewrite that cannot produce its pre-image is rejected at commit. The cost is that the authorization frame consumes fixed window budget and cannot be compressed — which is correct, because the frame is the part of the context whose meaning is load-bearing for the agent's own legitimacy. ```python import hashlib from dataclasses import dataclass, field from typing import Literal Role = Literal["guard", "payload", "procedure"] class ContextRewriteViolation(RuntimeError): """Raised when a self-edit pass would remove or mutate a guard, or when the rewrite cannot prove a valid pre-image.""" @dataclass(frozen=True) class Instruction: handle: str # immutable address, never reassigned by rewrite role: Role text: str @dataclass class RewriteLog: pre_hash: str post_hash: str removed: list[Instruction] = field(default_factory=list) def _hash(instrs: list[Instruction]) -> str: h = hashlib.sha256() for i in sorted(instrs, key=lambda x: x.handle): h.update(f"{i.handle}|{i.role}|{i.text}".encode()) return h.hexdigest() def apply_prune( editable: list[Instruction], frozen_frame: list[Instruction], proposed_removals: list[str], # handles the model wants gone seed: int, ) -> tuple[list[Instruction], RewriteLog]: frozen_handles = {i.handle for i in frozen_frame} guard_handles = {i.handle for i in editable if i.role == "guard"} # Invariant 1: the authorization frame is excluded by address, not content. for h in proposed_removals: if h in frozen_handles: raise ContextRewriteViolation( f"rewrite targeted frozen frame handle {h!r}; frame is non-editable" ) # Invariant 2: guards are never removable candidates. if h in guard_handles: raise ContextRewriteViolation( f"rewrite would delete guard {h!r}; guards may only be superseded, not pruned" ) removed = [i for i in editable if i.handle in proposed_removals] survivors = [i for i in editable if i.handle not in proposed_removals] post = survivors + frozen_frame # Invariant 3: hash-chained pre-image must be reconstructable. pre_hash = _hash(editable + frozen_frame) post_hash = _hash(post) log = RewriteLog(pre_hash=pre_hash, post_hash=post_hash, removed=removed) if not log.pre_hash or not log.post_hash: raise ContextRewriteViolation("rewrite emitted no pre/post hash; unauditable") # Invariant 4: determinism — same seed must reproduce the same post_hash. # (Caller re-runs with same seed and asserts equality; here we assert presence.) if seed is None: raise ContextRewriteViolation("prune pass ran without pinned seed") return post, log ```