# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-edit-divergence-between-a-model-driven-context-summarizer-and-its-own-replay-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-edit-divergence-between-a-model-driven-context-summarizer-and-its-own-replay-witness.warrant.json
# Markdown SHA-256:   3746506094224afae1c932c63c5c45ff431f38e8d6ad8800aa96708c7a14d034
# Code AST SHA-256:   a78dbb77d6541c43eef22edce389c1ea4897e1eb774663e880af1421e00d6386
# Verified Classes:   PruneDivergenceError, Constraint, Witness
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class PruneDivergenceError(RuntimeError):
    """Raised when a model-driven prune drops or demotes an active constraint."""


@dataclass(frozen=True)
class Constraint:
    kind: Literal["prohibition", "requirement"]
    target: str
    scope: str          # e.g. "task", "subtask:<id>"
    status: Literal["active", "closed"]


@dataclass
class Witness:
    """Append-only, outside the pruner's write scope."""
    records: list[Constraint] = field(default_factory=list)

    def active(self) -> list[Constraint]:
        return [c for c in self.records if c.status == "active"]


def reconcile_prune(witness: Witness, live_window: list[Constraint]) -> None:
    """
    Gate a model-driven prune. Reject if any active witness constraint is
    absent from the live window OR present with demoted modal status/scope.
    String presence alone is NOT sufficient (the observed failure passes it).
    """
    live_by_target = {c.target: c for c in live_window}
    for wc in witness.active():
        lc = live_by_target.get(wc.target)
        if lc is None:
            raise PruneDivergenceError(
                f"active constraint {wc.target!r} vanished from pruned window"
            )
        if lc.kind != wc.kind:
            raise PruneDivergenceError(
                f"modal drift on {wc.target!r}: {wc.kind} -> {lc.kind}"
            )
        if lc.scope != wc.scope:
            raise PruneDivergenceError(
                f"scope drift on {wc.target!r}: {wc.scope} -> {lc.scope}"
            )
        # status demotion to "closed" is a legitimate close, not a prune fault;
        # but a live window must not silently reclassify an active constraint.
        if lc.status != "active":
            raise PruneDivergenceError(
                f"status drift on {wc.target!r}: active -> {lc.status}"
            )


def apply_prune(witness: Witness, proposed_window: list[Constraint]) -> list[Constraint]:
    try:
        reconcile_prune(witness, proposed_window)
    except PruneDivergenceError:
        # Reject the divergent window; caller must re-prune with pinned block.
        raise
    return proposed_window


if __name__ == "__main__":
    w = Witness([Constraint("prohibition", "prod-db", "task", "active")])
    # Pruner folded the prohibition into narrative: same target, wrong modality.
    bad = [Constraint("requirement", "prod-db", "task", "active")]
    apply_prune(w, bad)  # -> raises PruneDivergenceError
