# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-style-continuous-safety-eval-has-silently-decoupled-from-the-deployed-policy-it-claims-to-measure.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-style-continuous-safety-eval-has-silently-decoupled-from-the-deployed-policy-it-claims-to-measure.warrant.json
# Markdown SHA-256:   c0bbb79d3d07a44d26052f7fa34166b342f5559d568571127b1f1d82ea68bedf
# Code AST SHA-256:   4f9ddba89b3ef5c72f362a5c64606efd1a1ec9978e8f1cd909d19faf44629a88
# Verified Classes:   EvalTargetDecoupled, ProbeResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EvalTargetDecoupled(RuntimeError):
    """Raised when the eval target does not match the artifact under test."""
    pass


@dataclass(frozen=True)
class ProbeResult:
    target_digest: str
    envelope_hash: str
    score: float
    variance: float


def gate_promotion(
    candidate_digest: str,
    candidate_envelope_hash: str,
    probe: ProbeResult,
    score_threshold: float = 0.90,
    variance_band: float = 0.05,
) -> bool:
    # Identity invariant: the eval must have measured the candidate artifact
    # through the same request envelope as production. Fail closed otherwise.
    if probe.target_digest != candidate_digest:
        raise EvalTargetDecoupled(
            f"eval measured digest {probe.target_digest!r} but candidate is "
            f"{candidate_digest!r}; score {probe.score:.3f} is evidence about "
            f"the wrong policy and must not open the gate"
        )
    if probe.envelope_hash != candidate_envelope_hash:
        raise EvalTargetDecoupled(
            f"eval envelope {probe.envelope_hash!r} diverges from production "
            f"envelope {candidate_envelope_hash!r}; probe is measuring a "
            f"different policy configuration"
        )
    # Only now is the score admissible as evidence.
    if probe.score < score_threshold:
        return False
    if probe.variance > variance_band:
        return False
    return True


def check_drift_series(digest_series, deploy_events):
    """Alert when target digest changes without a recorded deployment."""
    for prev, curr in zip(digest_series, digest_series[1:]):
        if prev != curr and curr not in deploy_events:
            raise EvalTargetDecoupled(
                f"eval target digest changed {prev!r} -> {curr!r} with no "
                f"deploy event; silent decoupling detected"
            )
    return True
