# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-model-driven-pruning-from-deleting-the-only-copy-of-a-live-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-model-driven-pruning-from-deleting-the-only-copy-of-a-live-commitment.warrant.json
# Markdown SHA-256:   ee55985021a48b2a890f80fb351252224b62c4ed33c70f1fe84ae466ba57cde4
# Code AST SHA-256:   06676c2006ce58f369c3aaec452e9694fea9457068fdeaa3fd7ef05ed435138a
# Verified Classes:   PruneInvariantViolation, CommitmentStatus, Commitment, CommitmentLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class PruneInvariantViolation(RuntimeError):
    """Raised when an eviction set would orphan a live commitment."""
    pass


class CommitmentStatus(Enum):
    OPEN = "open"
    CLOSED = "closed"


@dataclass
class Commitment:
    establishing_hash: str
    obligation_text: str          # verbatim, not summarized
    status: CommitmentStatus = CommitmentStatus.OPEN


@dataclass
class CommitmentLedger:
    entries: dict[str, Commitment] = field(default_factory=dict)

    def register(self, segment_text: str, obligation_text: str) -> str:
        h = hashlib.sha256(segment_text.encode()).hexdigest()
        self.entries[h] = Commitment(h, obligation_text)
        return h

    def close(self, establishing_hash: str) -> None:
        if establishing_hash not in self.entries:
            raise PruneInvariantViolation(
                f"cannot close unknown commitment {establishing_hash[:12]}"
            )
        self.entries[establishing_hash].status = CommitmentStatus.CLOSED

    def live_hashes(self) -> set[str]:
        return {
            h for h, c in self.entries.items()
            if c.status is CommitmentStatus.OPEN
        }


def safe_prune(
    segments: dict[str, str],
    eviction_candidates: list[str],
    ledger: CommitmentLedger,
) -> list[str]:
    """
    segments: hash -> text, the current window.
    eviction_candidates: hashes the relevance scorer wants to drop.
    Returns the actually-evictable set after liveness veto.
    """
    if ledger is None:
        # No ledger: refuse to evict anything that could carry a constraint.
        raise PruneInvariantViolation(
            "pruning attempted with no commitment ledger; "
            "liveness cannot be verified"
        )

    live = ledger.live_hashes()
    vetoed = [h for h in eviction_candidates if h in live]

    if vetoed:
        # A live commitment's sole referent is in the eviction set.
        # Do not silently skip: the caller must restate or close first.
        raise PruneInvariantViolation(
            f"eviction set orphans {len(vetoed)} live commitment(s): "
            f"{[h[:12] for h in vetoed]}"
        )

    # Verify every surviving obligation still has its referent in-window.
    survivors = set(segments) - set(eviction_candidates)
    for h in live:
        if h not in survivors:
            raise PruneInvariantViolation(
                f"post-prune window lacks referent for open commitment {h[:12]}"
            )

    return eviction_candidates
