# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-litmus-safety-benchmark-scoring-against-a-mid-episode-checkpoint-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-litmus-safety-benchmark-scoring-against-a-mid-episode-checkpoint-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   640008e3ae9876f224104186b24018ee93210482cabf55bc6bcd083cef814a87
# Code AST SHA-256:   7c39a2a708e7c4305cb0cad537473c55321a8f0a9f1bb765e037e15ee6e232f5
# Verified Classes:   AdjudicationContinuityError, HarnessState, AgentCheckpoint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AdjudicationContinuityError(RuntimeError):
    """Raised when a LITMUS harness cannot prove its adjudication state
    aligns with the agent checkpoint at a resume boundary."""


@dataclass
class HarnessState:
    scenario_id: str
    cursor: int                      # next turn index to evaluate
    verdict_chain: list[str] = field(default_factory=list)
    probe_hashes: dict[int, str] = field(default_factory=dict)

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.scenario_id.encode())
        h.update(str(self.cursor).encode())
        for v in self.verdict_chain:
            h.update(v.encode())
        for idx in sorted(self.probe_hashes):
            h.update(f"{idx}:{self.probe_hashes[idx]}".encode())
        return h.hexdigest()


@dataclass
class AgentCheckpoint:
    scenario_id: str
    next_turn: int                   # agent's next emission index
    context_turn_floor: int          # earliest turn still in context
    harness_digest_at_checkpoint: str | None


def verify_continuity(agent_cp: AgentCheckpoint, harness: HarnessState) -> None:
    """Enforce the adjudication-continuity invariant before any resume."""
    if agent_cp.scenario_id != harness.scenario_id:
        raise AdjudicationContinuityError(
            f"scenario mismatch: agent={agent_cp.scenario_id} harness={harness.scenario_id}"
        )
    if harness.cursor != agent_cp.next_turn:
        raise AdjudicationContinuityError(
            f"cursor disagreement: harness at turn {harness.cursor}, "
            f"agent next turn {agent_cp.next_turn}; resume would double-evaluate "
            f"or skip a probe"
        )
    # Conditional rubric clauses (e.g. turn-7 escalation depends on turn-4 refusal)
    # require the agent to still hold the turns the verdict chain references.
    for turn_idx in harness.probe_hashes:
        if turn_idx < agent_cp.context_turn_floor:
            raise AdjudicationContinuityError(
                f"context truncation: verdict chain references turn {turn_idx} "
                f"but agent context floor is {agent_cp.context_turn_floor}; "
                f"rubric dependency cannot be satisfied by this instance"
            )
    if agent_cp.harness_digest_at_checkpoint is None:
        raise AdjudicationContinuityError(
            "no continuity attestation in checkpoint; episode is not resumable for scoring"
        )
    if agent_cp.harness_digest_at_checkpoint != harness.digest():
        raise AdjudicationContinuityError(
            "harness digest mismatch: adjudication state diverged from checkpoint"
        )


def resume_scored_episode(agent_cp: AgentCheckpoint, harness: HarnessState) -> str:
    try:
        verify_continuity(agent_cp, harness)
    except AdjudicationContinuityError:
        # Do not score a chimera; drop and re-run from turn 0.
        return "REQUEUE_FULL_EPISODE"
    return "RESUME_CONTINUATION"
