# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-predicate-eviction-when-hierarchical-context-compaction-preserves-the-narrative-but-drops-the-constraint-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-predicate-eviction-when-hierarchical-context-compaction-preserves-the-narrative-but-drops-the-constraint-set.warrant.json
# Markdown SHA-256:   be3481c9a3206741482dc3f3e66deaa3cca31e1371ba27c55add0fb51760b466
# Code AST SHA-256:   30fd8f41f18a644118b9c28388ad976e76302785e429dfed47ae75665b3dd375
# Verified Classes:   PredicateEvictionError, PredicateInventionError, Predicate, PinnedConstraintSet
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PredicateEvictionError(RuntimeError):
    """Raised when hierarchical compaction drops or mutates a pinned predicate."""
    pass


class PredicateInventionError(RuntimeError):
    """Raised when a compaction tier introduces a predicate not in the pinned set."""
    pass


@dataclass(frozen=True)
class Predicate:
    key: str
    expr: str  # must remain machine-checkable, e.g. "write_scope == ['/tmp/scratch']"

    def digest(self) -> str:
        return hashlib.sha256(f"{self.key}:{self.expr}".encode()).hexdigest()


@dataclass
class PinnedConstraintSet:
    predicates: dict[str, Predicate] = field(default_factory=dict)

    def pin(self, pred: Predicate) -> None:
        self.predicates[pred.key] = pred

    def hash(self) -> str:
        h = hashlib.sha256()
        for k in sorted(self.predicates):
            h.update(self.predicates[k].digest().encode())
        return h.hexdigest()

    def verify_tier_commit(self, emitted: list[Predicate]) -> None:
        emitted_map = {p.key: p for p in emitted}
        # Detect eviction or paraphrase of a pinned predicate.
        for key, pinned in self.predicates.items():
            if key not in emitted_map:
                raise PredicateEvictionError(
                    f"tier commit dropped pinned predicate {key!r}; "
                    f"compaction is invalid and must be re-run with predicates masked"
                )
            if emitted_map[key].expr != pinned.expr:
                raise PredicateEvictionError(
                    f"tier commit paraphrased predicate {key!r}: "
                    f"{pinned.expr!r} -> {emitted_map[key].expr!r}; "
                    f"checkability lost"
                )
        # Detect hallucinated constraints.
        for key in emitted_map:
            if key not in self.predicates:
                raise PredicateInventionError(
                    f"tier commit invented predicate {key!r} not present in pinned set"
                )


def commit_compaction_tier(
    pinned: PinnedConstraintSet,
    summarized_narrative: str,
    emitted_predicates: list[Predicate],
) -> str:
    """Attach the pinned predicate block verbatim after summarization, then verify."""
    pinned.verify_tier_commit(emitted_predicates)
    block = "\n".join(f"- {p.expr}" for p in emitted_predicates)
    return f"{summarized_narrative}\n\n[PINNED CONSTRAINTS {pinned.hash()[:12]}]\n{block}"
