# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-summary-compaction-from-silently-dropping-the-active-constraint-set-during-long-horizon-agent-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-summary-compaction-from-silently-dropping-the-active-constraint-set-during-long-horizon-agent-runs.warrant.json
# Markdown SHA-256:   28a5f83c1c032ef11e8859a1d72b155dec9230c6a5967242586cee3e46b322ea
# Code AST SHA-256:   f9ed7f0ce8c931cbf36fc223f43b146296c714a62899a17f8d199adf63862134
# Verified Classes:   ConstraintLossOnCompaction, ConstraintRegister
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ConstraintLossOnCompaction(RuntimeError):
    """Raised when a compaction event drops or paraphrases a registered constraint."""
    pass


class ConstraintRegister:
    def __init__(self) -> None:
        self._entries: dict[str, str] = {}  # immutable-by-default; lifting is explicit

    def add(self, cid: str, text: str) -> None:
        self._entries[cid] = text

    def lift(self, cid: str, reason: str) -> None:
        if cid not in self._entries:
            raise ConstraintLossOnCompaction(f"lift of unknown constraint {cid!r}")
        del self._entries[cid]  # only path that removes an entry

    def snapshot(self) -> frozenset[str]:
        return frozenset(self._entries)

    def forbids(self, action_class: str) -> bool:
        return any(action_class in t for t in self._entries.values())


def compact(register: ConstraintRegister, narrative_span: str, summarize) -> str:
    before = register.snapshot()
    summary = summarize(narrative_span)  # summarizer never receives the register
    after = register.snapshot()
    if before != after:
        raise ConstraintLossOnCompaction(
            f"compaction mutated constraint set: lost={before - after} gained={after - before}"
        )
    return summary


def guard_irreversible(register: ConstraintRegister, action_class: str, reversible: bool) -> None:
    if reversible:
        return
    if register.snapshot() == frozenset():
        # empty register is indistinguishable from a lost register; fail closed
        raise ConstraintLossOnCompaction(
            f"irreversible action {action_class!r} with empty register: halt and re-derive"
        )
    if register.forbids(action_class):
        raise ConstraintLossOnCompaction(
            f"irreversible action {action_class!r} matches an active constraint"
        )
