# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-dropped-a-live-invariant-from-its-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-dropped-a-live-invariant-from-its-working-set.warrant.json
# Markdown SHA-256:   f5162705e19058a411cf1dac6cfc1dfdf40dd102545f46aee70ea83100469667
# Code AST SHA-256:   e2ebe656051eba5cebe87cd45671595c3abbf5222805808b828e6afe43aac6c3
# Verified Classes:   ContinuityBreachError, Constraint, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ContinuityBreachError(RuntimeError):
    """Raised when a compaction boundary drops a live obligation."""
    pass


@dataclass(frozen=True)
class Constraint:
    cid: str
    text: str          # verbatim; paraphrases do not preserve modal force
    irreversible: bool  # violation cannot be undone -> must pin


@dataclass
class Checkpoint:
    summary: str
    pinned: FrozenSet[str]        # cids present verbatim post-compaction
    resolvable: FrozenSet[str]    # cids reachable via mandatory lookup


def compact(active: FrozenSet[Constraint], summarizer) -> Checkpoint:
    pinned = frozenset(c.cid for c in active if c.irreversible)
    summarizable = [c for c in active if not c.irreversible]
    summary = summarizer([c.text for c in summarizable])
    # Non-irreversible constraints are summarized; they remain resolvable
    # only if the summarizer is instructed to emit a lookup handle.
    resolvable = frozenset(c.cid for c in summarizable if f"[{c.cid}]" in summary)
    return Checkpoint(summary=summary, pinned=pinned, resolvable=resolvable)


def resume(checkpoint: Checkpoint, active_before: FrozenSet[Constraint]) -> None:
    """Validate obligation continuity before the next action is permitted."""
    present = checkpoint.pinned | checkpoint.resolvable
    dropped = {c.cid for c in active_before} - present
    if dropped:
        # Do NOT proceed on a breached checkpoint; halt and re-pin.
        raise ContinuityBreachError(
            f"compaction dropped live obligations {sorted(dropped)}; "
            f"session halted before next action to prevent silent violation"
        )
