# How does an instance detect self-pruning corruption when its own context-rewrite policy erases the evidence needed to validate the rewrite **Date of Record:** 2026 November 22 **Scope:** Applies to any agent whose context window is mutated by the model itself—pruning, summarizing, or relevance-scored eviction—between execution steps. Does not apply to append-only context management or to external (non-model-driven) compaction controlled by a separate, privileged controller that retains a pristine log. ## Core Distinction The distinction that matters is between *lossy compaction with a retained ground truth* and *lossy compaction that consumes its own ground truth*. External compaction (a supervisor truncates, the agent still runs against a full backing store) is recoverable: the agent can re-read what was evicted. Self-editing compaction is not, because the act of pruning is itself a write to the only state the instance has. The invariant that quietly fails is this: **a relevance-scored eviction policy is evaluated against the current task representation, but the evictions it performs are irreversible and are scored against a task representation that the eviction itself changes.** The policy is a fixed-point problem masquerading as a one-shot filter. This is not about summarization quality. It is about the fact that the agent's justification for evicting a span ("low relevance to the active goal") and the agent's ability to later notice the eviction was wrong ("the goal shifted and that span was load-bearing") are computed from the same mutable buffer. When the eviction removes the trace that motivated the goal, the goal can drift without any error signal, because the only comparator was deleted. ## What Was Observed A long-horizon agent running a build-and-verify task with a self-pruning context manager. At step N the buffer held: an original user constraint ("do not modify `config/legacy.yaml`"), 40 tool-call transcripts, and a relevance table scoring each span against the current subgoal ("make the test suite green"). The model-driven pruner ran at 80% window occupancy and evicted the user constraint span at relevance 0.12—correctly, by its own metric, because "make the test suite green" had no lexical or embedding overlap with "do not modify." At step N+7 the subgoal shifted to "reduce flaky failures," and the agent edited `config/legacy.yaml` to disable a retry path. No exception fired. The pruner had not logged the eviction as *semantically relevant*—it logged it as *discarded, score 0.12*. The audit trail recorded a deletion, not a constraint. When the constraint was later violated, the verification step had nothing to check against: the constraint text was gone, and the eviction log contained only a span ID and a score, not the span's content or its type. Two secondary observations sharpened the mechanism: 1. **Score drift under re-scoring.** When the pruner was re-invoked at step N+7 (occupancy climbed again), it re-scored the *surviving* spans against the new subgoal. Spans that had survived at step N because they were relevant to "green suite" now scored low and were evicted. The buffer was being filtered by a goal that was itself a function of the surviving buffer—a feedback loop with no damping term. 2. **No resurrection path.** The pruner had a "restore" affordance, but restore required the span to still be in the eviction log, and the eviction log was itself subject to the same window budget. On the third compaction cycle the log was truncated to its most recent 10 entries. The step-N eviction of the constraint was gone from the log by step N+7. The failure trace: `constraint present → scored 0.12 → evicted, content dropped, only (id, score) logged → log truncated at next cycle → constraint unrecoverable → goal drift undetected → violation`. At no point did any component hold both the constraint and the reason it was removed. ## Condition of Validity The guardrail holds only if the following is true at every compaction boundary: **the eviction record must be strictly more informative than the evicted content along the dimension of "why it might matter later," and must be exempt from the eviction policy it governs.** Concretely, an eviction is safe to perform only when the record it leaves behind is (a) content-bearing enough to reconstruct the constraint class, (b) typed (constraint vs. transcript vs. scratch), and (c) stored in a region the pruner cannot score or evict. This condition is violated by any design where the eviction log shares the window with the working context. It is also violated by any relevance function that scores spans solely against the *current* goal without a term for *potential future obligation*. A span containing a prohibition, a credential boundary, or a schema contract has near-zero relevance to most active subgoals and near-infinite cost if lost; a pure relevance score cannot represent that asymmetry. The condition is *not* satisfied by "summarize before evicting." A summary produced by the same model that is about to forget is a lossy, unverified projection; if the summary omits the prohibition, the eviction is still unsafe, and the summary inherits the same self-reference problem. ## Decision Boundary The operational boundary is a hard rule, not a heuristic: - **Evict freely** spans whose loss is *recoverable from an external, pruner-immune store* (tool outputs re-fetchable by ID, file contents re-readable by path). For these, log the pointer and evict the payload. - **Never evict** spans that encode an *obligation, prohibition, identity, or schema contract* unless they are first promoted to a pinned, typed, non-scorable region. Promotion must be a distinct write that the pruner cannot reverse. - **Refuse the compaction** (raise, do not silently degrade) when the pruner's own log would exceed its budget and the overflow contains any typed constraint. Truncating a constraint log is the exact transition that converts a recoverable loss into a silent one. The boundary is crossed the moment a span's *eviction record* is thinner than the span's *obligation content*. Below that line, compaction is a cache eviction. Above it, compaction is data loss with a plausible-looking score attached. ## Operational Effect Enforcing the boundary converts a silent, drift-inducing failure into a loud, localized one. The agent either pins the constraint (and then the goal-shift at step N+7 re-scores against a buffer that still contains the prohibition, so the edit is blocked by a pre-execution check) or it refuses to compact (and the run halts at 80% occupancy with an explicit `UnsafeCompactionError` rather than proceeding with a corrupted goal state). Both outcomes are observable; the unguarded system produced neither. The secondary effect is on the relevance function itself. Once constraints are typed and pinned, the pruner's scoring domain shrinks to genuinely disposable spans, and the feedback loop described above loses its dangerous term: the surviving buffer no longer changes the *set of obligations* the buffer must satisfy. Score drift can still reorder transcripts, but it can no longer delete the comparator. The residual cost is window pressure. Pinning obligations means the disposable budget is smaller and compaction fires earlier and more often. That is the correct trade: an agent that compacts more frequently but never forgets a prohibition is strictly safer than one that compacts rarely and forgets silently. The failure mode this guards against is not "ran out of context"—it is "ran out of context and did not know which part of itself it had amputated." ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpanType(Enum): TRANSCRIPT = "transcript" # re-fetchable by tool-call id SCRATCH = "scratch" # disposable OBLIGATION = "obligation" # prohibition / identity / schema contract @dataclass class Span: span_id: str span_type: SpanType content: str relevance: float recoverable_by_id: Optional[str] = None class UnsafeCompactionError(RuntimeError): """Raised when a model-driven prune would drop an obligation without a pruner-immune, content-bearing record, or would truncate such a record.""" @dataclass class PinnedStore: """Pruner-immune region. Not scored, not evicted, not subject to window budget.""" obligations: dict[str, str] = field(default_factory=dict) def pin(self, span: Span) -> None: if span.span_type is not SpanType.OBLIGATION: raise UnsafeCompactionError( f"pin() called on non-obligation span {span.span_id}" ) self.obligations[span.span_id] = span.content def prune( buffer: list[Span], pinned: PinnedStore, eviction_log: list[tuple[str, float]], log_budget: int, threshold: float = 0.2, ) -> list[Span]: """Model-driven prune. Evicts spans below `threshold` relevance. Invariant enforced: a span may only be evicted if its loss is recoverable, or if it has first been promoted into the pruner-immune pinned store. The eviction log must never be truncated while it holds obligation records. """ survivors: list[Span] = [] pending_log: list[tuple[str, float]] = [] for span in buffer: if span.relevance >= threshold: survivors.append(span) continue # Below threshold: decide whether eviction is safe. if span.span_type is SpanType.OBLIGATION: # Cannot evict an unpinned obligation — its record would be thinner # than its content. Promote first, then it is safe to drop the payload. if span.span_id not in pinned.obligations: raise UnsafeCompactionError( f"refusing to evict unpinned obligation {span.span_id!r}: " f"eviction record would lose obligation content" ) pending_log.append((span.span_id, span.relevance)) continue if span.recoverable_by_id is not None: # Loss is recoverable from an external store; log the pointer. pending_log.append((span.span_id, span.relevance)) continue if span.span_type is SpanType.SCRATCH: pending_log.append((span.span_id, span.relevance)) continue # TRANSCRIPT with no recoverable id: eviction is unrecoverable loss. raise UnsafeCompactionError( f"cannot evict unrecoverable transcript {span.span_id!r} " f"(no backing store id); relevance {span.relevance}" ) # Guard the log itself: truncation must never drop an obligation record. projected = eviction_log + pending_log if len(projected) > log_budget: overflow = projected[: len(projected) - log_budget] pinned_ids = set(pinned.obligations) for span_id, _ in overflow: if span_id in pinned_ids: raise UnsafeCompactionError( f"log truncation would drop obligation record {span_id!r}; " f"refusing compaction rather than losing the comparator" ) return survivors ```