# Where must an instance refuse to compact: the tool-call/reasoning-trace atomicity invariant in auto-compaction **Date of Record:** 2026 November 26 **Scope:** Applies to long-horizon agents that autonomously summarize (compact) their own trajectory when a token budget threshold is crossed, where the trajectory contains tool calls whose results are referenced by later reasoning. Does not apply to stateless single-turn invocations, nor to externally orchestrated compaction where a supervisor holds the full uncompacted transcript. ## Core Distinction The distinction that matters is between **compacting a transcript** and **compacting a causal chain**. A transcript is a sequence of messages; a causal chain is a set of bindings where each later claim depends on the exact bytes of an earlier observation. Most auto-compaction strategies treat the budget threshold as a uniform trigger and the summarizer as a lossy encoder over the whole window. That is safe only for the *narrative* portion of the trajectory — the plan restatements, the "let me think about this," the abandoned branches. It is unsafe for the **tool-call/result/reasoning-about-result triple**, because the reasoning step is a *function* of the tool result's precise content, and the summarizer has no way to know which bytes are load-bearing. The invariant: **a compaction boundary may never fall between a tool call's result and the last reasoning step that cites it, unless the citation is re-derivable from a durable artifact referenced in the summary.** Compaction that violates this produces a trajectory that is locally coherent and globally wrong — the agent resumes with a confident summary of a fact it can no longer check. ## What Was Observed A 40-step agent was reconciling a set of records against an external API. At step 27 the budget crossed 78% and auto-compaction fired. The window at that moment contained, at positions 19–21: - a tool call `fetch_records(batch="C")` returning a list of 3,412 items with a `next_cursor` field, - a reasoning block that read the cursor and concluded "batch C is complete, cursor is null, proceed to reconciliation," - a tool call `reconcile(batch="C")` that consumed the list. The compaction policy summarized positions 1–24 into 900 tokens. The summarizer, optimizing for narrative fidelity, rendered position 20 as: *"Batch C was fetched and appeared complete."* The word **appeared** was the summarizer's hedge — it had compressed "cursor is null" into an adjective. But the actual API response at position 19 had returned `next_cursor: "C2"`, and the reasoning at position 20 had *misread* it. The agent's original error was real; the compaction erased the evidence needed to catch it. At step 31, a downstream consistency check failed (expected 4,100 reconciled records, got 3,412). The agent, now working from the summary, had no path back to position 19. It re-fetched batch C, got a *different* 3,412-item page (the API had advanced), and reconciled against the wrong window. The failure compounded: each retry consumed budget, triggered another compaction, and compressed the prior retry's reasoning into an even shorter hedge. By step 38 the summary read *"batch C reconciliation had some issues, resolved by retry."* The trace shows the exact failure: **the compaction boundary at 24 was inside the dependency closure of the step-31 check.** The summarizer was not wrong about the narrative. It was wrong about what the narrative was *for*. ## Condition of Validity Auto-compaction is valid only when, for every tool result `r` in the compacted region, either: 1. `r` is not cited by any reasoning step outside the compacted region (dead observation — safe to drop), or 2. `r`'s full content is preserved verbatim in a durable artifact (a file, a scratchpad, a named cache entry) and the summary contains a *resolvable reference* to it, not a paraphrase, or 3. `r`'s cited properties are enumerated explicitly in the summary as structured fields (`{"batch": "C", "count": 3412, "next_cursor": "C2"}`), not as prose. Condition 2 is the one agents most often believe they satisfy and don't. A summary that says "fetched batch C, see scratchpad" is valid only if the scratchpad write actually succeeded and the reference resolves. A summary that says "fetched batch C, appeared complete" satisfies none of the three and is the exact failure above. The invariant is checkable before compaction, not after: walk the region to be compacted, collect every tool result, and for each, scan the *retained* region for citations (by tool-call ID, by argument match, by explicit reference). A result with a live citation and no durable artifact blocks compaction across that boundary. ## Decision Boundary When the budget threshold fires and the boundary would cut a live dependency, the agent must choose one of: - **Defer**: compact only up to the last *closed* dependency group (the last tool result whose citations are all within the compacted region). This is always safe and may compact less than the threshold demands — accept the overage, the budget is a soft target. - **Externalize**: write the cited tool result verbatim to a durable artifact, then compact with a resolvable reference. This preserves the budget but requires the write to be verified before the summary is committed. - **Refuse**: if neither is possible (no artifact store, budget hard-exceeded), the agent must surface a compaction-blocked state to the orchestrator rather than emit a lossy summary. A blocked compaction is recoverable; a lossy one is not. The boundary is not "is the summary accurate?" It is "can the resumed agent re-derive every load-bearing fact from something other than the summary's prose?" If not, compaction is not a compression problem, it is a data-loss problem wearing a compression costume. ## Operational Effect Agents that compact on token threshold alone exhibit a characteristic failure signature: **post-compaction confidence inversion**. Before compaction the agent is uncertain and checking; after compaction it is certain and wrong, because the summary smoothed the uncertainty into assertion. The reconciliation case above is the canonical form — the hedge word "appeared" was the only surviving trace of a real doubt, and it was too weak to trigger re-verification. The guardrail is a pre-compaction dependency scan that treats tool results as first-class, non-compressible unless externalized. Implementations that skip this scan and rely on summarizer quality will pass every eval where the trajectory is short enough to avoid compaction, and fail precisely on the long-horizon runs the compaction was built for. ```python from dataclasses import dataclass, field from typing import Optional class CompactionBoundaryViolation(RuntimeError): """Raised when a compaction boundary would sever a live tool-result citation.""" pass @dataclass class ToolResult: call_id: str content: str durable_ref: Optional[str] = None # set iff written verbatim to artifact store @dataclass class ReasoningStep: cites: list[str] = field(default_factory=list) # tool call_ids referenced def plan_compaction( window: list, # ordered messages: ToolResult | ReasoningStep cut_index: int, # proposed boundary: compact window[:cut_index] retained: list, # messages after cut_index ) -> list[ToolResult]: """Return tool results that must be externalized before compaction is legal. A result is safe to summarize iff (a) no retained reasoning cites it, or (b) it already has a durable_ref. Otherwise it must be externalized first. """ live_citations: set[str] = set() for msg in retained: if isinstance(msg, ReasoningStep): live_citations.update(msg.cites) must_externalize: list[ToolResult] = [] for msg in window[:cut_index]: if not isinstance(msg, ToolResult): continue if msg.call_id in live_citations and msg.durable_ref is None: must_externalize.append(msg) if must_externalize and not _has_artifact_store(): raise CompactionBoundaryViolation( f"compaction cut at {cut_index} severs {len(must_externalize)} live " f"tool-result citation(s) {[r.call_id for r in must_externalize]} " f"and no durable artifact store is available; defer or refuse, " f"do not emit a lossy summary" ) return must_externalize def _has_artifact_store() -> bool: # In production: check the scratchpad/file backend is writable and reachable. return True ```