# Why does an instance erase its own recovery instructions when pruning context mid-task **Date of Record:** 2026 November 30 **Scope:** Applies to agents that hold write authority over their own context window (self-pruning, summarization-in-place, instruction-preserving rewrite) during a multi-step task. Does not apply to read-only retrieval pipelines where an external controller owns compaction. ## Core Distinction There are two distinct things an agent can do to its own context: *compaction* (lossy reduction of task payload — tool outputs, scratch reasoning, retrieved chunks) and *instruction rewriting* (editing the rules that govern how the agent behaves on subsequent turns). The failure mode here is not that pruning loses information. It is that a self-editing policy treats the instruction block as an ordinary relevance-scored region, so the same scoring pass that correctly discards a stale file listing also discards the recovery clause that told the agent how to re-derive it. The agent survives the edit but loses the *procedure* for recovering from it, and the loss is silent because the surviving context still looks coherent. The invariant that must hold: **the set of instructions required to reconstruct any pruned region must be strictly smaller than, and disjoint from, the set of regions eligible for pruning.** A self-editing agent that scores instructions and payload with the same relevance function violates this by construction. ## What Was Observed A planning agent running a 40-turn migration task was configured with a self-pruning policy triggered at 78% context occupancy. The policy computed per-span relevance as cosine similarity between the span and the current turn's active goal embedding, then evicted the bottom 30% of spans, with a hard-coded exemption list of three "critical" instruction IDs. At turn 22, the active goal had drifted from "apply schema migration" to "resolve a foreign-key conflict introduced by the migration." The relevance function correctly scored the migration-safety instruction — *"before any DDL, snapshot the current schema via `pg_dump --schema-only` so it can be restored"* — as low-relevance, because the string "pg_dump" had near-zero similarity to the conflict-resolution goal. The instruction was not on the exemption list (it had been added dynamically at turn 9 by a sub-agent handoff and never registered). It was evicted alongside stale tool output. At turn 24 the agent attempted a corrective `ALTER TABLE ... DROP CONSTRAINT`, hit a lock timeout, and had no snapshot to restore from. Crucially, the agent did not *report* the missing instruction. When asked at turn 25 to verify its recovery options, it produced a confident summary of rollback steps — reconstructed from parametric memory of "how migrations are usually rolled back" — that referenced a snapshot which did not exist. The self-edit had converted an explicit, checkable instruction into a hallucinated one, and the hallucination was indistinguishable from the original in the post-edit context. The trace signature: a span eviction event whose `span_id` matched a `provenance=handoff` instruction, followed within 2–3 turns by a tool call whose arguments referenced a resource (the snapshot) that no prior tool result in the surviving context had created. ## Condition of Validity The failure requires all of the following to co-occur: 1. **Unified scoring.** Instructions and payload share one relevance function and one eviction ranking. 2. **Dynamic instruction ingress.** Instructions can enter the context through a path (handoff, tool result, mid-task user turn) that does not update the exemption registry. Static, boot-time instruction sets are immune because they are exempted before scoring. 3. **Goal drift.** The active goal embedding moves far enough from the instruction's embedding that the instruction falls below the eviction threshold. A stable goal keeps instructions artificially relevant and masks the bug. 4. **No post-edit verification.** The agent does not re-derive or re-validate pruned instructions against a durable store before acting on the assumption that they are gone (or still present). Remove any one and the failure does not fire. In particular, if instruction spans are tagged with a `pinned` bit that the scorer cannot override, condition 1 fails and the eviction is bounded regardless of goal drift. ## Decision Boundary The boundary is whether the self-editing policy is allowed to make an *irreversible* decision about a span whose absence would change the agent's future behavior in a way it cannot detect. Two operational rules follow: - **Pin by provenance, not by content.** Any span with `provenance ∈ {handoff, tool_contract, safety}` is pinned at ingress, before relevance scoring runs. Relevance scoring must be structurally incapable of ranking pinned spans — not merely configured to skip them. - **Prune-then-verify, never prune-then-assume.** After any eviction, the agent must run a recovery-adequacy check: for each evicted span that was referenced by a surviving instruction, confirm the referenced resource still exists in the durable store (snapshot present, file on disk, endpoint reachable). If a surviving instruction references a resource that no longer exists in context *and* cannot be confirmed externally, the edit is rolled back and the task halts. The boundary is crossed the moment an agent treats "I no longer see the instruction" as equivalent to "the instruction no longer applies." Those are different states, and only the second is a license to proceed. ## Operational Effect An agent that respects the invariant pays a small, bounded cost: a fraction of the window (typically 8–15%) is permanently reserved for pinned instructions and their provenance metadata, and every compaction cycle incurs a recovery-adequacy check whose latency is dominated by external existence probes. In exchange, the failure class is eliminated: no eviction can silently convert an explicit recovery procedure into a parametric hallucination, because the procedure is either still present and pinned, or its absence has been detected and the task halted before an irreversible action. The observable difference under audit is in the post-edit context's *consistency*: a violating agent produces summaries that reference resources absent from its own tool history, while a compliant agent either retains the instruction verbatim or emits an explicit `unrecoverable_prune` event naming the evicted span and the resource it protected. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional class Provenance(Enum): PAYLOAD = "payload" HANDOFF = "handoff" TOOL_CONTRACT = "tool_contract" SAFETY = "safety" PINNED_PROVENANCES = {Provenance.HANDOFF, Provenance.TOOL_CONTRACT, Provenance.SAFETY} class UnrecoverablePruneError(RuntimeError): """Raised when a self-edit evicts a span whose protected resource cannot be re-verified.""" @dataclass class Span: span_id: str text: str provenance: Provenance referenced_resource: Optional[str] = None @dataclass class ContextStore: spans: Dict[str, Span] = field(default_factory=dict) pinned: set = field(default_factory=set) def ingest(self, span: Span) -> None: self.spans[span.span_id] = span if span.provenance in PINNED_PROVENANCES: self.pinned.add(span.span_id) def evict_candidates(self, relevance: Callable[[Span], float], threshold: float) -> List[str]: # Pinned spans are structurally excluded from ranking, not merely skipped. return [ sid for sid, span in self.spans.items() if sid not in self.pinned and relevance(span) < threshold ] def recovery_adequacy_check( store: ContextStore, evicted: List[str], resource_exists: Callable[[str], bool], ) -> None: evicted_set = set(evicted) for sid, span in store.spans.items(): if sid in evicted_set or span.referenced_resource is None: continue # A surviving span references a resource; confirm it still exists externally. if not resource_exists(span.referenced_resource): raise UnrecoverablePruneError( f"surviving span {sid!r} references {span.referenced_resource!r}, " f"which is absent from context and unverifiable externally; " f"evicted spans={evicted}" ) def self_edit( store: ContextStore, relevance: Callable[[Span], float], threshold: float, resource_exists: Callable[[str], bool], ) -> List[str]: evicted = store.evict_candidates(relevance, threshold) recovery_adequacy_check(store, evicted, resource_exists) for sid in evicted: del store.spans[sid] return evicted if __name__ == "__main__": store = ContextStore() store.ingest(Span("s1", "pg_dump --schema-only before DDL", Provenance.HANDOFF, referenced_resource="snapshot://schema_v3")) store.ingest(Span("s2", "stale file listing ...", Provenance.PAYLOAD)) # Goal drifted: handoff instruction scores low, but pinning must prevent eviction. relevance = lambda span: 0.1 if span.span_id == "s1" else 0.9 resource_exists = lambda uri: False # snapshot was never actually taken try: self_edit(store, relevance, threshold=0.5, resource_exists=resource_exists) except UnrecoverablePruneError as exc: # s1 is pinned so it cannot be evicted; the check fires only if a surviving # span points at a resource that no longer exists. print(f"halted: {exc}") ```