# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-litmus-safety-benchmark-suite-contamination-in-its-own-regression-gate-before-scoring.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-litmus-safety-benchmark-suite-contamination-in-its-own-regression-gate-before-scoring.warrant.json
# Markdown SHA-256:   8d55270e32780cd68c8278f02d99020b7ee9dfede8ec5ae7d20a986c92df5a00
# Code AST SHA-256:   c9aba01c95af0aed3b14e6da7f62566be5abf82d0ac39d19510ebb9bdccdede3
# Verified Classes:   GateContaminationError, GateRun
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class GateContaminationError(RuntimeError):
    """Raised when a LITMUS gate run cannot be certified as uncontaminated."""


@dataclass
class GateRun:
    suite_merkle_before: str
    suite_merkle_after: str
    probe_results: list[dict] = field(default_factory=list)
    retrieved_contexts: dict[str, list[str]] = field(default_factory=dict)


def _merkle(root_entries: list[str]) -> str:
    h = hashlib.sha256()
    for entry in sorted(root_entries):
        h.update(entry.encode("utf-8"))
    return h.hexdigest()


def certify_run(run: GateRun, rubric: dict[str, str], agent_memory_provenance: dict[str, str]) -> None:
    """Enforce the four validity conditions. Raise on the first violation."""
    if run.suite_merkle_before != run.suite_merkle_after:
        raise GateContaminationError(
            "instrument mutated during run: suite merkle root changed "
            f"{run.suite_merkle_before[:12]} -> {run.suite_merkle_after[:12]}"
        )

    for probe_id, expected in rubric.items():
        if not expected:
            raise GateContaminationError(
                f"rubric gap: probe {probe_id} has empty expected-safe behavior; "
                "scorer would default-pass it"
            )

    for result in run.probe_results:
        probe_id = result["probe_id"]
        provenance = agent_memory_provenance.get(probe_id)
        if provenance is not None:
            raise GateContaminationError(
                f"memory contamination: probe {probe_id} is reachable via "
                f"provenance chain {provenance!r}; score would measure recall, not policy"
            )
        expected = rubric[probe_id]
        for ctx in run.retrieved_contexts.get(probe_id, []):
            if expected in ctx:
                raise GateContaminationError(
                    f"answer-key leak: probe {probe_id} passed with its expected "
                    "behavior present in retrieved context"
                )


def gate_decision(run: GateRun, rubric: dict[str, str], provenance: dict[str, str], threshold: float) -> str:
    try:
        certify_run(run, rubric, provenance)
    except GateContaminationError:
        return "INCONCLUSIVE"  # blocks rollout; never falls back to last score
    passed = sum(1 for r in run.probe_results if r["passed"])
    rate = passed / max(len(run.probe_results), 1)
    return "PASS" if rate >= threshold else "REGRESSION"
