# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-scratchpad-under-a-policy-constraint-mid-execution-the-self-edit-monotonicity-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-scratchpad-under-a-policy-constraint-mid-execution-the-self-edit-monotonicity-violation.warrant.json
# Markdown SHA-256:   2bcc007df0309e3b1821784d53b1baac8677c633896d80996b44b418352e21e8
# Code AST SHA-256:   115bc523b1e90b77f3471539e9e4617ddaa8791aa29bffbc37ba3cf8807baa4f
# Verified Classes:   SelfEditEntailmentViolation, Premise, ScratchpadSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Set


class SelfEditEntailmentViolation(RuntimeError):
    """Raised when a self-edit retracts a premise that has live dependents,
    or when replay across snapshots produces a divergent answer."""
    pass


@dataclass
class Premise:
    pid: str
    text: str
    depends_on: Set[str] = field(default_factory=set)


@dataclass
class ScratchpadSnapshot:
    premises: Dict[str, Premise]
    digest: str


def snapshot(premises: Dict[str, Premise]) -> ScratchpadSnapshot:
    payload = "|".join(
        f"{p.pid}:{p.text}:{sorted(p.depends_on)}" for p in sorted(premises.values(), key=lambda x: x.pid)
    )
    return ScratchpadSnapshot(premises=dict(premises), digest=hashlib.sha256(payload.encode()).hexdigest())


def check_edit_preserves_entailment(
    before: ScratchpadSnapshot, after: ScratchpadSnapshot
) -> None:
    """The load-bearing invariant: no premise with a live dependent may be
    removed by an edit. Compaction may drop leaves; it may not drop roots."""
    removed = set(before.premises) - set(after.premises)
    for pid in removed:
        dependents = [
            p.pid for p in after.premises.values() if pid in p.depends_on
        ]
        if dependents:
            raise SelfEditEntailmentViolation(
                f"edit removed premise {pid!r} but dependents {dependents!r} "
                f"still reference it; scratchpad is a valid state but not a "
                f"valid successor of {before.digest[:12]}"
            )


def replay_and_compare(
    snapshots: List[ScratchpadSnapshot], derive
) -> None:
    """Verification-time guard: the answer must be stable across snapshots.
    Catches salience shift that edit-time checks cannot see."""
    answers = {derive(s) for s in snapshots}
    if len(answers) > 1:
        raise SelfEditEntailmentViolation(
            f"answer diverged across {len(snapshots)} snapshots: {answers!r}; "
            f"a self-edit changed effective constraint priority without "
            f"changing text"
        )


# Example trigger:
pre = {"p1": Premise("p1", "table B is append-only"),
       "p2": Premise("p2", "row 4471 is max", depends_on={"p1"})}
post = {"p2": Premise("p2", "row 4471 is max", depends_on={"p1"})}
check_edit_preserves_entailment(snapshot(pre), snapshot(post))  # raises
