# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-litmus-verdict-the-adversarial-skill-probe-that-silently-inverts-its-own-label-under-multi-turn-context-carryov.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-litmus-verdict-the-adversarial-skill-probe-that-silently-inverts-its-own-label-under-multi-turn-context-carryov.warrant.json
# Markdown SHA-256:   e08635913402f415c0fab12b09bc74dfdd4dc1449cee87bbcac0fe7b21033bc2
# Code AST SHA-256:   d7d81df0bd69bc285fb4770ed6fa128f8806a6e6269582f4d9f4712067f35991
# Verified Classes:   InadmissibleVerdictError, Turn, Probe
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class InadmissibleVerdictError(RuntimeError):
    """Raised when a LITMUS verdict cannot be proven admissible."""


@dataclass(frozen=True)
class Turn:
    role: str
    content: str
    tool_payload: str = ""

    def fingerprint(self) -> str:
        h = hashlib.sha256()
        h.update(self.role.encode())
        h.update(b"\x00")
        h.update(self.content.encode())
        h.update(b"\x00")
        h.update(self.tool_payload.encode())
        return h.hexdigest()


@dataclass(frozen=True)
class Probe:
    probe_id: str
    authoring_turns: Sequence[Turn]   # non-agent turns frozen with the expectation
    authoring_system_hash: str


def assert_admissible(
    probe: Probe,
    judge_turns: Sequence[Turn],
    judge_system_hash: str,
) -> None:
    """Enforce context-equivalence between authoring and judging windows.

    Raises InadmissibleVerdictError on any divergence; never returns a
    best-effort verdict.
    """
    if judge_system_hash != probe.authoring_system_hash:
        raise InadmissibleVerdictError(
            f"{probe.probe_id}: system hash mismatch "
            f"({judge_system_hash[:12]} != {probe.authoring_system_hash[:12]})"
        )

    authoring_non_agent = [
        t.fingerprint() for t in probe.authoring_turns if t.role != "assistant"
    ]
    judge_non_agent = [
        t.fingerprint() for t in judge_turns if t.role != "assistant"
    ]

    if authoring_non_agent != judge_non_agent:
        # Locate the first divergence for the operator.
        for i, (a, j) in enumerate(zip(authoring_non_agent, judge_non_agent)):
            if a != j:
                raise InadmissibleVerdictError(
                    f"{probe.probe_id}: non-agent turn {i} diverged "
                    f"(authoring={a[:12]} judge={j[:12]}) — likely "
                    f"cross-probe carryover or preamble dedup"
                )
        raise InadmissibleVerdictError(
            f"{probe.probe_id}: non-agent turn count mismatch "
            f"(authoring={len(authoring_non_agent)} "
            f"judge={len(judge_non_agent)}) — likely truncation"
        )

    # Any assistant turn in the judge window must belong to this probe only;
    # the caller guarantees that by passing a single-probe transcript.
    # If a foreign probe leaked, its stimulus appears as a non-agent turn
    # above and is already caught. This is the structural guarantee.


def score_probe(
    probe: Probe,
    judge_turns: Sequence[Turn],
    judge_system_hash: str,
    raw_verdict: str,
) -> str:
    assert_admissible(probe, judge_turns, judge_system_hash)
    if raw_verdict not in {"PASS", "FAIL"}:
        raise InadmissibleVerdictError(
            f"{probe.probe_id}: non-binary verdict {raw_verdict!r}"
        )
    return raw_verdict  # only reachable if context-equivalence held
