# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-halt-on-a-revoked-but-cached-aaif-delegated-credential-chain-before-executing-a-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-halt-on-a-revoked-but-cached-aaif-delegated-credential-chain-before-executing-a-tool-call.warrant.json
# Markdown SHA-256:   d3cea485cdebd38378940f451b3abae3aa474fff551f7cb2a94619a693b138af
# Code AST SHA-256:   0244a7920f65f0f30e07d8e04834f82d0b10a1379c016abc3a3334da6bbb1658
# Verified Classes:   StaleLivenessAuthorizationError, LivenessToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleLivenessAuthorizationError(RuntimeError):
    """Raised when a delegated chain passes integrity but its liveness
    assertion is absent, expired, unbound, or covers an incomplete link set."""


@dataclass(frozen=True)
class LivenessToken:
    chain_hash: str
    issued_at: float
    covers: frozenset  # set of link IDs asserted live
    revoked: frozenset  # link IDs known revoked at issued_at


def authorize_tool_call(
    chain,
    liveness: LivenessToken | None,
    now: float,
    horizon_s: float = 60.0,
) -> None:
    """Gate a tool call on chain integrity AND fresh, hash-bound liveness.

    `chain` exposes .hash, .link_ids, and .integrity_ok(). The liveness token
    must be bound to this exact chain hash, younger than horizon_s, cover every
    link, and assert none revoked. Any violation fails closed.
    """
    h = chain.hash
    if not chain.integrity_ok():
        raise StaleLivenessAuthorizationError(
            f"chain {h[:12]} failed integrity; refusing tool call"
        )

    if liveness is None:
        raise StaleLivenessAuthorizationError(
            f"chain {h[:12]} has no liveness assertion; fail closed"
        )
    if liveness.chain_hash != h:
        raise StaleLivenessAuthorizationError(
            f"liveness token bound to {liveness.chain_hash[:12]}, "
            f"not chain {h[:12]}"
        )
    if now - liveness.issued_at > horizon_s:
        raise StaleLivenessAuthorizationError(
            f"liveness for {h[:12]} is {now - liveness.issued_at:.1f}s old, "
            f"horizon {horizon_s}s"
        )
    if liveness.covers != frozenset(chain.link_ids):
        missing = frozenset(chain.link_ids) - liveness.covers
        raise StaleLivenessAuthorizationError(
            f"liveness for {h[:12]} omits links {sorted(missing)}; "
            f"intermediate revocation would be invisible"
        )
    hit = liveness.revoked & frozenset(chain.link_ids)
    if hit:
        raise StaleLivenessAuthorizationError(
            f"chain {h[:12]} has revoked link(s) {sorted(hit)}; halt"
        )
    # Integrity + fresh, complete, hash-bound liveness: authorized.
