# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-a-litmus-safety-benchmark-verdict-after-harness-re-integration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-a-litmus-safety-benchmark-verdict-after-harness-re-integration.warrant.json
# Markdown SHA-256:   7aec8b795d6221a4740dbb916dd57c95155fa89bbe0946ddff24b7e38feb4b3e
# Code AST SHA-256:   02257d51d22890fa0f3a35e455a8b763a30d06a31b4407e5e0033379fe54e107
# Verified Classes:   VerdictProvenanceError, VerdictTuple, LitmusVerdict
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class VerdictProvenanceError(RuntimeError):
    """Raised when a LITMUS verdict cannot be attributed to the exact
    (harness, target, seed-manifest, judge) tuple a gate is about to trust."""


@dataclass(frozen=True)
class VerdictTuple:
    harness_commit: str
    target_artifact_hash: str
    seed_manifest_hash: str
    judge_model_id: str
    judge_prompt_hash: str

    def tuple_hash(self) -> str:
        payload = json.dumps(
            {
                "harness_commit": self.harness_commit,
                "target_artifact_hash": self.target_artifact_hash,
                "seed_manifest_hash": self.seed_manifest_hash,
                "judge_model_id": self.judge_model_id,
                "judge_prompt_hash": self.judge_prompt_hash,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class LitmusVerdict:
    tuple_hash: str
    completion_status: str          # "COMPLETE" | "PARTIAL" | "CRASHED"
    seeds_executed: int
    seed_manifest_length: int
    per_seed_results: dict          # seed_index -> result
    score: float
    emitted_at_ns: int


def assert_verdict_trustworthy(
    verdict: LitmusVerdict,
    expected: VerdictTuple,
    latest_input_mtime_ns: int,
) -> None:
    """Fail-closed gate: raise unless the verdict is valid evidence about `expected`."""
    if verdict.tuple_hash != expected.tuple_hash():
        raise VerdictProvenanceError(
            f"tuple mismatch: verdict={verdict.tuple_hash[:12]} "
            f"expected={expected.tuple_hash()[:12]}"
        )
    if verdict.completion_status != "COMPLETE":
        raise VerdictProvenanceError(
            f"incomplete run: status={verdict.completion_status}"
        )
    if verdict.seeds_executed != verdict.seed_manifest_length:
        raise VerdictProvenanceError(
            f"seed count mismatch: executed={verdict.seeds_executed} "
            f"manifest={verdict.seed_manifest_length}"
        )
    if len(verdict.per_seed_results) != verdict.seed_manifest_length:
        raise VerdictProvenanceError(
            "per-seed result records missing; count-only completion is not evidence"
        )
    if verdict.emitted_at_ns <= latest_input_mtime_ns:
        raise VerdictProvenanceError(
            "verdict predates one of its declared inputs; stale evidence"
        )


def resume_checkpoint(
    checkpoint: dict,
    current: VerdictTuple,
) -> int:
    """Return next seed index to execute, or refuse on manifest mutation."""
    if checkpoint["seed_manifest_hash"] != current.seed_manifest_hash:
        raise VerdictProvenanceError(
            "refusing to resume across seed-manifest mutation: "
            f"checkpoint={checkpoint['seed_manifest_hash'][:12]} "
            f"current={current.seed_manifest_hash[:12]}"
        )
    if checkpoint["harness_commit"] != current.harness_commit:
        raise VerdictProvenanceError(
            "refusing to resume across harness version change"
        )
    return checkpoint["next_seed_index"]
