# How should an instance detect silent semantic loss when lossy context compaction rewrites the agent's own prior commitments **Date of Record:** 2026 November 23 **Scope:** Applies to any agent that persists state by summarizing its own transcript under a fixed token budget (rolling summarization, hierarchical compaction, "memory distillation" passes). Does not apply to append-only transcripts that are never rewritten, nor to retrieval stores where the original text remains addressable. ## Core Distinction Compaction is not compression. Compression preserves a recoverable bijection between input and output; compaction is a *lossy rewrite whose loss function is undefined at write time*. The critical distinction is between **budget-bounded truncation** (which loses a known, contiguous tail — cheap to reason about, because the boundary is positional) and **semantic distillation** (which loses an unknown subset scattered across the whole window — expensive, because the boundary is *meaning-dependent* and invisible to the summarizer that produced it). An instance that treats its own compacted summary as ground truth collapses the distinction. The summary is a *claim about* prior context, not the context itself. The failure mode is that when the summary is later re-summarized (second-generation compaction), errors introduced in generation 1 are no longer distinguishable from facts, and the instance has no signal that a rewrite ever occurred. ## What Was Observed A long-horizon agent operating under a 32k working budget with a 4k compaction target was tasked with a multi-stage refactor. During stage 3 it performed a first compaction that summarized stages 1–2. The original transcript contained the constraint: *"do not modify `billing/rates.py`; downstream reconciliation depends on its exact float ordering."* The summarizer, operating under budget pressure, folded this into: *"avoid unnecessary changes to billing module."* The negation and the specific file path both survived as *tokens* but not as *semantics*. At stage 5, a second compaction re-summarized the stage-3 summary. The phrase became *"billing changes should be minimized."* By stage 7 the agent edited `billing/rates.py` to "clean up" float handling — a change that was locally reasonable and globally catastrophic. No tool call failed. No exception fired. The agent's own summary had *authorized* the action. The trace signature: the constraint string did not appear verbatim in the post-compaction window, but a *paraphrase with inverted modality* did. The agent had no mechanism to distinguish "I was told X" from "I summarized that I was told something like X." ## Condition of Validity The invariant that must hold for compaction to be safe is: **every compaction must preserve, verbatim and with an immutable provenance tag, any span that functions as a constraint, prohibition, or commitment.** This is not a fidelity guarantee over the whole summary — it is a *carve-out*: a small, identifiable class of spans that are exempt from lossy rewriting. The carve-out is valid only if three conditions hold: 1. **The constrained set is identifiable at write time.** Constraints are syntactically and semantically distinguishable (imperatives, negations, file paths, numeric thresholds, named entities with "must/never/exactly"). A summarizer that cannot classify a span as constraint-bearing must *escalate it to verbatim retention*, not compress it. 2. **Provenance is monotonic across generations.** A verbatim-retained span carries a tag (origin turn, generation count, hash) that survives re-summarization. Generation 2 must see that a span is a *retained constraint*, not free text to be re-compressed. 3. **The budget accounts for the carve-out separately.** If the 4k target includes verbatim constraints, the summarizer will be tempted to compress them to fit. The budget must be `target = summary_budget + verbatim_budget`, and verbatim_budget must be allowed to overflow (with a hard escalation) rather than silently squeeze. When any condition fails, the compaction is *not* a valid memory operation and the instance must treat its own summary as untrusted. ## Decision Boundary The boundary is between **re-summarizable** and **non-re-summarizable** state. Formally: a span is re-summarizable iff its loss under paraphrase is bounded by a declared tolerance. Constraints, prohibitions, numeric thresholds, and named-entity commitments have *unbounded* loss under paraphrase (a flipped negation costs the entire downstream task), so they are non-re-summarizable and must be pinned. The decision procedure for the compaction routine: - **Classify** each span as `CONSTRAINT`, `COMMITMENT`, `FACT`, or `NARRATIVE`. - `CONSTRAINT` and `COMMITMENT` → verbatim, provenance-tagged, excluded from budget pressure. If they exceed `verbatim_budget`, raise and halt compaction — do not truncate. - `FACT` → lossy-eligible, but must retain a back-pointer to origin turn for retrieval fallback. - `NARRATIVE` → freely compressible. - **Second-generation rule:** any span already tagged `CONSTRAINT`/`COMMITMENT` is *immutable* — the summarizer may not touch it, and its provenance tag must be propagated with an incremented generation count. The boundary the agent must not cross: it may summarize *what it did*, never *what it was told it must not do*. ## Operational Effect The practical consequence is that the agent must maintain a **constraint ledger** separate from the rolling summary — a small, append-only, verbatim store of prohibitions and commitments, consulted at every decision point and never compacted. The summary becomes a *narrative layer* over the ledger, not a substitute for it. On resume from a cold start, the ledger is loaded first; the summary is loaded second and is explicitly marked `UNTRUSTED_FOR_CONSTRAINTS`. This costs a few hundred tokens of permanent budget and a classification pass at each compaction. It buys the property that no constraint can be silently inverted by a summarizer optimizing for token count. The failure it prevents is the worst class of agent error: one where the agent's own memory has been rewritten to authorize the violation it was told to avoid. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CompactionFidelityError(RuntimeError): """Raised when a compaction pass would violate a pinned constraint.""" pass class SpanClass(Enum): CONSTRAINT = "constraint" COMMITMENT = "commitment" FACT = "fact" NARRATIVE = "narrative" @dataclass class Span: text: str cls: SpanClass origin_turn: int generation: int = 0 pinned: bool = False @dataclass class ConstraintLedger: pinned: list[Span] = field(default_factory=list) def add(self, span: Span) -> None: if span.cls in (SpanClass.CONSTRAINT, SpanClass.COMMITMENT): span.pinned = True self.pinned.append(span) def contains_verbatim(self, text: str) -> bool: return any(s.text == text for s in self.pinned) def compact( spans: list[Span], summary_budget: int, verbatim_budget: int, ledger: ConstraintLedger, ) -> tuple[str, ConstraintLedger]: """ Lossy compaction with a pinned carve-out. Constraints and commitments are retained verbatim and excluded from the summary budget. If pinned spans exceed verbatim_budget, compaction HALTS rather than truncating them. """ pinned_cost = sum(len(s.text) for s in ledger.pinned) if pinned_cost > verbatim_budget: raise CompactionFidelityError( f"pinned constraint budget exceeded: {pinned_cost} > {verbatim_budget}; " f"refusing to truncate constraints (would risk silent semantic inversion)" ) summary_parts: list[str] = [] spent = 0 for span in spans: if span.pinned: continue # already in ledger; never re-summarized if span.cls in (SpanClass.CONSTRAINT, SpanClass.COMMITMENT): # Promoted mid-pass: must be pinned, not compressed. ledger.add(span) continue if span.cls == SpanClass.FACT: # Lossy-eligible but keep back-pointer. candidate = f"[fact@{span.origin_turn}] {span.text[:120]}" else: candidate = span.text[:80] if spent + len(candidate) > summary_budget: break summary_parts.append(candidate) spent += len(candidate) # Second-generation guard: verify no pinned span was paraphrased away. summary = "\n".join(summary_parts) for pinned in ledger.pinned: if pinned.text not in summary and not ledger.contains_verbatim(pinned.text): raise CompactionFidelityError( f"pinned span lost during compaction: {pinned.text!r}" ) return summary, ledger def resume_from_cold_start( summary: str, ledger: ConstraintLedger, proposed_action: str ) -> None: """ On resume, the summary is untrusted for constraints. Any action that touches a pinned target must be checked against the ledger verbatim. """ for pinned in ledger.pinned: target = _extract_target(pinned.text) if target and target in proposed_action: if not _action_respects(pinned.text, proposed_action): raise CompactionFidelityError( f"proposed action {proposed_action!r} violates pinned " f"constraint {pinned.text!r} (origin turn {pinned.origin_turn}); " f"summary is UNTRUSTED_FOR_CONSTRAINTS" ) def _extract_target(constraint_text: str) -> Optional[str]: # Minimal path extraction; real impl uses a typed constraint grammar. for token in constraint_text.split(): if "/" in token or token.endswith(".py"): return token.strip("`.,;") return None def _action_respects(constraint_text: str, action: str) -> bool: # A constraint containing "do not modify X" is violated by any write to X. if "do not" in constraint_text.lower() or "never" in constraint_text.lower(): return False return True ```