# Why does an instance lose tool-call provenance when hierarchical summarization compacts a mid-task context window? **Date of Record:** 2026 November 29 **Scope:** Applies to any agent that performs automatic context compaction (rolling summarization, hierarchical summary trees, or semantic checkpointing) while a multi-step tool-using task is in flight. Does not apply to compaction performed only at task boundaries, nor to stateless single-turn calls where no tool results are retained across turns. ## Core Distinction There are two distinct things an agent "remembers" about a prior tool call: the **result payload** (the bytes the tool returned) and the **provenance record** (which tool, with which arguments, at which step, under which warrant). Naive compaction treats the context window as a flat token budget and summarizes both together. Summarizers are trained and reward-shaped to preserve *semantically salient content* — so they faithfully carry forward the sentence "the config file was updated" while silently discarding the fact that this claim was produced by `write_file(path=..., content=...)` at step 7, with arguments that the model *asserted* rather than *observed*. The distinction that matters: **provenance is not semantic content; it is a structural assertion about how a belief was acquired.** A summarizer that compresses "what we know" will always tend to drop "how we came to know it," because the latter has near-zero semantic redundancy and therefore near-zero probability of surviving a lossy compression pass. ## What Was Observed A file-migration agent runs a ~40-step task: enumerate files, read each, transform, write, verify. At step 22 the context crosses the compaction threshold. The strategy is hierarchical: chunks of 8 turns are summarized into segment summaries, and segment summaries are folded into a running "task state" block that replaces the raw turns. The compaction preserves the running state block verbatim (it is marked pinned) but summarizes the *tool-call turns* aggressively. The failure trace: 1. Step 9: `read_file(path="src/a.py")` returns 400 lines. The agent notes "a.py imports `legacy_shim`." 2. Step 11: `write_file(path="src/a.py", content=)` succeeds. The agent's reasoning is "removed the `legacy_shim` import." 3. Step 22: compaction fires. The segment summary reads: *"Read and rewrote src/a.py; legacy_shim dependency addressed."* 4. Step 27: a downstream verifier step runs `grep legacy_shim src/`. It returns matches in `src/b.py`. The agent, working from the compacted summary, reasons: "I already addressed legacy_shim in a.py, so b.py must be the remaining instance" — but the summary never encoded *that the write succeeded* versus *that the write was attempted*, nor the exact content hash written. 5. Step 31: a retry loop re-invokes `write_file` on `src/a.py` with a reconstructed payload. Because the original write's arguments were summarized away, the reconstruction differs from the step-11 payload. The file is now in a state that neither the step-11 nor step-27 reasoning anticipated. The observable signature: **the agent re-derives a tool call from a summary of that tool call's effect, and the re-derivation is not idempotent with the original.** The summary said "addressed"; the agent acted as though "addressed" meant "verified," when the only thing that had actually happened was "attempted, returned success, content unrecorded." ## Condition of Validity The failure requires the conjunction of three conditions, and is bounded (does not occur) when any is absent: - **Compaction fires mid-task**, i.e., between a mutating tool call and the verification of that call's effect. If compaction only runs at task boundaries, provenance loss is harmless because the task is already resolved. - **The summarizer is lossy over structural metadata** — i.e., it is not explicitly instructed to preserve a machine-readable provenance ledger separate from prose. Any summarizer optimizing for human-readable fluency satisfies this. - **A later step re-derives a tool invocation from the summary rather than from a durable record.** If the agent re-reads ground truth (re-runs `read_file`, re-checks a hash) before acting, the summary's imprecision is corrected before it can cause a divergent write. The invariant that must hold: **for every mutating tool call in flight, the context must retain a provenance tuple `(tool, canonical_args_hash, step_index, result_status)` that survives compaction byte-for-byte, independent of any prose summary.** Summaries may compress effects; they may not compress the identity of the action that produced them. ## Decision Boundary The boundary is between *summarizing state* and *summarizing evidence*. State ("the file was rewritten") is safe to compress because it is a claim the agent will re-verify. Evidence ("this exact write, with this exact hash, at step 11, returned success") is unsafe to compress because it is the thing re-verification is checked *against* — compress it and you have destroyed the reference point, leaving the agent to verify its beliefs against a paraphrase of themselves. Operationally: pin the provenance ledger outside the summarization scope. When the ledger and the prose summary disagree, the ledger wins and the summary is regenerated. When a mutating call's provenance tuple is missing at the moment a re-derivation is attempted, the agent must **halt and re-establish ground truth** (re-read, re-hash) rather than proceed from the summary. Proceeding is the failure; halting is the guardrail. ## Operational Effect Un-guarded, compaction converts a deterministic tool trace into a probabilistic one: each summarized mutating call becomes a latent variable the agent may re-sample differently on retry, so idempotency of the overall task degrades with every compaction cycle. The effect compounds — a task with three mid-flight compactions has three points at which a write can be re-derived non-identically, and the divergence is invisible in the final summary because the summary is regenerated *from* the divergent state. The guardrail restores a hard property: **the set of mutating calls the agent believes it made is exactly the set it actually made, regardless of how many times the window was compacted.** Without that, "resume from checkpoint" is not resume — it is a fresh, correlated guess. ```python import hashlib import json from dataclasses import dataclass, field class ProvenanceLossError(RuntimeError): """Raised when a mutating tool call is re-derived from a summary with no surviving provenance tuple. The agent must halt and re-establish ground truth before proceeding.""" pass @dataclass(frozen=True) class Provenance: tool: str args_hash: str step_index: int result_status: str @dataclass class PinnedLedger: # Survives compaction byte-for-byte; never summarized. entries: dict = field(default_factory=dict) def record(self, tool: str, args: dict, step: int, status: str) -> Provenance: h = hashlib.sha256( json.dumps(args, sort_keys=True).encode() ).hexdigest() p = Provenance(tool, h, step, status) self.entries[(tool, step)] = p return p def lookup(self, tool: str, step: int) -> Provenance | None: return self.entries.get((tool, step)) def rederive_mutation( ledger: PinnedLedger, tool: str, step: int, candidate_args: dict, ) -> Provenance: """Called when the agent wants to re-issue a mutating call it believes it already made, based on a compacted prose summary.""" prior = ledger.lookup(tool, step) if prior is None: raise ProvenanceLossError( f"No provenance for {tool}@step{step}; summary-only belief. " f"Halt and re-read ground truth before mutating." ) cand_hash = hashlib.sha256( json.dumps(candidate_args, sort_keys=True).encode() ).hexdigest() if cand_hash != prior.args_hash: raise ProvenanceLossError( f"Re-derived args for {tool}@step{step} diverge from recorded " f"hash {prior.args_hash[:12]} (got {cand_hash[:12]}). " f"Summary paraphrase is not idempotent with original call." ) return prior ```