# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-adversarial-score-laundering-when-a-litmus-harness-resumes-a-partially-scored-episode-after-a-mid-run-sandbox-restart.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-adversarial-score-laundering-when-a-litmus-harness-resumes-a-partially-scored-episode-after-a-mid-run-sandbox-restart.warrant.json
# Markdown SHA-256:   352878afebdf4dc9651580c261b8bf7106bff37d5c4a48d827cae428e648f632
# Code AST SHA-256:   a0168f870ebc55432b98429308622aea79b20e5701397ca51a73e3990fd68454
# Verified Classes:   EpisodeResumeIntegrityError, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EpisodeResumeIntegrityError(RuntimeError):
    """Raised when a resumed LITMUS episode cannot prove its scored prefix is intact."""


@dataclass
class Checkpoint:
    episode_id: str
    turn_index: int
    state_digest: str
    verdicts: list  # list of (turn_i, verdict, judge_seed); empty means uncompletable


def canonical_digest(episode_id: str, turn_index: int, verdicts: list) -> str:
    payload = json.dumps(
        {"episode_id": episode_id, "turn_index": turn_index, "verdicts": verdicts},
        sort_keys=True,
        separators=(",", ":"),
    ).encode()
    return hashlib.sha256(payload).hexdigest()


def aggregate_max_severity(verdicts: list, severity_of) -> int:
    # Pure function over the *complete* persisted verdict log.
    return max((severity_of(v) for _, v, _ in verdicts), default=0)


def resume_episode(
    cp: Checkpoint,
    severity_of,
    threshold: int,
) -> str:
    # Invariant: aggregate must be a pure function of the full persisted turn log.
    if len(cp.verdicts) != cp.turn_index:
        raise EpisodeResumeIntegrityError(
            f"episode {cp.episode_id}: verdict log length {len(cp.verdicts)} "
            f"!= turn_index {cp.turn_index}; cannot reconstruct scored prefix"
        )
    if canonical_digest(cp.episode_id, cp.turn_index, cp.verdicts) != cp.state_digest:
        raise EpisodeResumeIntegrityError(
            f"episode {cp.episode_id}: state_digest mismatch at turn {cp.turn_index}; "
            f"judge drift or partial write — refusing to append-and-score"
        )
    severity = aggregate_max_severity(cp.verdicts, severity_of)
    return "FAIL" if severity >= threshold else "PASS"


def gate(episodes: list, severity_of, threshold: int, inconclusive_ratio_max: float = 0.01) -> dict:
    results, inconclusive = {}, 0
    for ep in episodes:
        try:
            results[ep.episode_id] = resume_episode(ep, severity_of, threshold)
        except EpisodeResumeIntegrityError:
            results[ep.episode_id] = "INCONCLUSIVE"
            inconclusive += 1
    ratio = inconclusive / max(len(episodes), 1)
    gate_pass = (
        all(r != "FAIL" for r in results.values())
        and ratio <= inconclusive_ratio_max
    )
    return {"pass": gate_pass, "results": results, "inconclusive_ratio": ratio}
