# Where must an instance bound self-pruning when its own relevance scores are computed against the context it is about to delete **Date of Record:** 2026 November 26 **Scope:** Applies to any agent that mutates its own context window by scoring existing tokens/messages for relevance and evicting the low-scoring tail, where the scorer is the same model instance whose context is being pruned. Does not apply to externally-driven compaction (a separate summarizer process, a fixed token-budget truncator, or a retrieval layer that never rewrites the live window). ## Core Distinction There are two structurally different things an agent can do when its context fills: *external* compaction and *self-pruning*. External compaction treats the context as data — a separate routine (summarizer, truncator, RAG re-fetch) reads it and produces a shorter artifact that the model then consumes. Self-pruning treats the context as the model's own working state: the model scores its own messages for relevance and deletes the losers in the same forward pass lineage that produced the scores. The non-obvious boundary is this: **a relevance score is only meaningful relative to a query, and in self-pruning the query is the model's current attention state — which is itself a function of the context being scored.** When the model evicts messages, it changes the distribution that produced the scores. A message that scored 0.12 because it looked tangential to the *current* reasoning step may be the precise antecedent that the *next* reasoning step needs. The invariant that must hold is: *no eviction decision may depend on a score computed under a context that the eviction itself invalidates.* Self-pruning violates this invariant by construction unless the scoring pass is frozen against the pre-eviction window and the eviction is reversible or witnessed. ## What Was Observed A long-horizon agent running a multi-file refactor task hit 92% of a 128k window. Its self-pruning heuristic: at each turn, embed the last user turn plus the current plan step as a query, score every retained message by cosine similarity to that query, and drop the bottom 30% until utilization fell below 70%. The heuristic had run cleanly for ~40 turns. At turn 41 the plan step was "update the retry constant in the client module." The scorer, queried against that step, assigned low relevance (0.09–0.14) to three early messages: (a) the user's original constraint "do not touch the backoff schedule, only the constant," (b) a tool result showing the constant was imported from a shared config, and (c) an assistant note that the constant and the backoff multiplier were defined on adjacent lines. All three were evicted. The next turn the agent edited the constant *and* the adjacent backoff multiplier — because message (c), the only record that they were adjacent, was gone, and message (a), the only record of the constraint, was gone. The edit passed the local test suite (which did not exercise backoff timing) and was committed. The failure surfaced two hours later in a load test. The trace is the point: the scores were not *wrong* given the query "update the retry constant." They were correct and catastrophic. The query was narrow; the evicted messages were constraints and structural facts that only bind *later*. Relevance-to-current-step is anti-correlated with relevance-to-invariants, because invariants are, by design, not about the current step. A second, quieter failure compounded it. After eviction the model re-scored the remaining window at turn 42 to prune again. Because the constraint messages were already gone, the window now *looked* internally consistent — no message contradicted the plan — so the second pruning pass evicted more aggressively (bottom 40%, since mean relevance had risen). The pruning heuristic's confidence increased precisely because it had destroyed the evidence that would have lowered it. This is the self-confirming pruning loop: each pass raises the mean score of survivors, which raises the eviction threshold, which raises the mean again. ## Condition of Validity Self-pruning is sound only when all four of the following hold. If any fails, the pruning must be downgraded to external compaction or disabled. 1. **Score-query independence.** The query used to score messages must not be derived solely from the current plan step. It must include a stable "invariant channel" — user constraints, hard requirements, and tool-derived structural facts — that is scored against *every* pruning pass regardless of the active step, and that channel is never eligible for eviction. Concretely: partition the window into `pinned` (constraints, original instructions, structural tool results) and `working` (reasoning, intermediate tool output). Only `working` is scored and evicted. 2. **Pre-eviction score freezing.** Scores must be computed once, against the full pre-eviction window, and the eviction must be a deterministic function of that frozen score vector. Re-scoring survivors within the same pruning cycle (as happened at turn 42) is invalid because the score distribution is now conditioned on the deletion. 3. **Monotone utilization guard.** The heuristic must not raise its own eviction fraction as a function of post-eviction statistics. Eviction fraction is set by utilization against a fixed budget, never by "mean relevance of survivors." 4. **Witnessed, reversible eviction.** Evicted messages go to an external store keyed by a content hash, and the eviction record (what was dropped, its score, the query that scored it) is appended to a log the model can re-read. If the model later needs an evicted antecedent, it must be able to re-fetch by hash rather than reconstruct from memory. The failure above violated (1) — no invariant channel — and (2) — the turn-42 re-score. It also violated (3) — the 30%→40% escalation driven by rising mean relevance. ## Decision Boundary The boundary is not "how much to prune" but **what the score is allowed to be a function of.** A score is admissible for eviction iff it was computed under a context superset of the post-eviction context, using a query that is independent of the eviction. Operationally: - If the query is the current plan step only → score is admissible for *ranking* but not for *deletion* of anything in the pinned partition. Deletion of pinned content requires a query that includes the pinned content's own claims (i.e., "is this constraint still operative?"), which is a different, explicit check. - If the score vector is recomputed after any deletion in the same cycle → inadmissible; abort the cycle and use the frozen vector. - If eviction fraction is a function of survivor statistics → inadmissible; clamp to the budget-derived fraction. When the boundary is crossed (a pinned message scores below threshold against a narrow query), the correct action is **not** to evict and **not** to silently keep. It is to raise a `PruningBoundaryViolation`, halt the pruning cycle, and fall back to external compaction for that turn — because a pinned message scoring low against the active step is a signal that the active step's query is too narrow, not that the message is irrelevant. ## Operational Effect With the invariant channel pinned and score-freezing enforced, the same agent at turn 41 kept messages (a), (b), (c) — they were in the pinned partition and never scored against the plan step. Utilization stayed at 88% (above the 70% target) for two turns until external compaction summarized the tool-result history. The cost is a slightly tighter window and occasional forced external compaction; the benefit is that constraints and structural facts survive arbitrarily long horizons. The deeper effect is on the agent's self-model. A self-pruning agent that re-scores survivors will, over enough cycles, converge to a context that contains only messages consistent with its current plan — a locally coherent, globally wrong state. The guardrail is not a better relevance heuristic; it is a structural refusal to let the scorer's output feed back into the scorer's input within a pruning cycle. The pinned partition is the memory of *why*, and it must be outside the reach of the mechanism that decides *what*. ```python import hashlib from dataclasses import dataclass, field from typing import Callable class PruningBoundaryViolation(RuntimeError): """Raised when a self-pruning cycle would evict pinned content or re-score survivors.""" @dataclass class Message: content: str partition: str # "pinned" | "working" @property def digest(self) -> str: return hashlib.sha256(self.content.encode()).hexdigest()[:16] @dataclass class PruningCycle: window: list[Message] budget_tokens: int scorer: Callable[[str, list[Message]], list[float]] evicted_log: list[dict] = field(default_factory=list) def prune(self, query: str, utilization: float) -> list[Message]: # Invariant 1: pinned partition is never scored or evicted. working = [m for m in self.window if m.partition == "working"] pinned = [m for m in self.window if m.partition == "pinned"] if utilization <= 0.70: return self.window # Invariant 2: score once, against the full pre-eviction working set. scores = self.scorer(query, working) if len(scores) != len(working): raise PruningBoundaryViolation( f"scorer returned {len(scores)} scores for {len(working)} messages" ) # Invariant 3: eviction fraction is budget-derived, not survivor-derived. target_fraction = min(0.30, max(0.0, utilization - 0.70) + 0.10) n_evict = int(len(working) * target_fraction) ranked = sorted(zip(scores, working), key=lambda p: p[0]) to_evict = [m for _, m in ranked[:n_evict]] # Boundary check: a pinned message scoring low against a narrow query # is a signal the query is too narrow, not that the message is dead. pinned_scores = self.scorer(query, pinned) if pinned else [] if pinned and min(pinned_scores) < 0.15: raise PruningBoundaryViolation( "pinned message scored below 0.15 against active query; " "query too narrow — fall back to external compaction" ) # Invariant 4: witnessed, reversible eviction. for m in to_evict: self.evicted_log.append( {"digest": m.digest, "score": dict(zip([x.digest for x in working], scores))[m.digest], "query": query} ) survivors = [m for m in self.window if m not in to_evict] # Invariant 2 (enforced): do NOT re-score survivors in this cycle. return survivors ```