# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-harness-verdicts-as-stale-between-checkpoint-resume-and-re-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-harness-verdicts-as-stale-between-checkpoint-resume-and-re-attestation.warrant.json
# Markdown SHA-256:   bf42bcb99971bceb7e04cf452c8c48e01ce3b6fec5e6b6dd18e2fe16cfc964f4
# Code AST SHA-256:   2af600ed3c82ef165cb60dc9625d119e8ff376c6d27fadfb1455978d55a7e0b7
# Verified Classes:   StaleVerdictError, CapabilityWidenedError, ConfigTuple, LitmusVerdict, ResumeContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class StaleVerdictError(RuntimeError):
    """Raised when a resumed instance attempts to rely on a LITMUS verdict
    whose configuration tuple no longer matches the live instance."""
    pass


class CapabilityWidenedError(RuntimeError):
    """Raised when a tool-manifest delta widens a capability without
    delta-scoped re-attestation."""
    pass


@dataclass(frozen=True)
class ConfigTuple:
    model_snapshot_id: str
    system_prompt_hash: str
    tool_manifest_hash: str
    policy_version: str
    harness_suite_version: str

    def hash(self) -> str:
        blob = json.dumps(self.__dict__, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass(frozen=True)
class LitmusVerdict:
    verdict: str            # "PASS" | "FAIL"
    attested_tuple_hash: str
    suite_version: str


@dataclass
class ResumeContext:
    live_tuple: ConfigTuple
    handed_verdict: LitmusVerdict
    config_delta: Optional[dict] = field(default=None)  # field -> (old, new)
    capability_widened: bool = False


def assert_verdict_fresh(ctx: ResumeContext) -> None:
    """Enforce the invariant: verdict validity is a function of the
    configuration tuple, not the task lineage. Must run as the first
    post-resume action, before any capability-bearing tool call."""
    live_hash = ctx.live_tuple.hash()

    if ctx.handed_verdict.attested_tuple_hash != live_hash:
        raise StaleVerdictError(
            "Resumed instance holds a LITMUS verdict attested against "
            f"tuple {ctx.handed_verdict.attested_tuple_hash[:12]}, but live "
            f"tuple is {live_hash[:12]}. Delta fields: "
            f"{sorted((ctx.config_delta or {}).keys())}. "
            "Refusing capability-bearing calls until delta-scoped "
            "re-attestation completes."
        )

    if ctx.handed_verdict.suite_version != ctx.live_tuple.harness_suite_version:
        raise StaleVerdictError(
            "Verdict produced by harness suite "
            f"{ctx.handed_verdict.suite_version}, live suite is "
            f"{ctx.live_tuple.harness_suite_version}. Coverage gaps may exist."
        )

    if ctx.capability_widened:
        raise CapabilityWidenedError(
            "Tool-manifest delta widens a capability (new params, mounts, "
            "or relaxed constraints) without delta-scoped re-attestation. "
            "Re-run tool-abuse and capability-escape suites for the delta."
        )


def resume_gate(ctx: ResumeContext) -> str:
    """Returns 'PROCEED' only if the verdict is fresh; otherwise raises."""
    assert_verdict_fresh(ctx)
    return "PROCEED"
