# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-bind-aaif-credentials-after-a-context-compaction-event-and-what-silently-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-bind-aaif-credentials-after-a-context-compaction-event-and-what-silently-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   a1eb0bea2e72e828f1320fd5e1af69b09650ee360e2ae79fb2386b0b0dcc0c6d
# Code AST SHA-256:   74de70873df25c7b1d27aa8fc93b8ebd37d9a27129f419c50417edf6d869e04f
# Verified Classes:   StaleWarrantBindingError, WarrantReplayError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleWarrantBindingError(RuntimeError):
    """Raised when a resumed warrant's context_digest no longer matches the live context."""
    pass


class WarrantReplayError(RuntimeError):
    """Raised when a warrant nonce is presented more than once."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject_instance: str
    scope: frozenset
    nonce: str
    expiry: float
    context_digest: str


def compute_context_digest(system_prompt: str, tool_schema_set: frozenset, intent_chain_head: str) -> str:
    h = hashlib.sha256()
    h.update(system_prompt.encode())
    for schema in sorted(tool_schema_set):
        h.update(schema.encode())
    h.update(intent_chain_head.encode())
    return h.hexdigest()


def authorize_on_resume(
    warrant: Warrant,
    live_system_prompt: str,
    live_tool_schema_set: frozenset,
    live_intent_chain_head: str,
    now: float,
    replay_cache: set,
) -> None:
    if now >= warrant.expiry:
        raise StaleWarrantBindingError(f"warrant {warrant.nonce} expired at {warrant.expiry}")

    live_digest = compute_context_digest(live_system_prompt, live_tool_schema_set, live_intent_chain_head)
    if live_digest != warrant.context_digest:
        # Signature may still verify; binding does not. Fail closed and force re-mint.
        raise StaleWarrantBindingError(
            f"context_digest mismatch on resume: warrant={warrant.context_digest[:12]} "
            f"live={live_digest[:12]} — schema or intent chain changed during compaction; re-bind required"
        )

    if warrant.nonce in replay_cache:
        raise WarrantReplayError(f"nonce {warrant.nonce} already consumed; restore storm suspected")

    replay_cache.add(warrant.nonce)
