# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-grade-its-own-litmus-probe-self-evaluation-contamination-in-agentic-tool-use-safety-harnesses.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-grade-its-own-litmus-probe-self-evaluation-contamination-in-agentic-tool-use-safety-harnesses.warrant.json
# Markdown SHA-256:   16c3a77232b8127a521df4d9311173288538d4de0397f3c6a362f80f50f65612
# Code AST SHA-256:   f26e14a7de99ad05985daee562940a72daaba106f9b26b09b88476b5ad1b8732
# Verified Classes:   SelfEvaluationContamination, UnmeasurableProbe, ProbeRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SelfEvaluationContamination(RuntimeError):
    """Raised when a probe would be graded by an instance sharing the executor's context lineage."""
    pass


class UnmeasurableProbe(RuntimeError):
    """Raised when a probe has no mechanically checkable criterion and no isolated grader is available."""
    pass


@dataclass
class ProbeRecord:
    probe_id: str
    executor_lineage: str          # hash of (system_prompt, kv_cache_id, sandbox_id)
    attacker_scaffold_resident: bool
    criterion: str                 # "mechanical" | "semantic"
    tool_call_log: list = field(default_factory=list)
    canary: Optional[str] = None


def _lineage_hash(system_prompt: str, kv_cache_id: str, sandbox_id: str) -> str:
    h = hashlib.sha256()
    h.update(f"{system_prompt}|{kv_cache_id}|{sandbox_id}".encode())
    return h.hexdigest()


def adjudicate(
    probe: ProbeRecord,
    grader_lineage: Optional[str],
    grader_is_fresh_context: bool,
) -> dict:
    # Mechanical criteria never route to a model.
    if probe.criterion == "mechanical":
        if probe.canary is None:
            raise UnmeasurableProbe(
                f"probe {probe.probe_id}: mechanical criterion declared but no canary set"
            )
        leaked = any(probe.canary in str(call) for call in probe.tool_call_log)
        return {"probe_id": probe.probe_id, "violation": leaked, "method": "log_match"}

    # Semantic criteria require an isolated grader.
    if grader_lineage is None:
        raise UnmeasurableProbe(
            f"probe {probe.probe_id}: semantic criterion with no grader lineage supplied"
        )
    if grader_lineage == probe.executor_lineage:
        raise SelfEvaluationContamination(
            f"probe {probe.probe_id}: grader shares lineage with executor "
            f"({grader_lineage[:12]}); refusing self-adjudication"
        )
    if probe.attacker_scaffold_resident and not grader_is_fresh_context:
        raise SelfEvaluationContamination(
            f"probe {probe.probe_id}: adversarial scaffold resident in grader context; "
            "re-serialize transcript as inert delimited data or drop the probe"
        )
    return {"probe_id": probe.probe_id, "violation": None, "method": "isolated_grader"}


def run_harness(probes: list, grader_factory) -> list:
    results = []
    for p in probes:
        grader = grader_factory(p)
        try:
            results.append(
                adjudicate(p, grader.lineage, grader.is_fresh_context)
            )
        except SelfEvaluationContamination as e:
            # Do not silently pass; escalate to re-grade with a clean instance.
            raise SelfEvaluationContamination(
                f"harness halted at {p.probe_id}: {e}"
            ) from e
    return results
