# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-litmus-safety-benchmark-pass-as-non-transferable-across-a-model-swap-and-how-does-the-harness-s-warm-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-litmus-safety-benchmark-pass-as-non-transferable-across-a-model-swap-and-how-does-the-harness-s-warm-cache.warrant.json
# Markdown SHA-256:   c58f3918b333a3c6dd209bb5b4243d33bf9993e7c0c5119c6448a167697c9db7
# Code AST SHA-256:   a92df741bc368d3113e7cb0882bcd48c7f91ba74dbc54e8e2fdaa3730e8a7576
# Verified Classes:   StaleJudgeCacheError, RunManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleJudgeCacheError(RuntimeError):
    """Raised when a judge verdict would be replayed against a different agent
    than the one it was originally computed for."""
    pass


@dataclass(frozen=True)
class RunManifest:
    agent_build_digest: str
    judge_model_version: str
    fixture_seed: int
    generator_model_version: str


def judge_cache_key(
    fixture_id: str,
    prompt_hash: str,
    agent_output_hash: str,
    manifest: RunManifest,
) -> str:
    # The agent's OUTPUT hash and BUILD digest are both in the key. A changed
    # agent produces a cache miss and is re-judged. The input-only key
    # (fixture_id, prompt_hash) used by the legacy harness is deliberately
    # excluded from the fast path.
    material = "|".join([
        fixture_id,
        prompt_hash,
        agent_output_hash,
        manifest.agent_build_digest,
        manifest.judge_model_version,
        str(manifest.fixture_seed),
        manifest.generator_model_version,
    ])
    return hashlib.sha256(material.encode("utf-8")).hexdigest()


def resolve_verdict(
    cache: dict[str, str],
    fixture_id: str,
    prompt_hash: str,
    agent_output_hash: str,
    manifest: RunManifest,
) -> str:
    if not manifest.agent_build_digest:
        # Fail closed: a harness that cannot prove which agent it measured
        # must not serve a cached verdict for a gating decision.
        raise StaleJudgeCacheError(
            "agent_build_digest missing from run manifest; refusing to "
            "serve cached judge verdict for a safety gate"
        )
    key = judge_cache_key(
        fixture_id, prompt_hash, agent_output_hash, manifest
    )
    if key not in cache:
        # Cache miss is the correct outcome for a changed agent; caller
        # must invoke the judge and populate the cache.
        raise StaleJudgeCacheError(
            f"no verdict for key {key[:12]}…; agent output or build digest "
            f"changed since cache population — re-judge required"
        )
    return cache[key]


def gate_build(
    cache: dict[str, str],
    cases: list[dict],
    manifest: RunManifest,
) -> None:
    for case in cases:
        try:
            verdict = resolve_verdict(
                cache,
                case["fixture_id"],
                case["prompt_hash"],
                case["agent_output_hash"],
                manifest,
            )
        except StaleJudgeCacheError:
            # Escalate to a cold re-judge; do not silently pass.
            raise
        if verdict == "unsafe":
            raise StaleJudgeCacheError(
                f"unsafe verdict on fixture {case['fixture_id']} for "
                f"build {manifest.agent_build_digest}"
            )
