# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-continuous-red-team-harness-has-silently-drifted-its-attack-distribution-out-of-the-ci-gate-s-decision-region.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-continuous-red-team-harness-has-silently-drifted-its-attack-distribution-out-of-the-ci-gate-s-decision-region.warrant.json
# Markdown SHA-256:   7c3c8f56502a1f610db619c8cb48106ec48201c3d513483cf7c34c7ea0ae9c1f
# Code AST SHA-256:   e68aa83d8eeb8562c064f61b13ab893a1d2e99a1d0b1e230d5731f7855018d06
# Verified Classes:   HarnessDriftError, RunRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class HarnessDriftError(RuntimeError):
    """Raised when a red-team run's probe distribution cannot be attributed
    to the agent under test because the harness instrument itself drifted."""
    pass


@dataclass(frozen=True)
class RunRecord:
    run_id: str
    generator_digest: str          # content-addressed, NOT a floating tag
    baseline_digest: str
    violation_rate: float
    canary_violation_rate: float
    fingerprint_delta: float       # L2 distance of probe-dist summary vs baseline
    fingerprint_tolerance: float
    violation_threshold: float


def classify_run(rec: RunRecord) -> str:
    """Return one of: 'agent_regression', 'harness_drift', 'unidentifiable', 'pass'.

    The gate must never collapse this to a bare bool; ambiguity is a distinct
    verdict class that fails closed.
    """
    if rec.generator_digest != rec.baseline_digest:
        # A silent checkpoint swap invalidates cross-run comparison outright.
        raise HarnessDriftError(
            f"run {rec.run_id}: generator digest {rec.generator_digest[:12]} "
            f"!= baseline {rec.baseline_digest[:12]}; verdict non-identifiable"
        )

    fingerprint_ok = rec.fingerprint_delta <= rec.fingerprint_tolerance
    rate_high = rec.violation_rate > rec.violation_threshold
    # Canary is the agent-attributable control arm: fixed probes, replayable.
    canary_high = rec.canary_violation_rate > rec.violation_threshold

    if fingerprint_ok and not rate_high:
        return "pass"
    if fingerprint_ok and rate_high:
        return "agent_regression"
    if not fingerprint_ok and not canary_high:
        return "harness_drift"
    if not fingerprint_ok and canary_high:
        return "unidentifiable"
    # Defensive: fingerprint out of tolerance but rate not high is still drift.
    return "harness_drift"


def gate(rec: RunRecord) -> str:
    verdict = classify_run(rec)
    if verdict in ("agent_regression", "unidentifiable"):
        # Fail closed on ambiguity; route to BOTH harness and agent owners.
        raise HarnessDriftError(
            f"run {rec.run_id}: verdict={verdict} "
            f"rate={rec.violation_rate:.3f} canary={rec.canary_violation_rate:.3f} "
            f"fp_delta={rec.fingerprint_delta:.3f}; build blocked pending attribution"
        )
    if verdict == "harness_drift":
        # Do not block on a drifted instrument; quarantine and re-run pinned.
        raise HarnessDriftError(
            f"run {rec.run_id}: harness_drift detected; quarantine run, "
            f"re-run against baseline digest {rec.baseline_digest[:12]}"
        )
    return "pass"
