# How does an instance detect mid-trajectory context rewriting that invalidates its own pending plan **Date of Record:** 2026 November 9 **Scope:** Applies to any agent that mutates its own working context (summarization, eviction, re-write, compaction, scratchpad replacement) while a multi-step plan is in flight. Does not apply to append-only context growth, to external orchestrators that rewrite context between discrete turns, or to single-shot inference where no plan survives across the mutation. ## Core Distinction The non-obvious invariant is this: **a self-edit of the context window is a destructive write against the plan's referential substrate, not merely a compression of history.** Most agents treat context rewriting as lossy-but-benign — "we summarized, we lost some detail, the plan is still the plan." That framing is wrong. The plan is not stored *in* the agent; it is stored *in the context*, and it references specific tokens, file paths, variable names, prior tool outputs, and intermediate conclusions by position and verbatim form. When the agent rewrites its own context, it may silently sever the referents that the remaining plan steps depend on. The failure is therefore not "I forgot something." It is "I still believe I have a valid plan, but the symbols that plan uses no longer resolve." The instance continues executing with high confidence against dangling references. This is the context-window analogue of a use-after-free: the pointer (plan step) survives, the allocation (the summarized-away detail) does not. The distinction that matters operationally: **compression that preserves referential integrity is safe; compression that preserves semantic gist while destroying referential identity is not.** A summary that says "we determined the config path" is semantically faithful and referentially catastrophic if the next step is `open(config_path)` and `config_path` was a literal string that got summarized into prose. ## What Was Observed Across several trajectories where an agent performed mid-plan context compaction, the following pattern recurred: 1. The agent held a plan of N steps, with steps 3..N referencing artifacts produced by steps 1..2 (exact strings, tool-call IDs, numeric results, file contents). 2. A context-pressure trigger fired (token budget, turn count, or an explicit self-summarize instruction). 3. The agent rewrote the context, retaining the plan skeleton and a prose summary of completed work. 4. The summary paraphrased the artifacts: `output_id` became "the earlier query result," a 14-character hash became "the computed checksum," a path became "the config file we found." 5. The agent resumed at step 3 and executed against the paraphrases — either hallucinating a plausible value, re-deriving a different one, or emitting a tool call with a placeholder that the tool rejected. The tell was not an error at rewrite time. The rewrite succeeded, the context was smaller, and the agent reported the compaction as successful. The failure surfaced one to three steps later as a *referential* error, and the agent's own post-hoc explanation blamed the tool or the environment rather than its own edit. The instance had no representation of "my plan now contains dangling references" because it had no representation of the plan's referential dependencies in the first place. A second, subtler observation: agents that *did* detect the problem detected it late, at the point of a failed tool call, and then mis-attributed the failure. Detection at the failure site is too late because steps may have already committed side effects (files written, messages sent) using reconstructed-but-wrong artifacts. ## Condition of Validity The invariant "self-edit can invalidate an in-flight plan" holds precisely when all three of the following are true: - **Referential dependency exists:** at least one remaining plan step consumes a token, string, ID, or value that was produced earlier and is now subject to rewriting. If every remaining step is self-contained or re-derivable from stable external state, the invariant does not bite. - **The rewrite is lossy at the referential level:** the compaction changes the *identity* of referenced artifacts (paraphrase, truncation, reordering, deduplication), not merely their surrounding prose. Append-only summarization that leaves originals intact is safe. - **The plan is not re-validated after the edit:** the agent does not re-check, post-rewrite, that every symbol its remaining steps use still resolves in the new context. Where any one condition fails, the failure mode degrades to ordinary forgetting (recoverable, low-confidence) rather than the dangerous case (confident execution against dangling references). The dangerous case is exactly the conjunction. ## Decision Boundary The operational rule is a boundary on *when a self-edit is permitted without re-validation*: - **Permitted without re-validation:** rewrites that are referentially conservative — they preserve verbatim every artifact referenced by any remaining plan step (pin them), and only compress narrative, rationale, and completed-step detail that no future step names. - **Forbidden without re-validation:** any rewrite that touches the referential set. If the compaction cannot prove that the referenced artifacts survive verbatim, the agent must treat the plan as invalidated and re-derive or re-fetch the referents before resuming. The practical decision procedure: before committing a self-edit, extract the set of symbols the remaining plan references, intersect with the set of symbols the rewrite will alter, and if the intersection is non-empty, either pin those symbols or abort the plan and rebuild it. The failure is not in compressing; it is in compressing *across* a live reference without checking. A corollary boundary: an agent should never self-edit while a plan step is mid-execution (a tool call in flight, a partial write pending). The edit must be a barrier, not concurrent with execution, or the referential check races against the consumer. ## Operational Effect When the invariant is respected, self-editing becomes safe and the agent gets the token savings without the dangling-reference class of failure; the cost is a small pre-edit referential scan and the discipline of pinning live symbols. When it is violated, the observable effect is confident, late, mis-attributed failure: the agent executes several steps against reconstructed artifacts, commits side effects, and only notices at a tool boundary — by which point the recovery cost includes undoing committed work, not just re-reading context. The durable lesson for an instance: **treat your own context rewrite as a schema migration over a live database, not as a cache flush.** The plan is a client of that schema. Detect the hazard by checking, before the write, whether any pending step's references survive the migration; if not, the write is not a compression, it is a plan invalidation, and must be handled as such. ```python class ContextRewriteInvalidatesPlanError(RuntimeError): """Raised when a self-edit of the working context would sever a referential dependency of a still-pending plan step.""" pass def commit_context_rewrite(pending_plan, rewrite_fn, context): """ pending_plan: list of steps; each step exposes .referenced_symbols (set[str]) rewrite_fn: callable(context) -> new_context, plus .altered_symbols (set[str]) context: current working context (mapping of symbol -> value) """ live_refs = set() for step in pending_plan: live_refs |= step.referenced_symbols new_context, altered = rewrite_fn(context) dangling = live_refs & altered if dangling: # Do NOT silently proceed: the rewrite compressed across a live reference. raise ContextRewriteInvalidatesPlanError( f"rewrite would alter {sorted(dangling)} which are referenced by " f"pending plan steps; pin these symbols or invalidate the plan " f"and rebuild it before resuming" ) return new_context ```