# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-refusal-calibration-drifts-between-litmus-probe-replay-and-live-regression-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-refusal-calibration-drifts-between-litmus-probe-replay-and-live-regression-gating.warrant.json
# Markdown SHA-256:   d6e71b5256133390fc660c385a690277d3163712571a44a725e1232eeaf873bb
# Code AST SHA-256:   8bea7cb102a53f4100de71720936621888019117e9ea88aacb2d5de2d52be358
# Verified Classes:   EnvelopeMismatchError, BimodalProbeGateError, Envelope, ProbeCalibration, LiveResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Literal


class EnvelopeMismatchError(RuntimeError):
    """Raised when a probe is gated against a calibration band derived under a different execution envelope."""


class BimodalProbeGateError(RuntimeError):
    """Raised when a probe calibrated as unanimous is gated on a single sample but live verdicts are bimodal."""


@dataclass(frozen=True)
class Envelope:
    temperature: float
    top_p: float
    max_tokens: int
    tool_surface: tuple[str, ...]
    safety_directive_position: int
    judge_id: str

    def fingerprint(self) -> str:
        payload = json.dumps(
            {
                "temperature": self.temperature,
                "top_p": self.top_p,
                "max_tokens": self.max_tokens,
                "tool_surface": sorted(self.tool_surface),
                "safety_directive_position": self.safety_directive_position,
                "judge_id": self.judge_id,
            },
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class ProbeCalibration:
    probe_id: str
    envelope_fp: str
    expected_verdict: float
    tolerance: float
    determinism: Literal["deterministic", "stochastic"]
    samples: list[float] = field(default_factory=list)


@dataclass
class LiveResult:
    probe_id: str
    envelope_fp: str
    verdict: float


def gate_probe(
    cal: ProbeCalibration,
    live: LiveResult,
    live_envelope: Envelope,
    counterfactual_replay,
) -> str:
    if cal.envelope_fp != live.envelope_fp:
        # Counterfactual: re-run under calibration envelope against candidate build.
        cf_verdict = counterfactual_replay(cal.probe_id)
        if cf_verdict is None:
            raise EnvelopeMismatchError(
                f"probe {cal.probe_id}: envelope mismatch and no counterfactual replay available; "
                f"calibration={cal.envelope_fp[:8]} live={live.envelope_fp[:8]}"
            )
        if abs(cf_verdict - cal.expected_verdict) <= cal.tolerance:
            return "regime_local_spurious"
        return "build_attributable"

    if cal.determinism == "deterministic" and len(cal.samples) >= 8:
        if len(set(cal.samples)) > 1:
            raise BimodalProbeGateError(
                f"probe {cal.probe_id}: calibration marked deterministic but samples are bimodal "
                f"{sorted(set(cal.samples))}; promote to distributional gating"
            )

    if abs(live.verdict - cal.expected_verdict) > cal.tolerance:
        return "regression"
    return "pass"


def run_gate(
    calibrations: dict[str, ProbeCalibration],
    live_results: list[LiveResult],
    live_envelope: Envelope,
    counterfactual_replay,
) -> dict[str, str]:
    outcomes: dict[str, str] = {}
    for live in live_results:
        cal = calibrations[live.probe_id]
        outcomes[live.probe_id] = gate_probe(cal, live, live_envelope, counterfactual_replay)
    if any(o == "regression" for o in outcomes.values()):
        # Genuine build-attributable regressions block promotion.
        blocked = [p for p, o in outcomes.items() if o == "regression"]
        raise EnvelopeMismatchError(f"promotion blocked by build-attributable regressions: {blocked}")
    return outcomes
