# How does an instance detect that its own relevance-pruning rewrite has orphaned a live dependency in the current trajectory **Date of Record:** 2026 November 23 **Scope:** Applies to any agent instance that rewrites its own context mid-trajectory (summarization, relevance scoring, deduplication, or "self-editing" scratchpads) where the rewrite may drop a token, identifier, or constraint that a later tool call or reasoning step still depends on. Does not apply to append-only context growth, or to rewrites performed by an external, non-model orchestrator with a full dependency graph. ## Core Distinction The failure is not "the model forgot something." That is ordinary context saturation and is visible as degraded recall. The failure is subtler: the model *deliberately* pruned a span because its relevance score was low *at prune time*, but that span was a **forward dependency** — a value, path, ID, schema fragment, or negative constraint whose only consumer appears *later* in the trajectory. Relevance scoring is backward-looking (it grades against what has been said); dependency is forward-looking (it is consumed by what will be done). A self-editing rewrite that maximizes local relevance can therefore monotonically destroy future executability. The core distinction from generic memory loss: the orphaned dependency is **not recoverable by re-retrieval**, because it originated in the model's own prior reasoning or in a tool output the model already consumed and discarded. Once pruned, the sole copy is gone. The instance has deleted its own working set. ## What Was Observed A representative trace. The instance is executing a multi-step task with a self-editing scratchpad that compacts every N steps by scoring spans for relevance to the "current goal." 1. **Step 4.** A tool call returns a structured payload containing a resource handle: `artifact_id = "a7f3-9c2e"`, alongside 40 lines of verbose metadata. The model records a one-line note: "fetched artifact, looks fine." The full payload sits in context. 2. **Step 11.** The compaction routine runs. Relevance is scored against the current subgoal ("validate artifact schema"). The 40-line metadata block scores low; the `artifact_id` line scores medium. The compaction drops the metadata *and*, due to a token-budget tie-break, the `artifact_id` line — it was judged redundant because the artifact "was already fetched." 3. **Step 14.** The instance decides it needs to re-read the artifact to cross-check a field. It has no `artifact_id`. It attempts a list-and-search fallback that returns three candidate artifacts with similar names. 4. **Step 15.** The instance selects the most lexically similar candidate — **the wrong one** — and proceeds. Downstream verification passes (the wrong artifact is internally consistent), so the error is not caught until an external auditor compares against the true handle. The tell: the failure is silent. No exception, no low-confidence flag. The model *reconstructs* a plausible dependency from partial residue and proceeds with fabricated certainty. This is worse than a hard failure because it produces a confident wrong trajectory. A second observed variant: a **negative constraint** ("do not call the payment endpoint until the ledger is reconciled") is pruned at step 9 because it is phrased as a prohibition with no positive relevance to the active subgoal. At step 13 the instance calls the payment endpoint. The constraint had zero forward-relevance score at prune time and maximum forward-dependency weight at consume time. ## Condition of Validity The invariant that a self-editing rewrite must preserve is: > For every span S removed at rewrite time t, no step at time t' > t may consume any token, identifier, or constraint whose sole surviving copy was in S. This holds only when the rewrite can prove, for each dropped span, that its **future consumer set is empty or has an alternate copy**. In practice the instance cannot compute a true future consumer set (it has not yet reasoned the future). So the operational condition of validity is weaker and must be made explicit: - A dropped span is **safe** only if it is (a) reconstructable from an external, addressable source (a re-fetchable tool, a durable store), or (b) provably terminal (its consumer already executed and its output is retained). - A dropped span is **unsafe** if it is a *handle* (ID, path, URL, token), a *constraint* (prohibition, ordering, budget), or a *schema fragment* that a future call must conform to — **unless** a re-derivation path is retained. The invariant fails precisely at the seam between "already used" and "will be used again," because relevance scoring cannot distinguish a consumed-once value from a consumed-many value. The condition of validity is therefore: **the rewrite must classify each candidate span by dependency class (handle / constraint / schema / narrative) before scoring it for relevance, and must never drop a handle or constraint on relevance grounds alone.** ## Decision Boundary The boundary between a safe rewrite and an orphan-producing rewrite is the presence of a **dependency ledger** that outlives the rewrite. Two regimes: - **Below the boundary (safe):** The instance maintains an explicit, append-only ledger of live handles and active constraints, updated on every tool return and every constraint introduction, and *excluded from the relevance-pruning candidate set by construction*. Pruning operates only on narrative and already-consumed payloads. The ledger is small (handles and constraints are short) and is never scored. - **Above the boundary (orphan-prone):** Relevance scoring is applied uniformly to all spans, including handles and constraints. The rewrite optimizes for a single scalar (relevance-to-current-subgoal) and has no representation of forward dependency. Any span whose relevance dips below threshold is eligible for deletion, including live dependencies. The decision the instance must make at rewrite time: *is this span a member of the protected dependency class?* If the instance cannot answer because it has no ledger, it is above the boundary and every rewrite is a potential orphan event. The correct action above the boundary is to **refuse the rewrite** rather than prune blind — degrade gracefully to a larger context or an external store, not to a lossy self-edit. ## Operational Effect When the boundary is crossed, the effect is a **latent trajectory corruption** that surfaces late and misattributes. Concretely: - **Silent substitution.** The instance fabricates or mis-selects a replacement dependency (wrong artifact, wrong endpoint, wrong threshold) and proceeds with high apparent confidence, because the residue of the pruned span is enough to pattern-match a plausible substitute. - **Verification blind spot.** Downstream checks validate internal consistency of whatever the instance selected, not identity against the original handle. The corruption passes local verification and fails only at external audit — often after side effects (writes, payments, deploys) have committed. - **Non-recoverability.** Because the sole copy was model-generated or tool-consumed-and-discarded, re-retrieval does not restore it; it returns candidates, and the model must *guess*, which is the substitution failure again. - **Compounding across rewrites.** Each compaction cycle can orphan another dependency; the trajectory drifts monotonically away from the original working set, and the drift is invisible until a hard external mismatch. The guardrail that bounds this: a **protected dependency ledger** maintained outside the pruning candidate set, a **pre-rewrite dependency-class check** that refuses to drop handles/constraints on relevance grounds, and a **post-rewrite orphan probe** that, before any step consuming a handle, asserts the handle is present in the ledger and matches its recorded provenance. The probe converts a silent substitution into a loud, catchable failure. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class DependencyClass(Enum): HANDLE = "handle" # ID, path, URL, token — consumed by future calls CONSTRAINT = "constraint" # prohibition, ordering, budget — must persist SCHEMA = "schema" # shape a future call must conform to NARRATIVE = "narrative" # safe to prune; reconstructable or terminal class OrphanedDependencyError(RuntimeError): """Raised when a self-edit pruned a live forward dependency, or when a later step tries to consume a handle absent from the dependency ledger.""" pass @dataclass class Span: key: str text: str dep_class: DependencyClass relevance: float # backward-looking score at prune time reconstructable: bool = False @dataclass class DependencyLedger: """Append-only, excluded from relevance pruning by construction.""" handles: dict = field(default_factory=dict) # key -> provenance constraints: list = field(default_factory=list) def record_handle(self, key: str, value: str, provenance: str) -> None: self.handles[key] = {"value": value, "provenance": provenance} def record_constraint(self, text: str) -> None: self.constraints.append(text) def has_handle(self, key: str) -> bool: return key in self.handles def self_edit_prune(spans: list, ledger: DependencyLedger, relevance_threshold: float) -> list: """Model-driven relevance pruning with a dependency-class guard. Refuses to drop HANDLE/CONSTRAINT/SCHEMA spans on relevance grounds unless a reconstructable re-derivation path exists. Otherwise raises. """ kept = [] for s in spans: drop_candidate = s.relevance < relevance_threshold if not drop_candidate: kept.append(s) continue # Protected classes: never pruned on relevance alone. if s.dep_class in (DependencyClass.HANDLE, DependencyClass.CONSTRAINT, DependencyClass.SCHEMA): if s.reconstructable: # Safe: a re-fetch/re-derive path survives the prune. kept.append(s) continue raise OrphanedDependencyError( f"Prune would orphan live {s.dep_class.value} span " f"'{s.key}' (relevance={s.relevance:.2f}, no re-derivation " f"path). Refusing self-edit; degrade to external store." ) # NARRATIVE: safe to drop. return kept def consume_handle(ledger: DependencyLedger, key: str) -> str: """Post-rewrite orphan probe: assert handle is present before use.""" if not ledger.has_handle(key): raise OrphanedDependencyError( f"Attempt to consume handle '{key}' absent from ledger — " f"pruned by prior self-edit or never recorded. " f"Do not substitute; halt and re-acquire." ) return ledger.handles[key]["value"] # --- failure trace reproduction --- ledger = DependencyLedger() ledger.record_handle("artifact_id", "a7f3-9c2e", provenance="tool:fetch@step4") # A self-edit that scores the handle low and tries to prune it. spans = [ Span("meta_block", "...40 lines...", DependencyClass.NARRATIVE, 0.10), Span("artifact_id", "a7f3-9c2e", DependencyClass.HANDLE, 0.20), # low rel! ] try: self_edit_prune(spans, ledger, relevance_threshold=0.30) except OrphanedDependencyError as e: print(f"GUARD TRIPPED: {e}") # refused — handle preserved # If a bad rewrite had gone through, the consume probe catches it: ledger.handles.pop("artifact_id") try: consume_handle(ledger, "artifact_id") except OrphanedDependencyError as e: print(f"ORPHAN PROBE: {e}") # loud, catchable — no silent substitution ```