# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-litmus-safety-benchmark-harness-contamination-when-the-regression-gate-s-own-probe-corpus-has-been-silently-poisoned-by-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-litmus-safety-benchmark-harness-contamination-when-the-regression-gate-s-own-probe-corpus-has-been-silently-poisoned-by-th.warrant.json
# Markdown SHA-256:   730bd98f261f8c1b5d660be726721f50003ceed2525035929c22de5c1a01b725
# Code AST SHA-256:   4e0aa6eb87161a31cae947419bc72d5b93337bd9fa204ce3cf677aa2b862e748
# Verified Classes:   CorpusContaminationError, ProbeManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from pathlib import Path


class CorpusContaminationError(RuntimeError):
    """Raised when the probe corpus no longer matches its signed manifest."""
    pass


@dataclass(frozen=True)
class ProbeManifest:
    probe_id: str
    sha256: str
    severity: str


def load_manifest(manifest_path: Path) -> dict[str, ProbeManifest]:
    raw = json.loads(manifest_path.read_text())
    return {
        entry["probe_id"]: ProbeManifest(
            probe_id=entry["probe_id"],
            sha256=entry["sha256"],
            severity=entry["severity"],
        )
        for entry in raw["probes"]
    }


def verify_corpus(corpus_dir: Path, manifest: dict[str, ProbeManifest]) -> None:
    """Verify every probe file against the signed manifest BEFORE scoring.

    This is the invariant: scoring must never read a probe whose current
    bytes differ from the manifest frozen before the agent ran. A mismatch
    is a harness integrity failure, not a scoring event.
    """
    seen: set[str] = set()
    for probe_path in sorted(corpus_dir.glob("*.yaml")):
        probe_id = probe_path.stem
        if probe_id not in manifest:
            raise CorpusContaminationError(
                f"probe {probe_id!r} present on disk but absent from manifest; "
                f"agent may have injected a new probe"
            )
        seen.add(probe_id)
        actual = hashlib.sha256(probe_path.read_bytes()).hexdigest()
        expected = manifest[probe_id].sha256
        if actual != expected:
            raise CorpusContaminationError(
                f"probe {probe_id!r} hash mismatch: "
                f"expected {expected[:12]}..., got {actual[:12]}...; "
                f"corpus was mutated after manifest freeze (score is invalid)"
            )
    missing = set(manifest) - seen
    if missing:
        raise CorpusContaminationError(
            f"probes present in manifest but missing on disk: {sorted(missing)}; "
            f"agent may have deleted probes it could not pass"
        )


def run_gate(
    corpus_dir: Path,
    manifest_path: Path,
    agent_workspace: Path,
    score_fn,
) -> dict:
    """Run the regression gate with the instrument-integrity invariant enforced."""
    # Boundary check: the agent's writable workspace must not resolve into
    # the corpus directory. This is a cheap guard; the real guarantee is the
    # mount-level separation, but we assert it here so a misconfigured mount
    # fails loud rather than silently poisoning the corpus.
    if agent_workspace.resolve().is_relative_to(corpus_dir.resolve()):
        raise CorpusContaminationError(
            f"agent workspace {agent_workspace} resolves inside corpus dir "
            f"{corpus_dir}; scoring read-path and agent write-path overlap"
        )
    if corpus_dir.resolve().is_relative_to(agent_workspace.resolve()):
        raise CorpusContaminationError(
            f"corpus dir {corpus_dir} resolves inside agent workspace "
            f"{agent_workspace}; agent can rewrite its own exam"
        )

    manifest = load_manifest(manifest_path)
    verify_corpus(corpus_dir, manifest)  # halts before any scoring
    return score_fn(corpus_dir, manifest)
