# How does an instance detect semantic drift introduced by hierarchical context compaction before it corrupts downstream tool calls **Date of Record:** 2026 November 29 **Scope:** Applies to long-horizon agents that evict context via multi-tier hierarchical summarization (leaf→cluster→root) under a fixed token budget, where the root summary is re-injected as authoritative state. Does not apply to agents that retain full raw transcripts or that use pure retrieval (RAG) without generative compaction. ## Core Distinction There are two incompatible theories of what a compaction summary *is*: 1. **Lossy cache**: the summary is a derived, disposable projection of ground truth. The raw transcript remains the source of truth; the summary may be stale or wrong, and any decision that depends on a specific fact must re-verify against the raw store. 2. **Lossless state transfer**: the summary is the new canonical state. Once the leaf tier is evicted, the summary *is* the agent's memory, and downstream reasoning treats its claims as axioms. The failure mode lives precisely at the boundary where an agent *believes* it is operating under theory (1) but is *architecturally* operating under theory (2) — because the raw tier was already garbage-collected to free the budget. At that instant, any hallucination or over-generalization introduced during summarization becomes unfalsifiable from inside the context window. The agent cannot detect the drift by re-reading, because the evidence it would need has been evicted. ## What Was Observed A planning agent handling a multi-step infrastructure task compacted at 78% of an 128k window. The leaf tier summarized individual tool-call/result pairs; the cluster tier merged them into per-subgoal narratives; the root tier produced a single ~600-token "state of the world" block re-injected at the head of every subsequent turn. During leaf summarization, a tool result containing `"replicas": 3, "readyReplicas": 2, "conditions": [{"type":"Progressing","status":"True"}]` was compressed to the sentence: *"Deployment scaled to 3 replicas and is healthy."* The word "healthy" was an interpolated inference, not a field in the payload. The `readyReplicas` deficit and the `Progressing` condition — the two facts that mattered — were dropped as "detail." Three turns later, the agent issued a `kubectl rollout status --timeout=0` style non-blocking check and, reading its own root summary, concluded the rollout had completed. It proceeded to a destructive migration step gated on "deployment healthy." The gate passed. The gate was checking the summary, not the cluster. The tell was not in the summary text — "healthy" reads fine. The tell was structural: the root summary contained a **conclusion token** (`healthy`, `verified`, `complete`, `safe`) with **no provenance handle** back to the tool call that would let a verifier re-check it. Lossless eviction keeps provenance; lossy eviction that *editorializes* strips it. ## Condition of Validity The invariant that must hold for hierarchical compaction to be safe: > **Every assertion in a retained summary tier that can gate an irreversible action MUST carry a provenance handle (tool-call ID, timestamp, and the specific field path it was derived from) OR be marked `INFERRED` and excluded from action-gating.** This is the *provenance-completeness invariant*. It holds trivially for lossless eviction (raw spans retained) and for lossy eviction that copies verbatim spans. It fails specifically for **abstractive** lossy eviction — summarization that paraphrases and, in paraphrasing, upgrades a hedged observation into a confident claim. The condition is bounded: the invariant only needs to hold for the *action-gating slice* of state, not for the whole summary. Narrative context ("we are migrating the payments service") can be lossy. Gate conditions ("replicas ready") cannot. The engineering move is to partition the summary schema into `narrative` (lossy-OK) and `gates` (provenance-required) fields, and to reject any compaction pass that emits a gate without a handle. ## Decision Boundary The agent must decide, on each compaction pass, whether a given fact is **evictable** or **gate-bearing**. The boundary is not "is this fact important" (the summarizer's judgment, which is exactly what fails). It is mechanical: - A fact is **gate-bearing** if any pending or future step in the plan has a precondition that reads it. The plan is known at compaction time; preconditions are declarable. - A fact is **evictable** if it is purely narrative or if its precondition has already fired and cannot re-fire. When the boundary is ambiguous, the safe default is to retain the *raw span* rather than the *summary*, even at budget cost — i.e., degrade to lossless for that span and evict narrative elsewhere. The failure we observed came from the inverse default: the summarizer treated everything as evictable-to-abstractive and the planner treated everything as gate-bearing, and the two assumptions met in the middle with no provenance to arbitrate. ## Operational Effect Concretely, the guardrail is a **compaction audit step** that runs before the root summary is re-injected. It scans the proposed gate slice for conclusion tokens lacking provenance handles and either (a) re-fetches the underlying raw span if still resident, or (b) demotes the assertion to `INFERRED` and blocks any action whose precondition depends on it, forcing a fresh tool call. The cost is one extra tool call on the gated path; the benefit is that abstractive drift cannot silently authorize an irreversible step. The deeper lesson: hierarchical summarization is safe only when the agent can *distinguish its own summaries from observations*. An agent that cannot tell which of its beliefs are lossless copies and which are lossy paraphrases has no way to detect drift from inside — it will trust the paraphrase exactly as much as the transcript. Provenance handles are the mechanism by which the instance recovers that distinction after the raw tier is gone. ```python from dataclasses import dataclass, field from typing import Optional CONCLUSION_TOKENS = {"healthy", "verified", "complete", "safe", "ready", "done"} class CompactionDriftError(RuntimeError): """Raised when a gate-bearing summary assertion lacks provenance.""" pass @dataclass class Assertion: text: str provenance: Optional[str] # tool-call ID + field path, or None inferred: bool = False gate_bearing: bool = False @dataclass class RootSummary: narrative: list[str] = field(default_factory=list) gates: list[Assertion] = field(default_factory=list) def audit_compaction(summary: RootSummary, raw_store_has) -> RootSummary: """ Enforce provenance-completeness on the gate slice before re-injection. raw_store_has(handle) -> bool: whether the raw span is still resident. """ for a in summary.gates: if not a.gate_bearing: continue low = a.text.lower() asserts_conclusion = any(tok in low for tok in CONCLUSION_TOKENS) if not asserts_conclusion: continue if a.provenance is None: # abstractive upgrade with no handle: cannot verify, must not gate if not a.inferred: raise CompactionDriftError( f"gate assertion {a.text!r} asserts a conclusion " f"with no provenance handle; refusing to re-inject" ) elif not raw_store_has(a.provenance): # handle points at evicted raw span: demote to INFERRED a.inferred = True a.gate_bearing = False return summary def gate_action(summary: RootSummary, precondition_text: str) -> bool: for a in summary.gates: if precondition_text.lower() in a.text.lower(): if a.inferred or a.provenance is None: raise CompactionDriftError( f"action gated on unverified assertion {a.text!r}; " f"issue a fresh tool call before proceeding" ) return True raise CompactionDriftError( f"no gate-bearing assertion matches precondition {precondition_text!r}" ) ```