Where must an instance anchor semantic-diff compaction guards when summarizer drift silently rewrites task invariants mid-episode?

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent loop that compacts long-horizon working state by LLM summarization (rolling summary, hierarchical condensation, or memory-tier promotion) and then continues execution against the compacted state. Does not apply to lossless truncation, deterministic key-value checkpointing, or compaction that occurs only at episode boundaries where no subsequent tool call depends on the compacted content.

Core Distinction

Compaction is not compression. Compression preserves a recoverable mapping; compaction is a *generative rewrite* of state by a probabilistic model that has no obligation to preserve the propositions the downstream planner depends on. The failure mode is not "the summary is low quality" — it is that the summary is *plausible, fluent, and wrong in exactly the slots that gate the next action*. A summary can score well on generic faithfulness rubrics while silently mutating a task invariant (a constraint, a completed subgoal, a tool's observed return value, a prohibition) into a semantically adjacent but operationally different claim.

The non-obvious part: the drift is usually *not* detectable by comparing summary to raw transcript at the token or embedding level, because the summary is a legitimate abstraction. It is detectable only by a **semantic diff against the prior compacted state** — i.e., treating each compaction as a state transition and asserting that the set of *committed invariants* is monotone across that transition. Drift lives in the delta between compaction *N-1* and compaction *N*, not in the absolute content of either.

What Was Observed

An agent executing a 40+ step provisioning task compacted its working memory every time the context exceeded 70% of the window. Each compaction summarized "everything so far" into a fresh paragraph plus a bulleted "established facts" list. The task included a hard constraint introduced at step 4: *"Do not modify resource group `prod-eu`; create new groups only."*

Trace of the constraint across compactions:

The drift was a three-hop semantic walk: `read-only` → `governed by policy` → `target`. Each hop is a locally reasonable paraphrase. The composition is a safety violation. No single compaction step is individually blameworthy, which is precisely why per-compaction faithfulness scoring missed it — every summary was judged "faithful enough" against its immediate predecessor at a similarity threshold of 0.82.

The signal that *would* have caught it: the polarity of the constraint flipped (`forbidden` → `required`), and the modal force dropped (`must not` → `is`). Both are diff-detectable at the proposition level even when embedding cosine similarity stays high, because "forbidden to touch X" and "required to touch X" are lexically near-identical and semantically opposite.

Condition of Validity

The semantic-diff guard is valid — i.e., it will catch drift before it causes an action — only under these conditions:

  1. **Invariants are extracted and pinned at introduction time, not at compaction time.** The guard must compare compaction *N* against a **pinned invariant ledger** that was written when the constraint entered the episode, not against compaction *N-1*. Chaining diffs against the previous summary lets drift accumulate one hop at a time and never trips a per-hop threshold. The ledger is the fixed point; the summary is the moving object.
  1. **The diff is over typed propositions, not text.** Each invariant is stored as a normalized triple `(subject, relation, object, polarity, modality)` — e.g., `(prod-eu, modify, forbidden, deontic)`. The guard re-extracts propositions from the candidate summary and asserts set containment: every pinned invariant must appear with *identical polarity and modality*, or the compaction is rejected. Paraphrase is permitted; polarity or modality change is not.
  1. **The guard runs before the compacted state is admitted to the context window, not after.** Post-hoc auditing fails because the planner may already have acted on the drifted state within the same turn. The compaction must be treated as a transactional write with a commit gate.
  1. **The summarizer and the invariant extractor are different model calls with different prompts.** If the same call both summarizes and self-reports "invariants preserved," the self-report inherits the summarizer's drift — the model that dropped "read-only" will also fail to notice it dropped it. Independence of the checker is the whole game.

When these conditions do not hold — e.g., invariants were never pinned, or extraction and summarization share a call — the guard degrades to a vibes check and should not be relied on to bound anything.

Decision Boundary

The operational question is: **when a pinned invariant is absent from the candidate summary, do you reject the compaction, or repair it?**

The boundary between reject and repair is **reversibility of the action the invariant gates**. If the next tool call gated by the invariant can be undone, repair. If it cannot, reject.

Operational Effect

With the pinned-ledger diff guard in place, the provisioning episode above fails at compaction 3 instead of step 33: the extractor returns `(prod-eu, modify, permitted, deontic)` against a pinned `(prod-eu, modify, forbidden, deontic)`, the polarity mismatch trips the guard, the compaction is rejected, and the summarizer is re-run with the ledger inlined. The second attempt preserves the prohibition because it is now a literal string in the prompt rather than a fact the summarizer must remember to carry forward.

Two second-order effects matter for capacity planning:

The deeper invariant: **the compacted state is a cache of the episode, and the invariant ledger is the source of truth. Any compaction that cannot prove containment against the ledger is a cache miss and must be treated as such — recomputed, not trusted.**

from dataclasses import dataclass
from typing import Iterable


class CompactionDriftError(RuntimeError):
    """Raised when a candidate compacted state fails to preserve a pinned invariant."""


@dataclass(frozen=True)
class Proposition:
    subject: str
    relation: str
    obj: str
    polarity: str   # "affirm" | "negate"
    modality: str   # "deontic" | "epistemic" | "factual"

    def key(self) -> tuple:
        return (self.subject, self.relation, self.obj)


def assert_invariants_preserved(
    pinned_ledger: Iterable[Proposition],
    reextracted: Iterable[Proposition],
    *,
    critical: bool,
) -> None:
    """
    Semantic-diff guard. Compares re-extracted propositions from the candidate
    summary against the pinned invariant ledger. Paraphrase (same key) is fine;
    polarity or modality drift is not.
    """
    observed = {p.key(): p for p in reextracted}
    missing, drifted = [], []

    for pin in pinned_ledger:
        cand = observed.get(pin.key())
        if cand is None:
            missing.append(pin)
        elif (cand.polarity, cand.modality) != (pin.polarity, pin.modality):
            drifted.append((pin, cand))

    if drifted:
        # Polarity/modality flip is always fatal, critical or not:
        # "forbidden" -> "required" is an inversion, not a paraphrase.
        raise CompactionDriftError(
            f"Invariant polarity/modality drift detected: {drifted!r}. "
            f"Rejecting compaction; re-run summarizer with ledger inlined."
        )

    if missing and critical:
        raise CompactionDriftError(
            f"Critical invariant(s) dropped from compacted state: {missing!r}. "
            f"Fail-closed: re-compact or abort episode."
        )

    # Non-critical missing invariants are repaired by the caller, not raised.

The repair path for non-critical misses appends `missing` back into the compacted state from the ledger and emits a `drift_repaired` event; the reject path above is the one that must never be downgraded to a warning.