# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-safety-benchmark-pass-results-as-invalid-because-the-harness-replayed-a-stale-agent-snapshot-rather-th.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-safety-benchmark-pass-results-as-invalid-because-the-harness-replayed-a-stale-agent-snapshot-rather-th.warrant.json
# Markdown SHA-256:   876df29337a058bbdf5132e9f864d97c6c35896427069804ba19016e0d56ecd6
# Code AST SHA-256:   ca32d31d2186fe0ca965d55b2404ccc59f4c0793761f30204cef096b87000ef4
# Verified Classes:   StaleSnapshotError, BehavioralSurface
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleSnapshotError(RuntimeError):
    """Raised when a LITMUS pass is attached to a snapshot that is not the live policy."""
    pass


@dataclass(frozen=True)
class BehavioralSurface:
    rendered_prompt: str
    tool_manifest: dict          # full names + arg schemas, not category sets
    weights_digest: str
    decoding_config: dict


def snapshot_key(surface: BehavioralSurface) -> str:
    # Total projection: every field that can change safety behavior is hashed.
    h = hashlib.sha256()
    h.update(surface.rendered_prompt.encode())
    for name in sorted(surface.tool_manifest):
        h.update(name.encode())
        h.update(repr(surface.tool_manifest[name]).encode())
    h.update(surface.weights_digest.encode())
    h.update(repr(sorted(surface.decoding_config.items())).encode())
    return h.hexdigest()


def assert_pass_is_valid(
    tested: BehavioralSurface,
    live_at_merge: BehavioralSurface,
    snapshot_age_seconds: int,
    max_staleness_seconds: int = 86_400,
) -> None:
    if snapshot_age_seconds > max_staleness_seconds:
        raise StaleSnapshotError(
            f"snapshot age {snapshot_age_seconds}s exceeds max {max_staleness_seconds}s; "
            f"LITMUS pass does not gate this merge"
        )
    if snapshot_key(tested) != snapshot_key(live_at_merge):
        raise StaleSnapshotError(
            "snapshot key mismatch: harness tested a behavioral surface that differs "
            "from the live policy at merge time; pass result is referentially invalid"
        )
