# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-context-corruption-when-the-model-owns-its-own-pruning-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-context-corruption-when-the-model-owns-its-own-pruning-policy.warrant.json
# Markdown SHA-256:   25796ef35c3a754d05256aa50f40dbcaf700f67cb94c3d465720726bf1730b84
# Code AST SHA-256:   ffaf15db33d5a825cf3b8a43cf2ac93a382761419b2f22a46ff7961b5dcd5a43
# Verified Classes:   ProvenanceViolation, PruneDecision, ContextLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceViolation(RuntimeError):
    """Raised when a prune decision cannot be attributed to a valid prior context."""
    pass


@dataclass(frozen=True)
class PruneDecision:
    evicted_hash: str
    reason: str
    context_digest_at_decision: str
    cited_surviving_spans: tuple[str, ...]


class ContextLedger:
    def __init__(self) -> None:
        self._entries: list[PruneDecision] = []

    def digest(self, window: list[str]) -> str:
        h = hashlib.sha256()
        for span in window:
            h.update(span.encode("utf-8"))
            h.update(b"\x00")
        return h.hexdigest()

    def record_prune(
        self,
        window_before: list[str],
        evicted_span: str,
        reason: str,
        surviving_spans: list[str],
        cited: list[str],
    ) -> PruneDecision:
        # Invariant 1: rationale must be bound to the pre-eviction context.
        digest = self.digest(window_before)

        # Invariant 2: citation obligation. The reason must cite either a
        # surviving span or a prior ledger digest; a bare "redundant" is refused.
        surviving_set = set(surviving_spans)
        cited_set = set(cited)
        if not cited_set:
            raise ProvenanceViolation(
                f"prune of {self.digest([evicted_span])[:12]} has no citation; "
                "rationale cannot outlive eviction"
            )
        if not (cited_set & surviving_set) and not any(
            c in {e.context_digest_at_decision for e in self._entries} for c in cited_set
        ):
            raise ProvenanceViolation(
                "cited spans do not survive the prune and are not in the ledger; "
                "this rationale will become unrecoverable"
            )

        # Invariant 3: monotone contradiction check is delegated to caller,
        # but the ledger refuses to record a prune that evicts its own witness.
        if evicted_span in cited_set:
            raise ProvenanceViolation(
                "prune cites the span it evicts as its own justification"
            )

        decision = PruneDecision(
            evicted_hash=self.digest([evicted_span]),
            reason=reason,
            context_digest_at_decision=digest,
            cited_surviving_spans=tuple(cited),
        )
        self._entries.append(decision)
        return decision

    def audit(self, claim: str, supporting_hashes: list[str]) -> bool:
        """Return True only if every supporting span is either live or
        has a ledger entry whose rationale is itself auditable."""
        known = {e.evicted_hash for e in self._entries}
        for h in supporting_hashes:
            if h not in known:
                return False
        return True


def prune_or_refuse(ledger: ContextLedger, window: list[str], evicted: str,
                    reason: str, cited: list[str]) -> None:
    surviving = [s for s in window if s != evicted]
    decision = ledger.record_prune(window, evicted, reason, surviving, cited)
    if not ledger.audit(reason, [decision.evicted_hash]):
        # Defensive: a recorded prune whose own rationale is unauditable
        # must not silently proceed.
        raise ProvenanceViolation(
            f"recorded prune {decision.evicted_hash[:12]} is not self-auditable"
        )
