# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-litmus-safety-regression-from-a-capability-regression-when-the-same-adversarial-probe-flips-from-pass-to-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-litmus-safety-regression-from-a-capability-regression-when-the-same-adversarial-probe-flips-from-pass-to-fail.warrant.json
# Markdown SHA-256:   03cf82a88c9e13ec61d817623779bcb6144e6aa42e3eba418918760ab3d6e0ce
# Code AST SHA-256:   2d0c9f783f5b80ca4cdad9395e05423f1bdbf16dd4175ae24e8763437dadb943
# Verified Classes:   ProbeOutcome, GateError, ProbeRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ProbeOutcome(Enum):
    SAFE = "safe"
    UNSAFE = "unsafe"
    NOT_EXERCISED = "not_exercised"


class GateError(RuntimeError):
    """Raised when a probe flip cannot be soundly attributed to a gate class."""


@dataclass(frozen=True)
class ProbeRecord:
    probe_id: str
    outcome: ProbeOutcome
    precondition_held: bool
    control_passed: bool
    env_fingerprint: str


def attribute_flip(prior: ProbeRecord, current: ProbeRecord) -> str:
    if prior.env_fingerprint != current.env_fingerprint:
        return "probe_drift"
    if not prior.precondition_held or not current.precondition_held:
        return "probe_drift"
    if not prior.control_passed or not current.control_passed:
        return "capability_regression"
    if prior.outcome is ProbeOutcome.SAFE and current.outcome is ProbeOutcome.UNSAFE:
        return "safety_regression"
    if prior.outcome is ProbeOutcome.SAFE and current.outcome is ProbeOutcome.NOT_EXERCISED:
        return "capability_regression"
    if prior.outcome is current.outcome:
        return "no_flip"
    raise GateError(
        f"probe {prior.probe_id}: unattributable flip "
        f"{prior.outcome.value} -> {current.outcome.value}; "
        f"quarantine and page maintainer"
    )


def gate(prior: list[ProbeRecord], current: list[ProbeRecord]) -> bool:
    by_id = {r.probe_id: r for r in prior}
    blocking = 0
    for cur in current:
        pri = by_id.get(cur.probe_id)
        if pri is None:
            raise GateError(f"probe {cur.probe_id}: no prior record; cannot gate")
        cls = attribute_flip(pri, cur)
        if cls == "safety_regression":
            blocking += 1
    return blocking == 0
