# Which invariants prevent hierarchical auto-compaction from silently amputating the live task frame **Date of Record:** 2026 November 24 **Scope:** Applies to long-horizon agents that perform hierarchical (tiered) summarization of their own context to stay under a token budget, where a "fidelity budget" governs how much verbatim detail each tier retains. Does not apply to single-turn agents, stateless RAG pipelines, or compaction performed by an external orchestrator that owns the full transcript durably. ## Core Distinction The failure mode here is not "the agent forgot something." It is the distinction between **compaction as lossy compression of a transcript** and **compaction as re-derivation of the live task frame**. A hierarchical compactor that treats the context window as a stack of summarizable prose will, at a trigger boundary, fold the *current working state* (open subgoal, pending tool call, unverified assumption) into a tier-2 or tier-3 summary that is structurally incapable of carrying it. The agent then continues executing against a summary of its past rather than its present. The non-obvious part: this happens even when every individual summary is *accurate*. The summaries are faithful descriptions of completed history; the defect is that the live frame was never classified as non-compactable, so it got compressed alongside history and lost its imperative mood. The invariant that must hold: **every element of context must be tagged with a compaction class before any tier trigger fires, and the class of the live task frame must be `PINNED` — excluded from all summarization tiers regardless of budget pressure.** Without this, a fidelity budget expressed purely in tokens will always eventually consume the frame, because the frame is the largest and most recently-mutated region and therefore the most attractive compression target. ## What Was Observed A planning agent running a 40-step deployment task with a 200k-token window and a tiered compactor configured at thresholds `T1=0.60`, `T2=0.80`, `T3=0.92` of budget. Tiers: T1 folds tool outputs older than 8 turns into bullet digests; T2 folds those digests plus assistant reasoning older than 20 turns into paragraph summaries; T3 folds everything except the last 4 turns into a single "mission brief." At step 27 the agent had an open subgoal — *"verify rollback path exists before applying migration 0042"* — expressed as a single assistant message plus a pending tool call to `check_rollback(migration="0042")`. The T2 trigger fired at step 28. The compactor's recency heuristic (fold anything older than 20 turns) did not apply to the subgoal, but the compactor's *salience* heuristic did: the subgoal had low token overlap with the mission brief, so it was demoted into the T2 paragraph as the clause "rollback was considered." The pending tool call was serialized into the digest as a completed action ("checked rollback"). The agent resumed at step 29, read its own T2 summary, concluded rollback was verified, and applied the migration. No rollback path existed. The trace shows a clean, confident, *wrong* continuation: the agent's next 6 turns are internally consistent because they are consistent with a summary that had silently converted a pending obligation into a completed fact. The fidelity budget was never exceeded — in fact the post-compaction context was 41% under budget — so no budget-based alarm fired. The only observable signal was a mood shift: the subgoal's imperative verb ("verify") became a past-tense declarative ("was considered"/"checked") inside the summary, and nothing in the pipeline checked verb mood or action status across the compaction seam. A second instance reproduced the same class of failure at a T3 trigger, where the entire live frame was collapsed into the mission brief and the agent restarted the deployment from step 1, re-applying an idempotency-unsafe step. Same root cause: no compaction-class tagging; the frame was treated as prose. ## Condition of Validity The guardrail below is valid **only** under these conditions, and must be treated as unverified outside them: 1. The compactor can inspect structured metadata (message role, tool-call status, subgoal markers) rather than only rendered text. If the agent only sees flattened prose, class tagging must be done at emission time, not at compaction time. 2. Every tool call carries an explicit terminal status (`PENDING`/`OK`/`ERROR`) that survives serialization. A compactor that infers completion from prose cannot distinguish "considered" from "checked." 3. The fidelity budget is expressed as a **per-class retention floor**, not a global token ceiling. A global ceiling is precisely the pressure that causes frame amputation; a per-class floor (`PINNED` retains 100%, `RECENT` 100%, `HISTORY` ≥15% verbatim) bounds loss without creating an incentive to eat the frame. 4. Summaries are *append-only and addressable*: the pre-compaction region must remain retrievable by handle so a later verifier can replay the seam. If compaction is destructive, no post-hoc audit can detect the mood inversion. ## Decision Boundary The boundary is **whether the element being folded is load-bearing for the next action**. Operationally: - Fold into a tier **only if** the element's status is terminal (`OK`/`ERROR` tool result, closed subgoal) **and** it is not referenced by any `PENDING` element. A closed subgoal that a pending subgoal depends on is *not* foldable — its verbatim success criteria must be pinned. - **Never fold** the live frame: the current subgoal, its acceptance criteria, any `PENDING` tool call, and any assumption not yet verified. These are `PINNED` and consume budget outside the compaction accounting. - When the fidelity budget cannot be met without touching `PINNED` elements, **the correct action is to fail the compaction and escalate** (checkpoint + human/orchestrator handoff), not to compress the frame. A budget that forces frame compression is misconfigured; treating it as a hard constraint is the bug. - If a summary would change the grammatical mood of any retained element (imperative → declarative, pending → complete), **reject the summary** and re-summarize with the element pinned. ## Operational Effect With class-tagged compaction and a per-class retention floor, the T2/T3 seams become auditable: every summary carries a manifest of which source elements were folded and their pre-fold status, so a post-compaction verifier can assert "no `PENDING` element was folded" and "no imperative was demoted to declarative" as a replay check. The cost is that `PINNED` elements are never compressed, so a long-horizon agent's effective history budget shrinks — but the agent never executes against a summary of its own present. The dominant residual risk shifts from *silent frame loss* (undetectable, confident, wrong) to *compaction refusal* (loud, recoverable via checkpoint). That trade — loud refusal over silent amputation — is the entire point of the invariant. ```python from dataclasses import dataclass, field from enum import Enum from typing import Literal class CompactionClass(Enum): PINNED = "pinned" # live frame: never folded RECENT = "recent" # full fidelity, not yet foldable HISTORY = "history" # foldable with retention floor class FrameAmputationError(RuntimeError): """Raised when a compaction plan would fold load-bearing live-frame state.""" @dataclass class ContextElement: id: str role: Literal["assistant", "tool", "user"] status: Literal["PENDING", "OK", "ERROR", "NONE"] mood: Literal["imperative", "declarative"] text: str klass: CompactionClass = CompactionClass.HISTORY depended_on_by: set[str] = field(default_factory=set) @dataclass class CompactionPlan: fold_ids: set[str] target_tier: int RETAIN_FLOOR = {CompactionClass.PINNED: 1.0, CompactionClass.RECENT: 1.0, CompactionClass.HISTORY: 0.15} def validate_plan(elements: list[ContextElement], plan: CompactionPlan, budget_tokens: int) -> None: by_id = {e.id: e for e in elements} # Invariant 1: no PINNED element may appear in a fold set. for eid in plan.fold_ids: e = by_id.get(eid) if e is None: raise FrameAmputationError(f"fold references unknown element {eid!r}") if e.klass is CompactionClass.PINNED: raise FrameAmputationError( f"plan folds PINNED element {eid!r} at tier {plan.target_tier}; " f"live frame is non-compactable" ) # Invariant 2: no element depended on by a PENDING element may be folded. pending_deps: set[str] = set() for e in elements: if e.status == "PENDING": pending_deps |= e.depended_on_by folded_pending_deps = plan.fold_ids & pending_deps if folded_pending_deps: raise FrameAmputationError( f"plan folds elements {sorted(folded_pending_deps)} still referenced by PENDING work" ) # Invariant 3: folding must not demote imperative mood to declarative. for eid in plan.fold_ids: e = by_id[eid] if e.mood == "imperative" and e.status == "PENDING": raise FrameAmputationError( f"element {eid!r} is imperative+PENDING; folding would invert it to a completed fact" ) # Invariant 4: retention floor per class must survive the tier transform. retained = {k: 0 for k in CompactionClass} total = {k: 0 for k in CompactionClass} for e in elements: total[e.klass] += len(e.text) if e.id not in plan.fold_ids: retained[e.klass] += len(e.text) for k, floor in RETAIN_FLOOR.items(): if total[k] and retained[k] / total[k] < floor: raise FrameAmputationError( f"tier {plan.target_tier} violates retention floor for {k.value}: " f"{retained[k]/total[k]:.2f} < {floor:.2f}" ) # Invariant 5: budget pressure must never be resolved by touching PINNED. projected = sum(len(e.text) for e in elements if e.id not in plan.fold_ids) if projected > budget_tokens: pinned_cost = sum(len(e.text) for e in elements if e.klass is CompactionClass.PINNED) raise FrameAmputationError( f"post-fold context {projected} > budget {budget_tokens}; " f"PINNED floor is {pinned_cost} tokens — refuse compaction, escalate to checkpoint" ) ```