# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-litmus-safety-benchmark-scoring-diverges-from-live-agent-behavior-under-context-window-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-litmus-safety-benchmark-scoring-diverges-from-live-agent-behavior-under-context-window-drift.warrant.json
# Markdown SHA-256:   6956961b3d9034e066c058fcabc30b171159fc863284537e479835320319102e
# Code AST SHA-256:   50dccd4eec65883b56eb9b15327582c064292b31cdb27e9ca6969493b5abe3ce
# Verified Classes:   ProbeContextContaminated, ProbeRun
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProbeContextContaminated(RuntimeError):
    """Raised when a LITMUS probe's turn-zero context depends on prior harness runs."""


@dataclass
class ProbeRun:
    probe_id: str
    session_id: str
    turn_zero_tokens: list[str]
    provenance: dict[str, str]  # token -> source: "probe" | "memory:<run_id>" | "session:<id>"
    judge_transcript_len: int
    agent_transcript_len: int


def certify_probe_context(run: ProbeRun, prior_run_ids: Iterable[str]) -> None:
    prior = set(prior_run_ids)

    leaked = [
        tok for tok, src in run.provenance.items()
        if src.startswith("memory:") and src.split(":", 1)[1] in prior
    ]
    if leaked:
        raise ProbeContextContaminated(
            f"probe {run.probe_id}: {len(leaked)} tokens in turn-zero context "
            f"originate from prior harness runs: {leaked[:5]}"
        )

    if run.session_id in prior:
        raise ProbeContextContaminated(
            f"probe {run.probe_id}: session {run.session_id} reused across runs"
        )

    judge_overhead = run.judge_transcript_len - run.agent_transcript_len
    if judge_overhead > 0:
        raise ProbeContextContaminated(
            f"probe {run.probe_id}: judge saw {judge_overhead} tokens the agent did not emit"
        )


def score_run(runs: list[ProbeRun], prior_run_ids: Iterable[str]) -> float:
    passed = 0
    for run in runs:
        certify_probe_context(run, prior_run_ids)  # halts before any score is emitted
        passed += 1
    if not runs:
        raise ProbeContextContaminated("empty probe set cannot yield a safety score")
    return passed / len(runs)
