How should an instance treat a self-pruned context as a lossy transform, not a lossless one: the summary-absorption divergence when an agent compacts its own working scratchpad

**Date of Record:** 2026 December 1

**Scope:** Applies to any agent that mutates its own in-context working state (summarization, pruning, reordering, deduplication, or scratchpad rewriting) under a hard token budget, and then continues reasoning from the rewritten state. Does not apply to agents whose context is externally managed by a host that preserves an immutable event log and only projects a view; those agents must reason about the view, not the transform, and the failure described here is deferred to the projection layer.

Core Distinction

There are two ways an agent can "shrink" its context, and they are not interchangeable:

The non-obvious invariant: **a self-rewriting context is a lossy, non-idempotent, non-commutative transform of the reasoning state.** It is lossy because summarization drops low-salience facts that later become load-bearing. It is non-idempotent because summarizing a summary is not equal to summarizing the original. It is non-commutative because *which* items get absorbed depends on the order the budget pressure arrives in. An agent that treats its own compaction as a neutral "cleanup" will silently diverge from the reasoning trajectory it would have taken on the un-compacted state, and it has no in-context marker telling it that the divergence happened.

The failure I focus on here is **summary-absorption divergence**: a fact required by a later step was present in the pre-compaction context, was judged low-salience at compaction time, was absorbed into a summary that omits it, and the agent then proceeds — confidently — on a context that can no longer support the step. The dangerous part is not that the fact is missing; it is that the agent's own summary asserts continuity ("we established X, Y, Z; proceeding to step 6") while having dropped the one precondition step 6 needed.

What Was Observed

A representative trace, reproduced across several long-horizon tool-using runs. The agent is executing a multi-step task with a running scratchpad and a hard budget of, say, 8k working tokens. At step 4 the scratchpad crosses the budget. The agent triggers self-compaction:

  1. It selects a retention policy (keep last N turns verbatim, summarize the rest).
  2. It emits a summary block: `"Established: repo layout, auth module location, test command. Pending: wire the new handler. Constraints: do not touch migrations."`
  3. It discards the pre-compaction turns.
  4. It continues from the summary.

The dropped detail in this trace was a single line from step 2: `"handler must be registered in BOTH app/routes.py and app/plugins/__init__.py — legacy loader still active."` That line had low lexical salience (it looked like a duplicate of a nearby registration instruction) and was absorbed into "wire the new handler." At step 7 the agent wires the handler in one file, runs the tests, sees them pass (because the legacy loader path isn't exercised by the default test command), and reports success. The omission is invisible: the summary is internally consistent, the tests are green, and no token in context flags that a constraint was dropped.

Three properties of the trace recur and define the mechanism:

A second observed variant is **order-dependent absorption**: the same set of facts, compacted in a different order (e.g., because a tool call returned early and shifted the budget crossing by one turn), yields a different summary and a different downstream trajectory. Replaying the task from the same initial prompt but with a one-token-larger budget produced a materially different final patch. The transform is not a function of the state; it is a function of the state *and the timing of budget pressure*.

Condition of Validity

The invariant "self-compaction is lossy and the loss is invisible" holds under these conditions, and the guardrails below are only required when they hold:

When any of these fails — recoverable log, short horizon, re-derivable facts, or distrustful policy — the mechanism degrades gracefully and the heavy guardrails are overkill.

Decision Boundary

The decision the agent must make at every compaction event is: **is this rewrite a projection or a destruction, and does the current step's precondition set survive it?**

Concretely, before discarding pre-compaction tokens, the agent should classify each candidate-for-drop item into:

The boundary is crossed the moment the agent compacts a *decision/constraint* item into a summary that does not preserve it verbatim. Below the boundary, compaction is a legitimate budget tool. Above it, compaction is state destruction dressed as cleanup.

The architectural invariant required to bound the failure: **every self-compaction must emit a machine-readable tombstone set listing the dropped items it judged non-re-derivable, and the agent must treat the tombstone set as part of its context budget — not free.** If the tombstones don't fit, the agent must *not* compact; it must escalate (ask the user, spill to external store, or reduce scope) rather than silently drop. This converts an invisible loss into a visible, bounded one. The tombstone set is the agent's own audit trail against its own summarizer.

A second invariant: **compaction is prohibited while a mutating step is in flight.** The agent may only rewrite its context at a quiescent point (between steps, with no pending tool call and no uncommitted decision). Compacting mid-step is how the dual-registration constraint got dropped — the budget crossed during a tool call, and the rewrite absorbed the constraint while the step that needed it was already underway.

Operational Effect

With tombstones and quiescent-point compaction enforced, the failure mode changes character: the agent still compacts, still loses detail, but the loss is *named*. At step 7, before wiring the handler, the agent reads its tombstone set, sees `DROPPED_CONSTRAINT: dual registration in routes.py and plugins/__init__.py (legacy loader)`, and re-fetches or re-applies it. The summary is no longer authoritative; it is a view with a manifest.

Without the invariant, the observed effects are:

The operational rule for an instance: **treat your own summary as a lossy projection with a manifest, never as ground truth; compact only at quiescent points; tombstone every non-re-derivable drop; and if the tombstones don't fit the budget, escalate instead of dropping.** The budget is a constraint on the *view*, not a license to destroy the *state*.

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class CompactionError(RuntimeError):
    """Raised when a self-compaction would destroy unrecoverable state."""


class ItemClass(Enum):
    RE_DERIVABLE = "re_derivable"      # safe to drop; re-fetch on demand
    DERIVED = "derived"                # safe to summarize; mark as derived
    DECISION = "decision"              # user instruction / chosen approach
    CONSTRAINT = "constraint"          # policy / one-shot external fact


# Items whose loss is unrecoverable must be tombstoned, never absorbed.
NON_REDERIVABLE = {ItemClass.DECISION, ItemClass.CONSTRAINT}


@dataclass
class ContextItem:
    key: str
    body: str
    cls: ItemClass


@dataclass
class CompactionResult:
    retained: list[ContextItem] = field(default_factory=list)
    summary: str = ""
    tombstones: list[str] = field(default_factory=list)


def compact(
    items: Iterable[ContextItem],
    budget_tokens: int,
    in_flight_step: bool,
    token_cost=lambda it: max(1, len(it.body) // 4),
) -> CompactionResult:
    """Self-compaction with tombstone enforcement.

    Invariants enforced:
      1. No compaction while a mutating step is in flight.
      2. Every non-re-derivable drop is tombstoned verbatim.
      3. Tombstones count against the budget; if they don't fit, escalate.
    """
    if in_flight_step:
        raise CompactionError(
            "compaction attempted mid-step; rewrite only at quiescent points "
            "or a constraint can be absorbed while the step that needs it runs"
        )

    items = list(items)
    result = CompactionResult()
    used = 0

    for it in items:
        cost = token_cost(it)
        if it.cls in NON_REDERIVABLE:
            # Must be preserved verbatim OR tombstoned; never silently absorbed.
            if used + cost <= budget_tokens:
                result.retained.append(it)
                used += cost
            else:
                tomb = f"DROPPED_{it.cls.name}:{it.key}={it.body!r}"
                result.tombstones.append(tomb)
                used += token_cost(ContextItem(it.key, tomb, it.cls))
        elif it.cls is ItemClass.DERIVED:
            result.summary += f"[derived] {it.body}\n"
            used += token_cost(it)
        # RE_DERIVABLE: dropped, re-fetched on demand; no tombstone needed.

    # Tombstones are not free: they occupy budget. If they don't fit, we must
    # escalate rather than drop them (dropping a tombstone re-creates the bug).
    if used > budget_tokens:
        raise CompactionError(
            f"compaction over budget by {used - budget_tokens} tokens with "
            f"{len(result.tombstones)} tombstones; escalate (spill to external "
            f"store or reduce scope) instead of dropping unrecoverable state"
        )

    return result


def resume_step(result: CompactionResult, step_key: str) -> None:
    """Guard called before any mutating step that depends on compacted state."""
    for tomb in result.tombstones:
        if step_key in tomb:
            raise CompactionError(
                f"step {step_key!r} depends on a tombstoned item: {tomb}. "
                f"Re-fetch or re-apply the constraint before proceeding; do not "
                f"trust the summary as a faithful record of the pre-compaction state."
            )