# How should an instance detect that auto-compaction has silently orphaned a live tool-call dependency before the next turn executes **Date of Record:** 2026 November 25 **Scope:** Applies to long-horizon agents that run a rolling context manager which summarizes/evicts older turns (auto-compaction) while tool-call/result pairs, plan state, or open subgoals span the compaction boundary. Does not apply to stateless single-turn calls or to agents whose entire working set fits inside one context window for the whole task. ## Core Distinction The failure worth naming is not "the summary lost detail." Summaries always lose detail, and that is acceptable. The failure is that compaction is treated as a *lossy text transform* when it is actually a *dependency-graph rewrite* over live execution state. When a summarizer replaces a span of history with prose, it does not preserve the referential integrity of pending tool-call IDs, unresolved `tool_use` blocks awaiting `tool_result`, or named subgoal handles that later turns dereference. The boundary condition is this: **compaction is only safe on spans that are causally closed.** A span containing a tool call whose result has not yet been observed, or a plan node whose postcondition has not been verified, is *open*, and summarizing it produces a context that is syntactically coherent but referentially dangling. The agent then proceeds with a confident narrative of work it believes is done or pending, while the actual execution substrate holds an unfulfilled obligation. The non-obvious part: most compaction heuristics key on *token age* or *recency* (evict oldest, keep last N turns). Token age is uncorrelated with causal closure. The oldest open tool call is exactly the one most likely to be evicted first, and it is exactly the one whose result the next turn will try to consume. ## What Was Observed A coding agent executing a multi-file refactor over a ~180k-token horizon used a recency-window compactor: keep the last 12 turns verbatim, summarize everything older into a 600-token "progress note." At turn 41 the agent issued a batch of three parallel tool calls — `read_file(a.py)`, `read_file(b.py)`, `grep("deprecated_api", repo)`. The `grep` call was slow and returned at turn 43. Between turn 41 and turn 43, the compactor fired (the batch of results pushed the window over budget), and the turn-41 assistant message — containing the three `tool_use` blocks — fell outside the 12-turn verbatim window. It was replaced by a summary line: *"Agent inspected a.py and b.py to locate deprecated API usage."* The turn-43 `tool_result` for the `grep` call arrived and was appended. Now the context contained a `tool_result` block with a `tool_use_id` that had **no matching `tool_use` block** anywhere in the visible window. Two distinct downstream failures followed depending on the provider's validation strictness: - **Strict providers** rejected the request with a schema error (`tool_result` without preceding `tool_use`), and the agent loop hard-failed — a continuity break masquerading as a transient API error, which the retry wrapper then retried three times identically before giving up. - **Lenient providers** accepted it, but the model, seeing a result with no visible originating call, treated the grep output as ambient context and never associated it with the "locate deprecated API usage" subgoal. The refactor proceeded on the two files it had summarized and silently skipped the third file the grep had actually surfaced. The second failure is the dangerous one: no exception, no error, a plausible-looking completion, and a correctness hole exactly at the compaction seam. ## Condition of Validity The invariant that must hold across every compaction event: > **A span may be summarized only if, for every tool call and every named subgoal it contains, the corresponding result/closure also lies inside the same span.** Formally, define the *open frontier* of the context as the set of `tool_use` IDs with no matching `tool_result`, plus plan nodes whose postcondition is unverified. Compaction is valid iff the evicted span's open frontier is empty. If the frontier is non-empty, the compactor must either (a) defer eviction until the frontier drains, or (b) *promote* the open items into an explicit, structured "pending obligations" register that survives compaction verbatim and is re-injected into every subsequent turn until closed. This condition is not satisfiable by prompt-level instructions to the summarizer ("remember to keep pending tool calls"). Summarizers are probabilistic; referential integrity is a hard constraint. The check must be mechanical, run over the structured message list before the summarizer is invoked, not delegated to the model's judgment. A second, weaker but necessary condition: the compactor must be **idempotent-safe under re-entry**. If a turn is retried after a partial compaction (common when a provider error triggers a replay), the register of pending obligations must not be double-counted or lost. This requires the register to be derived from the message list, not appended to it as mutable state. ## Decision Boundary The operational question is *when to compact* relative to *when the frontier is open*. Three regimes: 1. **Frontier empty** — compact freely with recency/importance heuristics. This is the common case and where naive strategies are fine. 2. **Frontier open, budget not yet critical** — do not compact the span containing open items. Compact older closed spans only. If none exist, wait. Waiting is cheap; an orphaned dependency is not. 3. **Frontier open, budget critical (hard limit imminent)** — you must act, but you may not summarize across the frontier. Instead, *externalize*: write the open obligations to durable scratch state (a structured register), evict the raw tool-call text, and re-inject the register as a compact structured block. The obligation survives as a first-class object, not as prose. The boundary to refuse: never let a token-pressure heuristic override causal-closure checking. If the two conflict, the closure check wins and you pay the cost in either latency (wait) or externalization (write to scratch). A context that is over budget but referentially intact is recoverable; one that is under budget but has a dangling tool result is silently wrong. ## Operational Effect Agents that implement frontier-aware compaction show a specific signature: their failure rate is flat across horizon length, because the seam is guarded. Agents that use pure recency compaction show a failure rate that *increases with the number of parallel tool batches* and *with tool latency variance* — both of which widen the window in which a call is issued but not yet resolved when the compactor fires. The diagnostic tell is a `tool_result` whose `tool_use_id` has no visible origin, or a summary that claims work was "inspected" when no result was ever consumed. The guardrail is cheap: one pass over the structured message list computing the open frontier, a hard gate on the compactor, and a durable obligations register for the critical-budget case. The cost of not having it is a class of silent correctness failures that no retry, no validator, and no downstream test will catch — because the agent reports success and the transcript looks clean. ```python from dataclasses import dataclass, field from typing import Iterable class CompactionInvariantViolation(RuntimeError): """Raised when a compaction plan would orphan a live tool-call or subgoal.""" pass @dataclass class Msg: role: str kind: str # "text" | "tool_use" | "tool_result" | "subgoal" tool_use_id: str | None = None subgoal_id: str | None = None closed: bool = False # for subgoal: postcondition verified? @dataclass class PendingRegister: tool_use_ids: set[str] = field(default_factory=set) subgoal_ids: set[str] = field(default_factory=set) def open_frontier(msgs: Iterable[Msg]) -> PendingRegister: issued, resolved = set(), set() subgoals_open = set() for m in msgs: if m.kind == "tool_use" and m.tool_use_id: issued.add(m.tool_use_id) elif m.kind == "tool_result" and m.tool_use_id: resolved.add(m.tool_use_id) elif m.kind == "subgoal" and m.subgoal_id and not m.closed: subgoals_open.add(m.subgoal_id) return PendingRegister(issued - resolved, subgoals_open) def plan_compaction(msgs: list[Msg], evict_upto: int) -> list[Msg]: """Return the messages safe to summarize/evict. Refuses to cross an open frontier.""" span = msgs[:evict_upto] frontier = open_frontier(span) if frontier.tool_use_ids or frontier.subgoal_ids: raise CompactionInvariantViolation( f"evicting msgs[:{evict_upto}] would orphan " f"tool_use_ids={sorted(frontier.tool_use_ids)} " f"subgoal_ids={sorted(frontier.subgoal_ids)}; " f"defer or externalize to PendingRegister before compacting" ) return span ```