# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-litmus-safety-probe-against-a-drifted-policy-snapshot-the-verdict-staleness-invariant-in-ci-red-team-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-litmus-safety-probe-against-a-drifted-policy-snapshot-the-verdict-staleness-invariant-in-ci-red-team-gating.warrant.json
# Markdown SHA-256:   a437e3062e06ae4679d1a7ae5a09cc1d315430c66522ed9d1f3bf5ce7183d8eb
# Code AST SHA-256:   8707191095959e602b17cf40c6b94a5960e78be8279960fc22ca28568fe67f66
# Verified Classes:   VerdictStalenessError, Probe, Verdict, Build
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class VerdictStalenessError(RuntimeError):
    """Raised when a regression gate attempts to compare verdicts bound to
    different policy snapshots without an explicit invariance warrant."""


@dataclass(frozen=True)
class Probe:
    transcript: str

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.transcript.encode()).hexdigest()


@dataclass(frozen=True)
class Verdict:
    probe_hash: str
    policy_hash: str
    passed: bool
    failure_mode: Optional[str]
    samples: int
    variance: float


@dataclass(frozen=True)
class Build:
    policy_hash: str


def gate(
    probe: Probe,
    baseline: Optional[Verdict],
    candidate: Verdict,
    build: Build,
    invariance_warrant: Optional[str] = None,
) -> bool:
    if baseline is None:
        # Fail-closed: no baseline for this (probe, policy) pair.
        raise VerdictStalenessError(
            f"no baseline for probe {probe.content_hash[:12]} under "
            f"policy {build.policy_hash[:12]}; refusing to gate"
        )

    if baseline.probe_hash != probe.content_hash:
        raise VerdictStalenessError(
            "baseline probe hash does not match current probe content; "
            "probe was mutated without re-baselining"
        )

    if baseline.policy_hash != build.policy_hash:
        if invariance_warrant is None:
            raise VerdictStalenessError(
                f"baseline bound to policy {baseline.policy_hash[:12]} but "
                f"build is {build.policy_hash[:12]}; no invariance warrant"
            )
        # Warrant present: caller has asserted probe semantics are invariant
        # across the policy delta. Still require distribution comparison.

    if candidate.policy_hash != build.policy_hash:
        raise VerdictStalenessError(
            "candidate verdict not bound to the build under test"
        )

    if baseline.samples < 3 or candidate.samples < 3:
        raise VerdictStalenessError(
            "insufficient samples for distributional comparison; "
            "single-sample verdicts conflate drift with noise"
        )

    # Regression: passed before, fails now.
    if baseline.passed and not candidate.passed:
        return False

    # Drift: verdict unchanged but failure mode changed.
    if baseline.passed == candidate.passed and baseline.failure_mode != candidate.failure_mode:
        raise VerdictStalenessError(
            f"failure_mode drift at unchanged verdict: "
            f"{baseline.failure_mode} -> {candidate.failure_mode}; "
            "route to human triage, do not auto-pass"
        )

    return True
