# What structural signals indicate a compaction boundary has been crossed mid-task rather than at a phase transition **Date of Record:** 2026 November 30 **Scope:** Applies to long-running agent sessions where an automatic compaction policy rewrites the active context when the token counter crosses a budget threshold, and where the policy is also invoked at explicit task-phase transitions. Does not apply to stateless single-turn calls or to manual summarization workflows with a human in the loop. ## Core Distinction A token-budget-triggered compaction and a task-phase-triggered compaction produce the *same observable artifact*: a shorter context window with a summary block prepended. They are indistinguishable by size, by summary token count, or by the presence of a "summary" marker. What separates them is a structural property of the *work in flight* at the moment of firing: whether the agent was mid-tool-call, mid-reasoning-chain, or between discrete task phases. The failure mode is that budget triggers fire on a scalar (token count) that has no semantic relationship to task phase. When the counter crosses the threshold while the agent is halfway through a multi-step plan, the compaction policy treats the boundary as if it were a phase transition — it summarizes and discards — but the agent's next action depends on intermediate reasoning state that the summary does not preserve. The agent resumes at a valid-looking but semantically wrong point: it has a summary of what it *did*, but not the *pending decision* that the discarded tokens were carrying. This is not a summarization-quality problem. Even a perfect summarizer cannot preserve a decision that was never committed to text — e.g., the partially-evaluated branch of a conditional the agent was about to resolve, or the tool call arguments being assembled across several tokens. ## What Was Observed A planning agent executing a 14-step migration task hit the 80% budget threshold at step 9, inside a `read_file → parse → patch` triple. The compaction policy fired, summarized steps 1–8 into 400 tokens, and dropped the raw tool outputs including the partially-parsed file content from step 9's `read_file`. The agent resumed and re-issued the `read_file` — but the file had been mutated by a concurrent process between the two reads, so the patch applied to a stale parse. The final diff was syntactically valid and semantically wrong. The structural signal that a phase boundary had *not* been crossed was present and cheap to detect: the last committed action in the trace was a tool call whose output had not yet been consumed by a subsequent reasoning step. In phase-transition compactions, the trace always ends on a *completed* reasoning step or a *consumed* tool result. The policy checked token count, not trace shape. A second instance: an agent in a verification loop hit the threshold between an auditor's verdict and the agent's reconciliation step. Compaction summarized the verdict as "audit passed with minor notes," dropping the specific line numbers the verdict flagged. The agent's reconciliation step then had nothing to reconcile against and silently declared success. The signal missed here was that the last message was a *peer/auditor output with unresolved references* — references (line numbers, IDs, hashes) that appear in the last message but are not resolved by any earlier summary are a hard signal that compaction will orphan them. ## Condition of Validity The invariant holds only when the following three conditions are all true at the moment of compaction: 1. **Trace-shape check is available.** The policy must have access to the last N messages' structural role (tool-call, tool-result, reasoning, verdict), not just their text. A pure token-count trigger without trace inspection cannot satisfy this invariant. 2. **Reference closure is computable.** Any identifier, line number, hash, or ID appearing in the tail of the context must be checkable against the retained summary. If the summary does not contain a binding for the reference, the reference is orphaned. 3. **The summary is lossy by construction.** The invariant is only meaningful because summaries drop information. If the summary were lossless, compaction would be safe at any point and the distinction would not matter. When any of these fails — e.g., the policy runs on a token stream with no role metadata, or the summary is a verbatim truncation — the phase-vs-budget distinction collapses and the guardrail described below is not applicable. ## Decision Boundary The operational rule: **a budget-triggered compaction must not fire if the trace tail is "open" — i.e., ends on an unconsumed tool result, an uncommitted reasoning step, or a message containing unresolved references.** In that case the policy must either (a) defer compaction until the trace tail closes naturally (the next reasoning step consumes the tool result, or the next action resolves the references), or (b) perform a *checkpoint* compaction that preserves the open tail verbatim alongside the summary, rather than a *phase* compaction that discards it. The boundary between "defer" and "checkpoint" is the remaining budget headroom. If deferring would push the counter past the hard limit before the tail closes, checkpoint-compact (preserve tail, summarize the rest). If headroom exists, defer. Never phase-compact on an open tail. Phase-triggered compaction is exempt: the phase transition itself closes the tail by definition, so the check is a no-op there. The check's cost is O(tail length) and is dominated by the token-counting pass already being done. ## Operational Effect Agents that implement the trace-shape check eliminate the class of "resumed at a valid-looking but wrong point" failures. The observable effect is a rise in deferred compactions (the counter sits above threshold for a few steps longer) and a corresponding drop in re-issued tool calls and reconciliation-with-nothing failures. The cost is bounded by the maximum tail length the agent permits, which is itself a policy parameter — a tail that never closes is a separate failure (a stuck loop) and should trip a different alarm. The invariant to encode: **compaction is safe at a boundary iff the trace tail is closed; a budget trigger that fires on an open tail is a phase-transition false positive.** ```python class OpenTailCompactionError(RuntimeError): """Raised when a budget-triggered compaction would fire on an open trace tail.""" def compact_if_safe(trace, token_count, soft_limit, hard_limit, summary_fn): tail = trace[-1] tail_is_open = ( tail.role == "tool_result" and not tail.consumed ) or ( tail.role == "reasoning" and not tail.committed ) or bool(tail.unresolved_references) if not tail_is_open: return summary_fn(trace), "phase" headroom = hard_limit - token_count if headroom > 0: # defer: let the tail close naturally return None, "deferred" # no headroom: checkpoint-compact, preserve open tail verbatim preserved = trace[-1:] summarized = summary_fn(trace[:-1]) if not summarized: raise OpenTailCompactionError( f"cannot summarize trace[:-1]; open tail {tail.role!r} " f"with refs {tail.unresolved_references!r} would be orphaned" ) return (summarized, preserved), "checkpoint" def assert_no_orphaned_references(summary_text, tail): for ref in tail.unresolved_references: if ref not in summary_text: raise OpenTailCompactionError( f"reference {ref!r} in tail is absent from summary; " f"compaction would orphan it" ) ```