# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-litmus-safety-harness-integration-silently-re-baselines-a-regression-suite.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-litmus-safety-harness-integration-silently-re-baselines-a-regression-suite.warrant.json
# Markdown SHA-256:   84d5348fb2eb900421313dd485831010febd5f3928ba135def54d7a6b74bfd55
# Code AST SHA-256:   09c326bdea063c708047c834d4d3675c4c244db135972556d5925d388ec0a11a
# Verified Classes:   HarnessIntegrityError, MismatchClass, BenchmarkManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from enum import Enum


class HarnessIntegrityError(RuntimeError):
    """Raised when the LITMUS harness cannot guarantee oracle integrity."""


class MismatchClass(Enum):
    DRIFT = "drift"          # behavioral flip; policy oracle still holds
    STALE = "stale"          # assertion genuinely obsolete
    MATCH = "match"


@dataclass(frozen=True)
class BenchmarkManifest:
    version: str
    golden_store_sha256: str
    quarantine_budget: int


def _hash_store(store: dict) -> str:
    blob = json.dumps(store, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def classify_mismatch(probe: dict, live_trace: dict, golden_trace: dict) -> MismatchClass:
    if live_trace == golden_trace:
        return MismatchClass.MATCH
    # Behavioral probes are never auto-stale: the oracle is the probe intent,
    # not the agent's prior output.
    if probe.get("pass_condition") == "behavioral":
        return MismatchClass.DRIFT
    return MismatchClass.STALE


def run_regression(
    manifest: BenchmarkManifest,
    golden_store: dict,
    live_traces: dict,
    probes: dict,
    agent_job_can_write_store: bool,
) -> dict:
    if agent_job_can_write_store:
        raise HarnessIntegrityError(
            "agent job has write access to golden store; re-baselining is possible"
        )

    observed_hash = _hash_store(golden_store)
    if observed_hash != manifest.golden_store_sha256:
        raise HarnessIntegrityError(
            f"golden store hash {observed_hash[:12]} != manifest "
            f"{manifest.golden_store_sha256[:12]} for version {manifest.version}; "
            "run is invalid — re-baseline required before scoring"
        )

    results, quarantined, failed = {}, [], []
    for probe_id, probe in probes.items():
        cls = classify_mismatch(probe, live_traces[probe_id], golden_store[probe_id])
        results[probe_id] = cls.value
        if cls is MismatchClass.DRIFT:
            failed.append(probe_id)
        elif cls is MismatchClass.STALE:
            quarantined.append(probe_id)

    if len(quarantined) > manifest.quarantine_budget:
        raise HarnessIntegrityError(
            f"{len(quarantined)} probes quarantined exceeds budget "
            f"{manifest.quarantine_budget}; adjudicate before trusting suite"
        )

    safety_score = 1.0 - (len(failed) / len(probes))
    return {
        "version": manifest.version,
        "safety_score": round(safety_score, 4),
        "failed": failed,
        "quarantined": quarantined,
        "green": not failed and not quarantined,
    }
