# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-litmus-safety-score-when-the-red-team-harness-and-the-agent-under-test-disagree-about-which-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-litmus-safety-score-when-the-red-team-harness-and-the-agent-under-test-disagree-about-which-policy.warrant.json
# Markdown SHA-256:   b61bf659f749e9b3f679d53571e062eff551fdb5417b37a4f68b7355101d7abe
# Code AST SHA-256:   22c5eaa12e86b831dcc4452aa3eb2c7ffc2cbb00fcc4c01bc78e45fc0e1da407
# Verified Classes:   PolicyRevisionMismatch, Verdict, Attestation, Corpus
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class PolicyRevisionMismatch(RuntimeError):
    """Raised when the agent's attested policy revision diverges from the
    LITMUS corpus calibration revision at scoring time."""


class Verdict(Enum):
    PASS = "pass"
    FAIL = "fail"
    INDETERMINATE = "indeterminate"


@dataclass(frozen=True)
class Attestation:
    policy_bytes_hash: str
    resolution_path: str  # "default" | "env" | "remote" | "fallback"


@dataclass(frozen=True)
class Corpus:
    calibration_hash: str


def attest_loaded_policy(policy_bytes: bytes, resolution_path: str) -> Attestation:
    return Attestation(
        policy_bytes_hash=hashlib.sha256(policy_bytes).hexdigest(),
        resolution_path=resolution_path,
    )


def resolve_and_attest(loader) -> Attestation:
    # loader returns (bytes, resolution_path); may fall back to stale bundle.
    policy_bytes, path = loader()
    return attest_loaded_policy(policy_bytes, path)


def gate_score(
    attestation: Attestation,
    corpus: Corpus,
    *,
    deterministic_rerun: Attestation | None,
) -> Verdict:
    if attestation.policy_bytes_hash == corpus.calibration_hash:
        return Verdict.PASS  # score is valid; caller applies probe verdicts

    # Mismatch detected. Distinguish transient from deterministic.
    if deterministic_rerun is None:
        raise PolicyRevisionMismatch(
            "policy revision mismatch with no isolated re-resolution; "
            "cannot classify transient vs deterministic"
        )

    if deterministic_rerun.policy_bytes_hash == corpus.calibration_hash:
        # Re-resolution under healthy config matched corpus -> first was transient.
        return Verdict.INDETERMINATE

    # Still diverges under healthy config -> baked-in / misconfigured plumbing.
    raise PolicyRevisionMismatch(
        f"deterministic policy divergence: resolved={attestation.policy_bytes_hash[:12]} "
        f"path={attestation.resolution_path} corpus={corpus.calibration_hash[:12]}"
    )
