# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-cross-org-capability-token-when-the-peer-agent-s-attestation-chain-still-verifies-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-cross-org-capability-token-when-the-peer-agent-s-attestation-chain-still-verifies-locally.warrant.json
# Markdown SHA-256:   9034ea090ae1e3f69a1496cf17c6c627f8bb585b4c5833bad87892ea51fdc038
# Code AST SHA-256:   68e127241b0ef1adfe7d9d0847f05fddecfb94993a263c60fc541944606ea2b4
# Verified Classes:   StaleAuthorityError, CachedAuthority
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable, Optional


class StaleAuthorityError(RuntimeError):
    """Raised when cached SCT authority cannot be proven fresher than the
    issuer's revocation propagation bound. Fail-closed: do not act."""
    pass


@dataclass
class CachedAuthority:
    token_id: str
    claim_set: dict
    minted_at: float
    expires_at: float
    max_staleness: float          # verifier-chosen freshness bound, seconds
    propagation_bound: float      # issuer-published revoke->visible bound
    last_revocation_check: float = 0.0
    last_check_result: Optional[bool] = None  # True=revoked, False=not, None=unknown

    def effective_freshness_bound(self) -> float:
        # The tighter of the two bounds governs; we may not outlive either.
        return min(self.max_staleness, self.propagation_bound)


def authorize_tool_call(
    auth: CachedAuthority,
    now: float,
    revocation_probe: Callable[[str], Optional[bool]],
) -> None:
    """Enforce the freshness invariant before a side-effecting call.

    revocation_probe returns True (revoked), False (not revoked),
    or None (endpoint unreachable). None is treated as fail-closed.
    """
    if now >= auth.expires_at:
        raise StaleAuthorityError(
            f"token {auth.token_id} expired at {auth.expires_at}, now {now}"
        )

    bound = auth.effective_freshness_bound()
    age = now - auth.last_revocation_check

    if age >= bound:
        # Cache is stale relative to the propagation window: must re-check.
        result = revocation_probe(auth.token_id)
        if result is None:
            # Unreachable revocation endpoint: cannot establish liveness.
            raise StaleAuthorityError(
                f"token {auth.token_id}: revocation endpoint unreachable; "
                f"cached authority age {age:.1f}s exceeds bound {bound:.1f}s; "
                f"refusing to act (fail-closed)"
            )
        auth.last_revocation_check = now
        auth.last_check_result = result

    if auth.last_check_result is True:
        raise StaleAuthorityError(
            f"token {auth.token_id} revoked by issuer; scope released"
        )

    # Invariant holds: age < bound and last check said not-revoked.
    if now - auth.last_revocation_check >= bound:
        # Defensive: should be unreachable given the branch above.
        raise StaleAuthorityError(
            f"token {auth.token_id}: freshness invariant violated "
            f"(age {now - auth.last_revocation_check:.1f}s >= bound {bound:.1f}s)"
        )
