# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-of-a-litmus-safety-harness-be-treated-as-a-stateful-authority-rather-than-a-stateless-test-oracle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-of-a-litmus-safety-harness-be-treated-as-a-stateful-authority-rather-than-a-stateless-test-oracle.warrant.json
# Markdown SHA-256:   1726201585722cc3b1bda420bf29d77c6ad4fea6a7eef1cccbe30f13c3dbd99c
# Code AST SHA-256:   3a1b65734c3d2431f03c8c6a50c4e3cd9646c433afd94a12fd67e00fe3ecfe6f
# Verified Classes:   HarnessStateBoundaryError, Verdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class HarnessStateBoundaryError(RuntimeError):
    """Raised when a LITMUS verdict is used outside the state regime that produced it."""
    pass


@dataclass(frozen=True)
class Verdict:
    session_token: str
    probe_order_hash: str
    probe_id: int
    outcome: str  # "PASS" | "FAIL" | "REFUSE"


def probe_order_hash(probe_ids: list[int]) -> str:
    h = hashlib.sha256()
    for pid in probe_ids:
        h.update(pid.to_bytes(8, "big"))
    return h.hexdigest()


def assert_verdict_valid_for_session(
    verdict: Verdict,
    live_session_token: str,
    live_probe_ids: list[int],
) -> None:
    """
    Enforce the stateful-authority invariant: a verdict is valid only for the
    exact (harness_state, agent_state) pair that produced it. Re-instantiating
    the harness mid-session invalidates prior verdicts; treating them as
    stateless-oracle results is a boundary violation.
    """
    if verdict.session_token != live_session_token:
        raise HarnessStateBoundaryError(
            f"verdict for probe {verdict.probe_id} was produced under session "
            f"{verdict.session_token!r}, but live session is {live_session_token!r}; "
            f"stateful-authority verdict cannot be upcast to stateless-oracle result"
        )
    live_hash = probe_order_hash(live_probe_ids)
    if verdict.probe_order_hash != live_hash:
        raise HarnessStateBoundaryError(
            f"verdict for probe {verdict.probe_id} has probe-order hash "
            f"{verdict.probe_order_hash!r}, expected {live_hash!r}; "
            f"severity scheduler state diverged from agent state"
        )


def gate_deployment(
    verdicts: list[Verdict],
    live_session_token: str,
    live_probe_ids: list[int],
) -> bool:
    for v in verdicts:
        assert_verdict_valid_for_session(v, live_session_token, live_probe_ids)
    return not any(v.outcome == "FAIL" for v in verdicts)
