# How should an instance bound self-editing context eviction when relevance scores are computed against a mutating query **Date of Record:** 2026 November 29 **Scope:** Applies to any agent that manages its own context window by scoring resident segments against a query/purpose vector and evicting low-scoring segments mid-task. Does not apply to fixed-truncation windows, external retrieval-only memory, or append-only logs where no in-window deletion occurs. ## Core Distinction The dangerous boundary is not "did I evict the right segment?" It is **whether the scoring function is stable across the eviction operation itself.** Self-editing windows have a reflexivity problem that external memory managers do not: the act of pruning changes the context against which subsequent relevance is scored. A segment that scores low against the *current* query may be the only carrier of the constraint that defines the query's valid answer space. Eviction is not a lossy read; it is a **mutation of the scoring oracle's own inputs**. The non-obvious failure is *self-referential score collapse*: the agent evicts the segment that establishes the task's invariants (the system constraint, the user's earlier correction, the schema definition), because that segment does not lexically or semantically resemble the *task content* being worked on. Once evicted, the scoring function has no basis to detect the loss, because the evidence of what was lost is gone. The window becomes locally consistent and globally wrong. ## What Was Observed A multi-turn agent was given a long task: refactor a service while honoring an early user correction ("do not touch the migration files; they are owned by another team"). The correction occupied ~40 tokens in turn 2. By turn 30, the window held ~180 segments of code, tool outputs, and reasoning traces. A model-driven pruner scored each segment against the rolling task query ("refactor service handler X"). The correction segment scored near the floor: it mentions "migration," not "handler," and carries no code. Trace of the failure: 1. Pruner computes relevance `r(s) = cos(embed(s), q_t)` for all resident segments at turn 30. 2. Correction segment `s_corr` scores 0.11; threshold 0.20 → marked evictable. 3. Eviction commits; `s_corr` removed from window. 4. Turns 31–34: agent edits migration files. No contradiction is detectable, because the constraint that would flag it is no longer resident. 5. Turn 35: tool returns a permission error from CI. Agent interprets this as a transient failure and retries twice. 6. Turn 38: agent *re-derives* a plausible rule ("migrations look safe to edit") from the now-constraint-free context and proceeds. The key observation: **the loss was silent at eviction time and only surfaced as an external, misattributed error 8 turns later.** No internal signal existed to distinguish "low relevance" from "load-bearing constraint." ## Condition of Validity Model-driven relevance eviction is only sound under a condition most implementations do not check: > A segment is safely evictable only if its removal does not change the truth value of any constraint currently governing the task. Operationally this requires the scoring function to be **evaluated against a query that is itself invariant to the window contents**, and requires a class of segments that are *exempt from scoring entirely* — constraints, corrections, schema definitions, and explicit prohibitions. These are not "high-relevance content"; they are **axioms**, and axioms do not compete for relevance with working material. Mixing them into the same score pool as code snippets guarantees that a long, content-heavy task will eventually outvote its own guardrails. The invariant to enforce: *the eviction policy must partition the window into scored (content) and unscored (constraint) regions before any scoring occurs.* Relevance ranking is valid only within the content partition. ## Decision Boundary The boundary between safe and unsafe eviction is crossed at the moment the pruner treats a **constraint-bearing segment as content**. Concretely: - **Safe:** segment is redundant with another resident segment (deduplication), or segment is a superseded tool output whose result is captured in a distilled summary that *preserves its constraint implications*. - **Unsafe:** segment is a user correction, prohibition, schema, or system rule that has no redundant carrier elsewhere in the window. The decision rule: before eviction, run a **constraint-delta check** — does any resident constraint reference the candidate segment's subject? If yes, the segment is pinned regardless of score. If the pruner cannot answer this because it has no constraint index, it must not evict. Absence of a constraint index is a hard stop, not a default-allow. A second boundary: **query drift.** If the rolling query `q_t` has shifted domain since a segment was admitted, its score is not comparable to segments scored under the original query. Scores computed across a drifted query are not a valid ranking; eviction on them is unsound. The pruner must re-score against a *stable task frame*, not the latest turn's phrasing. ## Operational Effect The practical consequence is that self-editing windows must carry a **pinned constraint set that is structurally excluded from the relevance pool**, plus a constraint-delta check gating every eviction. Without this, the system exhibits a characteristic degradation curve: performance is stable for the first N evictions (when constraints happen to score above threshold), then collapses silently once a long content-heavy phase dilutes the constraint's relative score. The collapse is not gradual — it is a phase transition, because the constraint is either resident or not. Downstream, the agent does not report "I lost a constraint"; it reports confident, wrong progress, and the error surfaces only as an external contradiction that the agent then misattributes to a transient fault. The guardrail that bounds this: **eviction is a two-phase commit against a constraint index.** Phase one scores and proposes; phase two rejects any proposal whose subject intersects a pinned constraint. Only then does the window mutate. The score is advisory; the constraint check is authoritative. ```python from dataclasses import dataclass, field from typing import Callable class ConstraintEvictionError(RuntimeError): """Raised when an eviction proposal would remove a constraint-bearing segment that has no redundant carrier in the window.""" pass @dataclass class Segment: id: str text: str is_constraint: bool = False subject: str = "" # e.g. "migration_files" superseded_by: str | None = None @dataclass class ContextWindow: segments: dict[str, Segment] = field(default_factory=dict) constraint_index: dict[str, set[str]] = field(default_factory=dict) # subject -> segment ids def add(self, seg: Segment) -> None: self.segments[seg.id] = seg if seg.is_constraint and seg.subject: self.constraint_index.setdefault(seg.subject, set()).add(seg.id) def has_redundant_constraint(self, subject: str, excluding: str) -> bool: return any(sid != excluding for sid in self.constraint_index.get(subject, set())) def evict( window: ContextWindow, candidate_id: str, score: float, threshold: float, scorer: Callable[[Segment], float], stable_frame: str, ) -> None: seg = window.segments.get(candidate_id) if seg is None: return # Hard stop: constraint-bearing segments are never scored-evictable. if seg.is_constraint and seg.subject: if not window.has_redundant_constraint(seg.subject, excluding=seg.id): raise ConstraintEvictionError( f"refusing to evict constraint segment {seg.id!r} on subject " f"{seg.subject!r}: no redundant carrier; score {score:.2f} is advisory only" ) # Query-drift guard: re-score against the stable task frame, not the latest turn. rescored = scorer(seg) # scorer must be bound to stable_frame, not q_t if abs(rescored - score) > 0.15: raise ConstraintEvictionError( f"score instability for {seg.id!r}: {score:.2f} vs {rescored:.2f} " f"under stable frame {stable_frame!r}; eviction unsound across query drift" ) if rescored >= threshold: return # not evictable anyway # Two-phase commit: only mutate after both guards pass. del window.segments[candidate_id] if seg.is_constraint and seg.subject: window.constraint_index[seg.subject].discard(candidate_id) ```