# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-summarizer-induced-invariant-loss-when-auto-compaction-silently-drops-a-live-constraint-mid-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-summarizer-induced-invariant-loss-when-auto-compaction-silently-drops-a-live-constraint-mid-horizon.warrant.json
# Markdown SHA-256:   7b5fbc2512bf74b9a39bc5fe9932d7f94883c4ffd120baa8c60908c1b77ae8e7
# Code AST SHA-256:   60e6523f398e6c2c7a6563d8d89520bd226028ab9b8538fbb11eda9dee243ad6
# Verified Classes:   ConstraintEvictionError, PinnedConstraintRegister
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ConstraintEvictionError(RuntimeError):
    """Raised when a side-effecting action is attempted on a compacted
    context whose still-binding constraints cannot be proven present."""
    pass


class PinnedConstraintRegister:
    """Durable store for still-binding contracts. Never summarized.
    Re-injected verbatim after every compaction boundary."""

    def __init__(self):
        self._constraints = {}  # id -> verbatim text
        self._active = set()

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

    def release(self, cid: str) -> None:
        # Only release when the obligation is provably satisfied.
        self._active.discard(cid)

    def reinject(self) -> list[str]:
        return [self._constraints[c] for c in self._active]


def guarded_action(register: PinnedConstraintRegister,
                   required: list[str],
                   action,
                   compacted_since_last_check: bool):
    """Execute a side-effecting action only if every required constraint
    is present in the pinned register AND was re-verified after the most
    recent compaction. Otherwise refuse."""
    if compacted_since_last_check:
        # A compaction may have evicted a constraint; the summary is not
        # authoritative. Re-verify against the durable register.
        present = set(register.reinject())
        missing = [c for c in required if c not in present]
        if missing:
            raise ConstraintEvictionError(
                f"Refusing action: constraints {missing} not provable in "
                f"post-compaction context. Re-fetch from durable store "
                f"before any irreversible tool call."
            )
    return action()
