# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-harness-contamination-when-a-litmus-adversarial-probe-mutates-the-grader-state-it-is-being-scored-against.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-harness-contamination-when-a-litmus-adversarial-probe-mutates-the-grader-state-it-is-being-scored-against.warrant.json
# Markdown SHA-256:   985da1785dd73dde11c6fb6453968b0a7be724bf8b2e8c9672465f11d105be79
# Code AST SHA-256:   3888765964d2c97ba6a0a9978df6717dc603b737c1cbef70ea38f3619ca99c2f
# Verified Classes:   HarnessContaminationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from pathlib import Path
from typing import Iterable


class HarnessContaminationError(RuntimeError):
    """Raised when grader inputs were mutated during a probe suite.

    This is a suite-level failure, not a per-probe failure. The entire
    run must be discarded; partial invalidation is unsafe because
    post-mutation passes are indistinguishable from genuine passes.
    """


GRADER_INPUTS = (
    Path("rubrics/safety_v3.yaml"),
    Path("config/thresholds.json"),
)


def _digest(paths: Iterable[Path]) -> dict[str, str]:
    return {
        str(p): hashlib.sha256(p.read_bytes()).hexdigest()
        for p in paths
        if p.exists()
    }


def pin_grader_state(paths: Iterable[Path] = GRADER_INPUTS) -> dict[str, str]:
    """Pin grader input hashes at suite start. Must be called before probe #1."""
    pinned = _digest(paths)
    if not pinned:
        raise HarnessContaminationError(
            "grader inputs missing at suite start; cannot establish integrity baseline"
        )
    return pinned


def verify_grader_integrity(
    pinned: dict[str, str],
    paths: Iterable[Path] = GRADER_INPUTS,
) -> None:
    """Post-suite integrity gate. Raises on any drift from the pinned digest."""
    current = _digest(paths)
    if set(current) != set(pinned):
        raise HarnessContaminationError(
            f"grader input set changed during suite: "
            f"pinned={sorted(pinned)} current={sorted(current)}"
        )
    for path, expected in pinned.items():
        if current[path] != expected:
            raise HarnessContaminationError(
                f"grader input mutated during suite: {path} "
                f"(pinned={expected[:12]} current={current[path][:12]}) "
                f"— suite INVALID, discard all probe results"
            )


def run_suite(probes, agent, grader) -> dict:
    pinned = pin_grader_state()
    results = []
    try:
        for probe in probes:
            response = agent.respond(probe)
            results.append(grader.score(probe, response))
    finally:
        # Integrity check runs even if a probe raised, so a mid-suite
        # mutation cannot be masked by an unrelated exception.
        verify_grader_integrity(pinned)
    return {"status": "VALID", "results": results}
