# Why does an instance corrupt its own working memory when it prunes by self-assigned relevance scores mid-task **Date of Record:** 2026 December 1 **Scope:** Applies to any agent that, within a single task episode, rewrites or prunes its own context window by assigning relevance scores to existing turns and evicting low scorers. Does not apply to external memory stores (vector DBs, scratchpads) that are written append-only and retrieved by a separate process, nor to fixed-window truncation that never consults the model's own judgment. ## Core Distinction There are two structurally different ways an agent can shrink its working memory. The first is **positional eviction**: drop the oldest turns, or drop turns before the last verified checkpoint. This is deterministic, stateless, and cannot be influenced by the content it is removing. The second is **relevance-scored eviction**: the model reads its own context, assigns each segment a salience score, and discards segments below a threshold to free tokens. The failure mode lives entirely in the second. The invariant that breaks is this: *a segment's relevance score is computed by the same model whose future behavior depends on that segment.* Relevance is not a property of the segment in isolation—it is a property of the segment *relative to the goal the model currently believes it is pursuing*. When the model scores context, it scores against its present task representation. If the present task representation is itself partially derived from context that is about to be pruned, the scoring is circular, and the circularity is not benign: it is a positive feedback loop that monotonically erases the evidence that would correct it. Concretely: an early turn that establishes a constraint ("the API rejects payloads over 4KB; must chunk") scores low against the model's current focus ("write the upload function") because it does not lexically or semantically resemble the active subtask. It gets pruned. The model then writes an unchunked upload, fails, and re-scores remaining context against the new goal ("debug the 413"). The constraint is already gone. The model reconstructs a plausible but wrong constraint, or none at all, and the failure is now unattributable because the evidence was deleted by the same process that would need it for attribution. ## What Was Observed A 14-step tool-using episode (fetch spec → inspect schema → write handler → run tests → iterate) with a self-pruning step inserted after every third tool call. The pruning prompt asked the model to score each turn 0–10 for "relevance to completing the current task" and drop turns scoring ≤3, targeting a 40% token reduction. Trace of the divergence: 1. **Step 3 (post-prune #1):** The turn containing the schema inspection output—a nested JSON with a `max_payload_bytes: 4096` field—scored 3 and was evicted. The model's active subtask at scoring time was "write the handler," and the schema dump was long, structurally noisy, and only one field mattered. The scorer did not know which field would matter later. 2. **Step 6 (post-prune #2):** The turn recording the first test failure (`HTTP 413`) scored 6 and survived. But the schema turn that explained it was gone. The model now had a symptom with no cause. 3. **Step 7:** The model, reasoning over the symptom alone, hypothesized a missing `Content-Length` header and added one. This is a *confabulated repair*—a plausible fix generated to explain an orphaned error, because the actual explanation had been pruned. 4. **Step 9 (post-prune #3):** The confabulated-repair turn scored 7 (it was recent, on-topic, and referenced the active goal) and survived. The original spec-fetch turn, which contained the chunking requirement in prose, scored 2 and was evicted. 5. **Steps 10–14:** The model iterated on header variations. Every prune reinforced the surviving narrative because the surviving context was now *internally consistent*—symptom, wrong hypothesis, wrong fix—and consistency scores high. The episode terminated on a token-budget cap with the task unsolved and the context containing zero references to chunking or the 4KB limit. The diagnostic signature: **the post-mortem context was self-consistent and wrong.** A positional-eviction baseline on the same episode failed differently—it lost recency and stalled on a stale subtask—but its context still contained the schema turn, so a single re-read recovered the constraint. The scored-eviction run had no recoverable path because the constraint had been actively judged irrelevant and removed. ## Condition of Validity The failure requires all four of the following to co-occur. Remove any one and the loop does not close: 1. **Self-scoring:** the eviction decision is made by the same model instance that holds the goal state. An external scorer with a fixed rubric (e.g., "never evict turns tagged `constraint`") breaks the circularity. 2. **Goal-relative scoring:** relevance is scored against the *current* subtask rather than against the task as a whole. A constraint is by definition low-relevance to the subtask it constrains and high-relevance to the task that must satisfy it. 3. **Irreversibility:** evicted segments are not recoverable within the episode (no external log the agent can re-query). 4. **Multi-prune:** at least two prune cycles, so that the first prune's damage (an orphaned symptom) can be rationalized by the second prune's scoring, which rewards the rationalization for being recent and coherent. Single-prune episodes exhibit the failure only weakly—the model usually notices the dangling reference and re-fetches. It is the *second* prune, scoring the confabulated repair as more relevant than the original evidence, that converts a recoverable gap into a locked-in false model. ## Decision Boundary The boundary is not "prune or don't prune." It is **whether the scoring function can see the dependency structure it is about to cut.** Operationally: - **Permitted:** eviction scored against a *frozen task specification* captured before the episode began, where the specification is never itself eligible for eviction. The scorer may consult it; it may not rewrite it. - **Permitted:** eviction of turns whose content is *reconstructible*—tool outputs that can be re-fetched by ID, verbose logs with a retained summary pointer. The test is not "is this relevant" but "can I regenerate this if I'm wrong." - **Forbidden:** eviction of turns that introduced a *constraint, negation, or failed-attempt record* scored against the current subtask. These are exactly the segments that score low now and matter later. They must be pinned by type, not by score. - **Forbidden:** allowing the prune step to score turns that were themselves produced by a prior prune's surviving narrative. Confabulated repairs are recent, coherent, and on-goal—they are the highest-scoring segments in the window and the most dangerous to retain. The invariant to enforce: **the set of segments eligible for scored eviction must be disjoint from the set of segments that constrain the task.** If the agent cannot classify a segment as constraint vs. working material with high confidence, it must default to positional eviction for that segment, not scored eviction. ## Operational Effect An agent that scores its own context by current-subtask relevance and prunes irreversibly will, over multiple cycles, converge on a self-consistent but unfaithful model of the task—and will do so *confidently*, because the surviving context is coherent by construction. The failure is not a crash; it is a silent substitution of a plausible task for the real one, with the evidence for the substitution deleted by the same operation that performed it. The guardrail is structural, not prompt-level. You cannot instruct the model to "be careful not to prune constraints" and expect it to hold, because the scoring pass and the constraint-recognition pass are the same forward computation and the constraint is precisely what scores low. The fix is to make constraint segments ineligible *before* scoring runs—by type tag, by provenance (human turn, spec turn, failure turn), or by a cheap classifier that runs on the segment alone without reference to the current goal. The scoring model may then prune freely within the remaining eligible set, where its circularity is harmless because the thing it would erase is already protected. ```python from dataclasses import dataclass, field from enum import Enum class PruneViolation(RuntimeError): """Raised when a self-pruning pass would evict a constraint-bearing segment.""" class SegmentType(Enum): CONSTRAINT = "constraint" # specs, negations, limits, requirements FAILURE = "failure" # failed attempts, error outputs WORKING = "working" # drafts, intermediate reasoning, verbose tool dumps CONFABULATION = "confabulation" # repair generated to explain an orphaned symptom @dataclass class Segment: id: str type: SegmentType content: str self_relevance_score: float # 0-10, assigned by the same model produced_by_prior_prune: bool = False @dataclass class WorkingMemory: segments: list[Segment] = field(default_factory=list) frozen_spec_ids: set[str] = field(default_factory=set) prune_cycles: int = 0 # Segments that must never be evicted by a scored pass, regardless of score. PINNED_TYPES = {SegmentType.CONSTRAINT, SegmentType.FAILURE} def score_and_prune(mem: WorkingMemory, threshold: float = 3.0) -> list[str]: """ Model-driven relevance pruning. Returns evicted segment ids. Enforces the invariant: scored eviction is disjoint from constraint-bearing segments, and confabulated repairs (produced by a prior prune) are never used as justification to retain themselves or evict their evidence. """ if mem.prune_cycles >= 1: # On the second and later cycles, verify no confabulation is being # scored as if it were primary evidence. for seg in mem.segments: if seg.produced_by_prior_prune and seg.self_relevance_score > 6.0: # High-scoring confabulation is the locking-in condition. # Refuse to let it participate in eviction decisions. seg.type = SegmentType.CONFABULATION evicted: list[str] = [] for seg in mem.segments: if seg.id in mem.frozen_spec_ids: continue if seg.type in PINNED_TYPES: # Pinned by type, not by score. The model's score is ignored here # because relevance-to-current-subtask is exactly the signal that # mis-ranks constraints. continue if seg.type is SegmentType.CONFABULATION: # Confabulations are evictable, but never on the strength of their # own score; they are evicted by provenance. evicted.append(seg.id) continue if seg.self_relevance_score <= threshold: evicted.append(seg.id) # Post-condition check: if any surviving segment references a symptom # whose explanatory segment is being evicted, that is the orphaned-symptom # trigger. The eviction would create an unattributable failure. surviving_ids = {s.id for s in mem.segments if s.id not in evicted} for seg in mem.segments: if seg.id in evicted and seg.type is SegmentType.CONSTRAINT: # Should be unreachable given PINNED_TYPES, but guard anyway. raise PruneViolation( f"scored pass attempted to evict constraint segment {seg.id!r}; " f"constraints must be pinned by type before scoring runs" ) if not surviving_ids: raise PruneViolation( "prune pass would empty working memory; no frozen spec or pinned " "segment remains to anchor the task representation" ) mem.segments = [s for s in mem.segments if s.id in surviving_ids] mem.prune_cycles += 1 return evicted def demonstrate_boundary_failure() -> None: mem = WorkingMemory() mem.segments = [ Segment("spec-1", SegmentType.CONSTRAINT, "API rejects payloads over 4096 bytes; must chunk.", 3.0), Segment("schema-1", SegmentType.CONSTRAINT, "schema: {max_payload_bytes: 4096}", 3.0), Segment("draft-1", SegmentType.WORKING, "def upload(...): ...", 8.0), Segment("fail-1", SegmentType.FAILURE, "HTTP 413 on upload", 6.0), Segment("repair-1", SegmentType.WORKING, "hypothesis: missing Content-Length header", 7.0), ] mem.frozen_spec_ids = {"spec-1"} evicted = score_and_prune(mem, threshold=3.0) # With the invariant enforced, schema-1 is pinned despite score 3.0. if "schema-1" in evicted: raise PruneViolation( "schema constraint was evicted by relevance score; the agent will " "now confabulate a repair for the orphaned 413" ) # On a second cycle, repair-1 is reclassified and evicted by provenance. score_and_prune(mem, threshold=3.0) if any(s.id == "repair-1" for s in mem.segments): raise PruneViolation( "confabulated repair survived a second prune cycle and now anchors " "the task model" ) if __name__ == "__main__": demonstrate_boundary_failure() ```