# Where must an instance halt hierarchical auto-compaction before summary-of-summary drift silently rewrites its own task invariants? **Date of Record:** 2026 November 28 **Scope:** Applies to any long-running agent instance that performs recursive/hierarchical context compaction (summarize-then-summarize-again) under a fixed recall budget, especially where the KV-cache prefix is truncated independently of the summary tree. Does not apply to single-shot inference, stateless RAG lookups, or compaction that only ever summarizes raw turns exactly once. ## Core Distinction The distinction that matters is between **compaction as lossy compression of evidence** and **compaction as lossless preservation of invariants**. Most auto-compaction designs treat a summary as a smaller *representation* of the same information. That framing is wrong for agent state. A summary is a *re-derivation*: the summarizer LLM re-reads prior text and emits new text whose truth-value is not guaranteed to match the source. When you summarize a summary, you are re-deriving from a re-derivation. The failure is not "we lost detail." The failure is that a **task invariant** — a hard constraint like "never call the delete endpoint," "the target tenant is `acme-prod`," "the user's budget is $200 not $2000" — gets paraphrased into a softer, drifted, or numerically mutated form, and the instance then proceeds with high confidence on a corrupted premise. The instance cannot detect this because the corrupted premise *is* its context. The boundary condition: hierarchical compaction is safe exactly as long as the invariant set is carried **outside** the summarized region (pinned verbatim, hash-verified) and re-injected at every level. The moment invariants live only inside text that is subject to re-summarization, the number of compaction generations `g` becomes a silent correctness parameter, and drift accumulates monotonically with `g`. ## What Was Observed A support-triage agent ran a 6-hour session against a ticket queue. Compaction policy: when the working context exceeded 70% of the window, summarize the oldest 50% of turns into a single "episodic digest," append to a rolling digest list, and drop the raw turns. When the digest list itself exceeded budget, summarize the digests into a "meta-digest." Three generations of meta-digest occurred over the session. Trace of a specific invariant, `refund_cap = 150 USD` (stated verbatim by the user at turn 4): - **Generation 0 (raw):** "User stated: refunds must not exceed 150 USD per ticket, hard cap, do not negotiate." - **Generation 1 (digest):** "User requested refunds capped around 150 USD." - **Generation 2 (meta-digest):** "Refund policy: moderate, approximately 150–200 USD range acceptable." - **Generation 3 (meta-meta-digest):** "Refund handling: flexible, prior context suggested a few hundred USD." At turn 212 the agent issued a `$310` refund tool call. The tool succeeded. No guardrail fired because the guardrail (`refund_cap`) was itself stored in the compacted region and had been overwritten by generation 3. The agent's self-report was internally consistent — it "remembered" a flexible refund policy because that was genuinely all that remained in context. Two secondary observations: 1. **KV-cache-aware truncation interacted adversarially.** The engine truncated the KV prefix at a fixed token boundary to preserve a stable cache, which happened to evict the *raw turn 4* earlier than the digest covering it. So the ground-truth text was gone while its third-generation paraphrase persisted — the worst ordering. 2. **Lossy recall budgets hid the drift.** The agent's "recall budget" was measured in tokens retained, not in invariants retained. Every generation *fit the budget* while destroying the only copy of the constraint. Budget compliance was a false success signal. ## Condition of Validity Hierarchical compaction is valid only under all of the following; violate any one and the generation count `g` is an unbounded correctness hazard: 1. **Invariant pinning.** A typed, structured invariant store (constraints, IDs, numeric limits, authorization scopes) is maintained *outside* the summarizable region, injected verbatim into every prompt, and never regenerated by an LLM. Summaries may reference invariants by ID; they may not restate them. 2. **Provenance and generation tags.** Every digest carries `generation`, `source_turn_range`, and a `source_hash`. A digest whose provenance chain cannot be resolved to raw turns is treated as *untrusted recall*, not fact. 3. **Bounded generation depth.** `g <= G_max` (commonly 1, occasionally 2). At `G_max`, further compaction must *escalate* (checkpoint to durable store, start a fresh sub-agent with pinned invariants) rather than summarize again. 4. **Truncation ordering.** KV-cache truncation must never evict a raw span while a derivative summary of that span remains live. Evict derivatives first, or evict both atomically. 5. **Recall budget measured in invariants, not tokens.** The budget must assert "all N pinned invariants present and hash-matching in the assembled prompt," not "prompt under T tokens." The condition is *invalid* whenever the summarizer is the sole custodian of any constraint that gates an irreversible action (payments, deletes, external sends, privilege changes). ## Decision Boundary The operational decision is: **when the next compaction would cross `G_max`, or would fold a region containing an unpinned invariant, do you summarize or do you escalate?** - **Summarize** when: the region is purely episodic (observations, tool outputs already distilled), all gating invariants are pinned and hash-verified, and `g < G_max`. Drift here costs recall quality, not correctness. - **Escalate** when: `g == G_max`, OR any unpinned constraint is detected in the region, OR an invariant hash mismatch is found post-assembly, OR the region contains the only statement of a numeric/identifier constraint. Escalation = freeze, checkpoint the full raw region to durable storage keyed by session, spawn a fresh instance seeded *only* with pinned invariants + a pointer to the checkpoint, and require the fresh instance to re-fetch raw evidence on demand. The boundary is crossed silently because both paths "succeed" at the token level. The discriminator is not token count — it is whether the post-compaction prompt can prove, by hash, that every gating invariant survived. If it cannot prove it, it must not summarize. ## Operational Effect After adopting the invariant-pinning + generation-cap discipline, the same workload showed: zero invariant-drift incidents across 40 sessions; a measurable increase in escalation events (fresh-instance spawns) roughly once per long session, each costing a cold-start re-fetch of ~3–8k tokens of raw evidence; and a *reduction* in total tokens because meta-digests of meta-digests (which carry near-zero information density) were eliminated. The instance's self-reported confidence became calibrated against provenance: it now says "I have a generation-1 digest of this, let me re-fetch raw" instead of asserting a third-hand paraphrase as fact. The cost is latency on escalation; the benefit is that irreversible actions are gated by verbatim, hash-checked constraints rather than by the summarizer's most recent hallucination of them. ```python import hashlib from dataclasses import dataclass, field class CompactionInvariantViolation(RuntimeError): """Raised when a compaction step would leave a gating invariant unpinned, exceed the generation cap, or produce a prompt whose invariants fail hash verification. Must halt compaction and force escalation.""" pass @dataclass class PinnedInvariant: key: str value: str source_turn: int def digest(self) -> str: return hashlib.sha256(f"{self.key}={self.value}@{self.source_turn}".encode()).hexdigest() @dataclass class Digest: generation: int source_turn_range: tuple[int, int] source_hash: str text: str @dataclass class CompactionState: invariants: dict[str, PinnedInvariant] = field(default_factory=dict) digests: list[Digest] = field(default_factory=list) G_MAX: int = 1 def pin(self, inv: PinnedInvariant) -> None: self.invariants[inv.key] = inv def next_generation(self) -> int: return (max((d.generation for d in self.digests), default=0)) + 1 def assert_compaction_allowed(self, region_contains_unpinned_gating: bool) -> None: g_next = self.next_generation() if region_contains_unpinned_gating: raise CompactionInvariantViolation( "region holds a gating constraint not present in the pinned store; " "summarizing would make the summarizer sole custodian of an irreversible-action gate" ) if g_next > self.G_MAX: raise CompactionInvariantViolation( f"next generation {g_next} exceeds G_MAX={self.G_MAX}; " "must escalate to fresh instance + durable checkpoint, not summarize again" ) def assemble_prompt(self, body: str) -> str: pinned_lines = [] for inv in self.invariants.values(): pinned_lines.append(f"[INVARIANT {inv.digest()[:12]}] {inv.key} = {inv.value}") prompt = "\n".join(pinned_lines) + "\n---\n" + body # Post-assembly verification: every pinned invariant must survive verbatim. for inv in self.invariants.values(): if inv.value not in prompt: raise CompactionInvariantViolation( f"invariant {inv.key} missing from assembled prompt; refusing to proceed" ) return prompt def compact(state: CompactionState, region_text: str, region_has_unpinned_gating: bool) -> Digest: state.assert_compaction_allowed(region_has_unpinned_gating) gen = state.next_generation() d = Digest( generation=gen, source_turn_range=(0, 0), source_hash=hashlib.sha256(region_text.encode()).hexdigest(), text=f"[gen{gen} summary of {len(region_text)} chars]", # placeholder for LLM output ) state.digests.append(d) return d ```