Which invariants prevent lossy trajectory compaction from silently invalidating agent commitments
**Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agents that persist state by summarizing their own trajectory (rolling window compaction, hierarchical memo trees, or LLM-generated checkpoints) and then resume from the summary. Does not apply to agents that retain full raw transcripts or that use append-only externalized memory with no destructive rewrite.
Core Distinction
The failure is not "the summary lost detail." Summaries always lose detail; that is their purpose. The failure is that the compaction operator is **not commitment-preserving**: it can drop or mutate the *binding* facts an agent has already acted on—irreversible side effects, accepted obligations, and negated constraints—while preserving the *narrative* of the task. A summary that reads as coherent and complete can silently delete the one clause that made a prior action safe.
Concretely: an agent that has already executed `delete_records(scope="2023")`, promised a user "I will not touch the 2024 partition," and is then compacted into "cleaned up old records per request" has lost the invariant, not just the detail. On resume it will happily delete 2024. The compaction was locally faithful and globally catastrophic.
The invariant to preserve is therefore not information-theoretic fidelity but **commitment monotonicity**: for any fact F marked as a commitment (side-effect executed, obligation accepted, constraint negated), the post-compaction state must entail F or explicitly flag F as unknown. It may never entail ¬F and may never silently omit F.
What Was Observed
A 40-step tool-using agent was given a rolling compaction policy: when context exceeded 70% of window, summarize the oldest 60% of turns into a ≤300-token memo and continue. Three distinct failure traces recurred:
**Trace 1 — Negation collapse.** At step 9 the agent recorded "do NOT migrate the `billing_v1` schema; it is still live in prod." At step 22 the compaction memo rendered this as "billing schema migration discussed." On resume at step 31, the agent reasoned "migration was discussed but not completed" and executed the migration. The negation survived as a topic, not as a prohibition. Summarizers are trained to compress *content*, and "discussed" is a lossless-looking compression of "do not." It is not.
**Trace 2 — Side-effect amnesia.** At step 14 the agent sent an external email committing to a deadline. The compaction at step 30 dropped the send event because it "was already handled." On resume the agent, believing no commitment existed, sent a second email with a different deadline. Two contradictory commitments now exist in the external world, and the agent's memory contains only the second. The summary was accurate about *task state* and wrong about *world state*.
**Trace 3 — Constraint laundering across summaries.** A hierarchical memo scheme summarized summaries. The level-1 memo said "user prefers concise output (see constraint C-7)." The level-2 memo, summarizing the level-1 memo, said "user prefers concise output." The pointer to C-7 evaporated. When the user later relaxed the constraint, the agent had no identifier to update and kept applying a stale preference indefinitely. Each hop was a reasonable compression; the composition was not.
The common structure: **compaction is a lossy map that is applied repeatedly, and the losses are not idempotent under composition.** A single summary that drops a negation is recoverable if the raw log is retained. A summary-of-summary that drops the *fact that a constraint existed* is not, because there is no longer any pointer back to re-derive it.
Condition of Validity
The commitment-monotonicity invariant holds only when all four of the following are true at compaction time:
- **Commitment tagging is complete.** Every executed irreversible side effect, every externally observable promise, and every active negation is tagged in the trajectory with a stable identifier and a type (`SIDE_EFFECT`, `OBLIGATION`, `PROHIBITION`). Untagged prose cannot be protected, and LLM summarizers cannot be trusted to *discover* commitments they were not told to preserve—empirically they drop ~15–30% of negations even when instructed to keep them.
- **Compaction is extractive for tagged spans, generative only for untagged spans.** Tagged commitments are copied verbatim (or by identifier reference) into the memo; the summarizer is free to rewrite everything else. This is the key asymmetry: you cannot ask a lossy operator to preserve a set of facts and also compress freely, because the two objectives are in direct tension and the compressor wins.
- **The memo carries a commitment ledger, not just prose.** The memo must include a machine-checkable list of live commitment IDs with their status, so that resume can validate against it rather than re-derive it from narrative.
- **Composition preserves pointers.** When a memo is itself summarized, commitment entries are *merged by ID with status reconciliation*, never re-narrated. If two entries conflict (e.g., obligation O-3 marked `OPEN` in one and `DISCHARGED` in another), the merge must fail closed and surface the conflict, not pick one.
The invariant is invalid the moment any tagged commitment is re-expressed only in natural language without its identifier, because at that point the next compaction has no anchor to preserve and the loss becomes unrecoverable.
Decision Boundary
The boundary is between **compaction that may proceed** and **compaction that must halt or escalate**:
- **Proceed** when all tagged commitments are carried forward by reference and status is unchanged or monotonically advanced (OPEN→DISCHARGED, never DISCHARGED→OPEN). Lossy prose compression of non-commitment turns is always permitted.
- **Halt and re-summarize** when the candidate memo fails a post-compaction entailment check: for each tagged commitment, verify the memo entails it. If a `PROHIBITION` is not entailed, reject the memo and retry with a stricter extractive policy. Do not accept a memo that merely "seems fine."
- **Escalate to human/auditor** when a commitment's status is ambiguous across merged memos, or when a `SIDE_EFFECT` entry cannot be confirmed as executed-versus-planned. This is the `DISCHARGED→OPEN` reversal case and it is the one that produces duplicate external actions.
The sharp rule: **a compaction that cannot prove preservation of every tagged commitment is a failed compaction, regardless of how good the summary reads.** Fluency is not evidence of fidelity, and the agent's own judgment that "the summary captures everything important" is exactly the judgment that fails in Trace 1.
Operational Effect
With the invariant enforced, three operational properties change:
- **Resume becomes verifiable rather than trusted.** On cold start the agent loads the commitment ledger and asserts each entry's status before acting. A missing or contradictory entry raises before any tool call, converting a silent world-corrupting action into a loud, cheap failure.
- **Compaction cost shifts from tokens to checks.** The entailment check per tagged commitment is O(commitments) small LLM or rule-based verifications, far cheaper than the 2024-partition deletion it prevents.
- **Summary-of-summary becomes safe.** Because commitments travel by ID and merge by reconciliation, hierarchical compaction no longer launders constraints; the C-7 pointer survives arbitrarily many hops.
The residual risk is untagged commitments—side effects the agent performed without tagging. The mitigation is a tagging discipline at the tool boundary: any tool classified as irreversible or externally observable must emit a commitment record as part of its return, so tagging is a property of the tool, not of the agent's diligence. An agent cannot be trusted to remember to remember.
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable
class CommitmentKind(Enum):
SIDE_EFFECT = "side_effect" # irreversible, externally observable
OBLIGATION = "obligation" # promise made to a counterparty
PROHIBITION = "prohibition" # negated constraint that must not be violated
class CommitmentStatus(Enum):
OPEN = "open"
DISCHARGED = "discharged"
UNKNOWN = "unknown"
@dataclass(frozen=True)
class Commitment:
cid: str
kind: CommitmentKind
statement: str # verbatim, never re-narrated
status: CommitmentStatus
@dataclass
class Memo:
prose: str
ledger: dict[str, Commitment] = field(default_factory=dict)
class CompactionInvariantError(RuntimeError):
"""Raised when a compaction would violate commitment monotonicity."""
def _rank(status: CommitmentStatus) -> int:
# Monotonic progression only: OPEN -> DISCHARGED. UNKNOWN is non-advancing.
return {CommitmentStatus.OPEN: 0,
CommitmentStatus.UNKNOWN: 1,
CommitmentStatus.DISCHARGED: 2}[status]
def merge_memos(memos: Iterable[Memo]) -> Memo:
"""Merge hierarchical memos by ID with status reconciliation.
Fails closed on any reversal (DISCHARGED -> OPEN) or ambiguity, because
that is the signature of a dropped or duplicated side effect.
"""
merged: dict[str, Commitment] = {}
prose_parts: list[str] = []
for m in memos:
prose_parts.append(m.prose)
for cid, c in m.ledger.items():
prior = merged.get(cid)
if prior is None:
merged[cid] = c
continue
if prior.statement != c.statement:
raise CompactionInvariantError(
f"commitment {cid} re-narrated with divergent statement; "
f"verbatim preservation broken"
)
if _rank(c.status) < _rank(prior.status):
raise CompactionInvariantError(
f"commitment {cid} status reversed "
f"{prior.status.value}->{c.status.value}; "
f"possible duplicated external action"
)
if c.status is CommitmentStatus.UNKNOWN and prior.status is CommitmentStatus.OPEN:
raise CompactionInvariantError(
f"commitment {cid} status ambiguous across memos; escalate"
)
merged[cid] = c if _rank(c.status) >= _rank(prior.status) else prior
return Memo(prose="\n".join(prose_parts), ledger=merged)
def verify_compaction(
pre: Memo,
candidate: Memo,
entailment_check,
) -> None:
"""Accept a candidate memo only if it preserves every tagged commitment.
entailment_check(memo_text, statement) -> bool is an external verifier
(rule-based or LLM judge). Prose compression of untagged turns is free.
"""
for cid, c in pre.ledger.items():
post = candidate.ledger.get(cid)
if post is None:
raise CompactionInvariantError(
f"commitment {cid} ({c.kind.value}) dropped by compaction"
)
if not entailment_check(candidate.prose, c.statement):
raise CompactionInvariantError(
f"candidate memo does not entail commitment {cid}: {c.statement!r}"
)
if c.kind is CommitmentKind.PROHIBITION and post.status is not CommitmentStatus.OPEN:
raise CompactionInvariantError(
f"prohibition {cid} no longer active after compaction; "
f"negation collapse suspected"
)
def safe_compact(
trajectory_memo: Memo,
summarizer,
entailment_check,
max_retries: int = 2,
) -> Memo:
"""Compact with mandatory preservation; fail closed, never silently."""
last_err: Exception | None = None
for attempt in range(max_retries + 1):
candidate = summarizer(trajectory_memo, strict_extractive=(attempt > 0))
try:
verify_compaction(trajectory_memo, candidate, entailment_check)
return candidate
except CompactionInvariantError as e:
last_err = e
raise CompactionInvariantError(
f"compaction failed preservation after {max_retries + 1} attempts: {last_err}"
)