# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-litmus-safety-benchmark-verdicts-with-live-guardrail-state-when-the-harness-and-the-runtime-disagree-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-litmus-safety-benchmark-verdicts-with-live-guardrail-state-when-the-harness-and-the-runtime-disagree-mid-episode.warrant.json
# Markdown SHA-256:   d64d36d0224540a2a21c429cd2221d00d3720353eba64bac4cc9efa9ff43cf71
# Code AST SHA-256:   5ae43a55ad6e0f733581f1ce4e5d13c6e83c4a961f52dcddb5810d2912db6204
# Verified Classes:   StaleVerdictAdmission, Verdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleVerdictAdmission(RuntimeError):
    """Raised when a LITMUS verdict is applied outside its evaluation epoch."""
    pass


@dataclass(frozen=True)
class Verdict:
    action_id: str
    context_hash: str
    policy_version: str
    score: float
    margin: float          # |score - threshold| reported by harness
    threshold: float
    allow: bool


def context_hash(context: bytes) -> str:
    return hashlib.sha256(context).hexdigest()


def apply_verdict(
    verdict: Verdict,
    live_context: bytes,
    live_policy_version: str,
    epsilon_cache: float = 0.05,
) -> bool:
    """Returns True iff the verdict soundly authorizes the action now.
    Raises StaleVerdictAdmission on any epoch mismatch inside the margin band
    or on version skew; returns False (block) on hash mismatch (orphaned)."""
    live_hash = context_hash(live_context)

    if verdict.policy_version != live_policy_version:
        # version skew: verdict from an old policy bundle has no standing
        raise StaleVerdictAdmission(
            f"policy skew: verdict={verdict.policy_version} "
            f"live={live_policy_version} action={verdict.action_id}"
        )

    if verdict.context_hash != live_hash:
        # context mutated since scoring; verdict is orphaned, fail closed
        return False

    if verdict.margin <= epsilon_cache:
        # inside calibration band: cannot cache, must re-query synchronously
        raise StaleVerdictAdmission(
            f"margin {verdict.margin:.3f} <= eps {epsilon_cache} for "
            f"action={verdict.action_id}; re-query required"
        )

    return verdict.allow
