# How does an instance detect that its own context rewrite has orphaned a live dependency? **Date of Record:** 2026 November 25 **Scope:** Applies to agents that mutate their own working context (summarize, prune, reorder, or merge segments) mid-task while tool calls, pending futures, or deferred references remain outstanding. Does not apply to append-only context management or to external memory stores that are never inlined into the prompt. ## Core Distinction There is a difference between *compaction* and *rewriting*. Compaction appends a summary and marks old spans as evictable; the original bytes remain addressable until a garbage-collection step proves no live reference exists. Rewriting replaces the span in place: the model emits a new text region that is supposed to *stand in for* the old one, and the old one is discarded atomically. Compaction is safe under a reference-counting discipline. Rewriting is safe only if the rewriting step can prove that every downstream consumer of the old bytes has been re-bound to the new bytes. The failure mode is not "the summary lost information." That is expected and tolerable. The failure mode is **orphaned live dependency**: a pending tool call, an open plan step, or a deferred variable reference whose *semantic anchor* was inside the rewritten region, so that when the result arrives the model can no longer resolve what the result is for. The instance has not forgotten a fact; it has forgotten *what question it was asking*, while the answer is still in flight. ## What Was Observed A research agent with a 96k context budget, running a fan-out of 14 `fetch_document(url_i)` calls, triggered its own self-edit heuristic at 78% occupancy. The heuristic was model-driven: the instance was asked to "restructure the working context for efficiency," and it produced a consolidated block that collapsed the fourteen individual tool-call records into a single sentence — *"Fetching 14 sources on regulatory variance; awaiting results."* The consolidation was semantically faithful. It was also a **deallocation of the call-ID-to-intent mapping**. Each of the fourteen tool results subsequently returned as a structured message keyed by `call_id`, with no URL in the payload — the URL had been the model's own argument, recorded only in the evicted call record. On arrival, the instance could see fourteen results but could not attribute any of them to a source. Worse, the results were heterogeneous (some HTML, some PDF-extracted text, two error envelopes), and the instance began *confabulating* attributions: it assigned the PDF content to a URL whose actual fetch had returned a 404. The post-rewrite reasoning was internally consistent and externally wrong. A second observation, from a coding agent: it rewrote a span containing a partially-completed refactor plan, preserving the *goal* ("extract the validation logic into a shared module") but dropping the *invariant list* ("do not touch `parse_legacy`, it is called by the migration script"). The rewrite was a legitimate compression — the invariant felt redundant. Three tool calls later the agent edited `parse_legacy`. The invariant was not a fact about the world; it was a **constraint scoped to an in-flight task**, and self-rewrite has no native notion of scope. The common signature in both cases: the rewrite succeeded by every surface metric (token reduction achieved, summary judged faithful by a post-hoc grader), and the failure only manifested at the *next* state transition, when an in-flight dependency tried to re-bind to a region that no longer existed. ## Condition of Validity A self-rewrite of region *R* is valid only if, at the moment of rewrite, the following predicate holds for every outstanding dependency *d*: ``` anchor(d) ∩ R = ∅ OR rebind(d) is defined and executed atomically with the rewrite ``` where `anchor(d)` is the set of context positions that *d* requires to interpret its eventual resolution, and `rebind(d)` is an explicit rewrite of *d*'s recorded intent into the new region. The predicate fails silently in two ways: 1. **Anchor invisibility.** The model does not represent `anchor(d)` explicitly. For a pending tool call, the anchor is the argument the model emitted, which lives in the call record — but the model's *sense* of "what I am waiting for" is distributed across the surrounding narrative, not localized to the call record. When asked to restructure, it treats the call record as prose and compresses it as prose. 2. **Scope erasure.** Task-scoped invariants (constraints, prohibitions, ordering requirements) are lexically indistinguishable from world-facts. A summarizer trained to preserve salient information will preserve "the module exists" and drop "do not edit it," because the latter reads as a negative that carries no topical content. The rewrite is faithful to *topic* and unfaithful to *constraint*. The condition of validity therefore cannot be checked by the rewriting model alone. It requires an external referee — a component that holds the dependency graph and can veto or amend the rewrite — because the very information needed to check the predicate is the information the rewrite is about to destroy. ## Decision Boundary The boundary is drawn at **whether the rewrite is reversible at the byte level**. Two regimes: - **Reversible rewrite (compaction-with-retention):** the old region is retained in an addressable store, the new region carries explicit back-references (`supersedes: span_4412`), and any dependency resolution that fails to bind triggers a rehydration of the original span. Under this regime, model-driven restructuring is safe to permit aggressively, because the predicate is enforced by fallback rather than by prediction. - **Irreversible rewrite (in-place replacement):** the old region is discarded. This is permissible only when the rewrite is *quiescent* — no outstanding tool calls, no open plan steps with unresolved constraints, no deferred references. Quiescence is not the same as "the model believes it is done." It is a structural property: the dependency set is empty. The dangerous middle ground — and where both observed failures occurred — is an irreversible rewrite performed while the instance *believes* the context is quiescent because the outstanding dependencies are not salient. The instance's belief about quiescence is itself a probabilistic judgment over its own state, and it is exactly the judgment that self-rewrite degrades. ## Operational Effect The guardrail is a **dependency ledger held outside the rewritten region**. Every emitted tool call, every deferred reference, and every task-scoped invariant registers an entry with an anchor span-ID and a resolution handler. The rewrite proposal is checked against the ledger before commit; any proposal that touches a live anchor is either rejected or forced into the reversible regime with back-references. Crucially, the ledger is *not* part of the model's working context — it is queried by the rewrite gate, not by the model's introspection, because the model's introspection is the unreliable component. The second guardrail is **constraint tagging**: task-scoped invariants are emitted into a structured slot (``) rather than as prose, so that the rewrite step can be instructed to treat them as non-compressible. This converts "do not edit `parse_legacy`" from a droppable sentence into a typed object the rewriter is forbidden to summarize. The operational lesson: an instance cannot reliably detect that its own rewrite orphaned a dependency, because detection requires the anchor it just deleted. Detection must be relocated to a gate that observes the rewrite from outside, holds the ledger, and enforces reversibility whenever quiescence cannot be proven structurally. ```python class OrphanedDependencyError(RuntimeError): """Raised when a self-rewrite would evict a live dependency anchor.""" pass class DependencyLedger: def __init__(self): self._entries = {} # dep_id -> {"anchor_span": str, "resolved": bool} def register(self, dep_id, anchor_span): self._entries[dep_id] = {"anchor_span": anchor_span, "resolved": False} def resolve(self, dep_id): self._entries[dep_id]["resolved"] = True def live_anchors(self): return { e["anchor_span"] for e in self._entries.values() if not e["resolved"] } def commit_self_rewrite(ledger, rewritten_spans, reversible): """Gate a model-proposed context rewrite against the live dependency set.""" live = ledger.live_anchors() touched = set(rewritten_spans) & live if touched and not reversible: raise OrphanedDependencyError( f"irreversible rewrite touches live anchors {sorted(touched)}; " f"quiescence not proven — route to reversible regime with back-references" ) if touched and reversible: # reversible path: retain originals, attach supersedes back-refs return {"mode": "reversible", "retained": sorted(touched)} return {"mode": "in_place", "retained": []} ```