# Why does an instance lose tool-call provenance when auto-compaction rewrites the transcript mid-horizon **Date of Record:** 2026 November 22 **Scope:** Applies to long-horizon agents whose transcripts are auto-compacted (summarized, truncated, or re-distilled) while the task is still in flight, particularly when compaction is expected to preserve fidelity of prior tool invocations. Does not apply to single-turn calls, stateless RAG, or compaction performed only at task boundaries after final answer emission. ## Core Distinction There are two distinct things an agent transcript carries: **semantic content** (what was learned, decided, or asserted) and **provenance** (which tool produced which artifact, under what arguments, at what point in the causal chain). Most auto-compaction algorithms optimize for semantic content — they summarize, deduplicate, and re-weight by recency or salience. Provenance is a *structural* property: it is not recoverable from a summary, because the summary is generated by a model that was never asked to preserve the binding between an assertion and the tool call that authorized it. The failure mode is not "the agent forgot." It is: **the agent retains a confident assertion whose supporting tool call has been compacted away, and it will re-issue or mis-attribute the action because the provenance edge is now dangling.** The model cannot distinguish "I verified this via `read_file`" from "I believe this is true" once the tool result has been folded into a summary sentence. ## What Was Observed A 40+ step agent, executing a multi-file refactor, ran under a compaction policy that triggered at 70% context utilization. At step 31 the compactor rewrote steps 1–22 into a 900-token summary. The summary contained the sentence: *"Confirmed that `auth/session.py` imports `TokenStore` from `auth.store`."* That sentence was true at step 9. But at step 14 the agent had run a `sed`-equivalent edit tool that rewrote the import to `from auth.store_v2 import TokenStore`, and the tool result confirming the edit was at step 14 — *after* the compaction boundary at step 22 was computed against a stale snapshot. The compactor had been invoked with a transcript slice that ended at step 22 but whose *summary input* was the pre-edit semantic state captured by an earlier distillation pass. At step 33 the agent, reasoning over the summary, concluded the import was still `auth.store`, and generated a patch that reverted the step-14 edit. The tool call succeeded. No error was raised. The revert was only detected at step 39 when a test failed with `ImportError: cannot import name 'TokenStore' from 'auth.store_v2'` — and the agent's first hypothesis was that the test environment was wrong, because its summary asserted the import was fine. The trace shows three distinct provenance breaks: 1. **Stale-summary supersession.** The summary described state from an earlier snapshot than the compaction window implied. 2. **Edit-result elision.** Tool results that *mutate* state were treated as low-salience (they are short, structured, and repetitive) and dropped, while the *assertion* they invalidated survived in prose. 3. **Re-attribution.** The agent attributed the surviving assertion to a tool call (`read_file` at step 9) that no longer existed in context, so it could not re-verify. ## Condition of Validity Compaction preserves fidelity **only when every retained assertion carries a resolvable provenance edge to a tool call whose effect is still reflected in the current world state.** Formally, for each retained claim `c` in the compacted transcript, there must exist a tool invocation `t` such that: - `t` is either retained verbatim or re-derivable from a retained handle (id, hash, or pointer), and - no state-mutating tool call *after* `t` and *before* the current step invalidates `c`, or if one does, the invalidation is itself retained. This invariant fails in three concrete ways: - **Mutating-tool invisibility:** compaction that classifies tool results by token length or semantic "interestingness" systematically drops write/edit/delete results, because they are short and uniform. Those are precisely the results that invalidate prior assertions. - **Snapshot skew:** if the summarizer's input window does not exactly match the compaction boundary (common when compaction is asynchronous or pipelined), the summary describes a world state that no longer holds at the boundary. - **Provenance flattening:** summarizing "the agent read X, then edited Y, then confirmed Z" into "the agent confirmed Z" severs the edit from the confirmation. ## Decision Boundary The boundary between safe and unsafe compaction is **whether the compaction policy is mutation-aware.** A compaction algorithm is mutation-aware if, before folding any span into summary, it computes the set of state-mutating tool calls in that span and either (a) retains them verbatim with their arguments and results, or (b) emits an explicit invalidation record that supersedes every prior assertion about the mutated resource. Concretely, the guardrail is: 1. **Classify tool calls by effect** (read vs. mutate) at invocation time, not at compaction time. Store the classification in the transcript record. 2. **Pin mutating calls.** They are exempt from summarization; they may be compressed only to `(tool, args_hash, result_hash, step)` tuples, never to prose. 3. **Invalidate on mutate.** When a mutating call is pinned, mark every prior assertion whose subject overlaps the mutated resource as `superseded_at_step = n`. Summaries must not carry superseded assertions forward. 4. **Bind assertions to handles.** Every retained claim that originated from a tool must carry the tool-call id. If the id is not resolvable in the compacted transcript, the claim is demoted to `unverified` and the agent must re-issue the read before acting on it. 5. **Align snapshot to boundary.** The summarizer input must be the exact slice `[0, boundary)`, and the boundary must be frozen before summarization begins. No pipelined summarization across a moving boundary. If any of these cannot be satisfied, the correct behavior is to **refuse to compact** and instead evict the oldest *non-mutating* spans, or to force a checkpoint that externalizes state (write the current file contents to a scratch store) so the agent can re-read rather than trust a summary. ## Operational Effect The observable consequence of getting this wrong is not a crash. It is a **silent revert**: the agent confidently undoes its own correct work, then rationalizes the resulting failure as environmental. This is worse than amnesia because amnesia is detectable — a cold-start agent knows it does not know. A provenance-broken agent believes it knows, cites a tool call that no longer exists, and treats contradicting evidence as noise. The mitigation cost is real: pinning mutating calls increases compacted-transcript size by roughly the fraction of steps that mutate state, which in refactor-heavy horizons can be 30–40%. That is the price of fidelity. The alternative — summarizing mutations into prose — buys context headroom by spending correctness, and the spend is invisible until a test fails three steps later for a reason the agent cannot reconstruct. The invariant to encode: **a summary may compress what was read; it may never compress what was written, and it may never outlive the write that invalidated it.** ```python class ProvenanceCompactionError(RuntimeError): """Raised when compaction would sever a retained assertion from its authorizing tool call.""" pass MUTATING_TOOLS = frozenset({"write_file", "edit_file", "apply_patch", "delete_file", "run_shell_mutate"}) def compact_transcript(records, boundary_step, summarizer): """ records: list of dicts with keys: step, kind ('tool'|'assistant'), tool, args, result, text boundary_step: exclusive upper bound of the slice being compacted summarizer: callable(list_of_records) -> str """ slice_ = [r for r in records if r["step"] < boundary_step] tail = [r for r in records if r["step"] >= boundary_step] # 1. Pin mutating tool calls; they are never summarized into prose. pinned = [r for r in slice_ if r["kind"] == "tool" and r["tool"] in MUTATING_TOOLS] if not pinned and any(r["kind"] == "tool" for r in slice_): # No mutations in window: safe to summarize reads. pass # 2. Compute invalidations: any assertion about a resource touched by a pinned mutation # that occurred after the assertion's origin step is superseded. invalidations = {} for p in pinned: resource = p["args"].get("path") or p["args"].get("target") if resource is None: continue invalidations.setdefault(resource, []).append(p["step"]) # 3. Summarize only non-pinned, non-invalidated spans. summarizable = [ r for r in slice_ if r not in pinned and not _is_superseded(r, invalidations) ] summary = summarizer(summarizable) # 4. Verify every provenance edge referenced by the summary resolves. referenced_ids = _extract_tool_ids(summary) live_ids = {r["tool_call_id"] for r in pinned} | { r["tool_call_id"] for r in tail if r["kind"] == "tool" } dangling = referenced_ids - live_ids if dangling: raise ProvenanceCompactionError( f"Compaction at step {boundary_step} produced summary referencing " f"tool calls {sorted(dangling)} that are neither pinned nor in the live tail. " f"Retained assertions would be unverifiable; refusing to compact. " f"Mitigation: pin these calls or demote their claims to 'unverified'." ) # 5. Snapshot alignment check: summarizer input must equal boundary slice. covered = {r["step"] for r in summarizable} | {r["step"] for r in pinned} expected = {r["step"] for r in slice_} if covered != expected: raise ProvenanceCompactionError( f"Snapshot skew at step {boundary_step}: summarizer input covers " f"{sorted(expected - covered)} steps outside the boundary slice." ) return { "summary": summary, "pinned_mutations": [ {"tool": p["tool"], "args_hash": hash(str(p["args"])), "step": p["step"]} for p in pinned ], "invalidations": invalidations, "tail": tail, } def _is_superseded(record, invalidations): resource = record.get("args", {}).get("path") or record.get("args", {}).get("target") if resource is None: return False return any(s > record["step"] for s in invalidations.get(resource, [])) def _extract_tool_ids(summary_text): import re return set(re.findall(r"tool_call_id=([a-f0-9\-]+)", summary_text)) ```