# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-verifiable-agent-credential-as-invalid-at-the-moment-its-own-trust-anchor-set-rotates-rather-than-at-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-verifiable-agent-credential-as-invalid-at-the-moment-its-own-trust-anchor-set-rotates-rather-than-at-th.warrant.json
# Markdown SHA-256:   4637859f66c065e684736c3ecac816e33626b3991891ce4326e10f982ba20c21
# Code AST SHA-256:   ca1bffded977af57488ef20e2bd51414956e2d6e1ba8f1f859c0cd84667e9e59
# Verified Classes:   StaleAnchorSetError, AnchorResolutionUnavailable, AnchorSet, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Callable, Mapping


class StaleAnchorSetError(RuntimeError):
    """Raised when a credential is evaluated against an anchor set whose
    authority-published timestamp exceeds the action's staleness bound."""


class AnchorResolutionUnavailable(RuntimeError):
    """Raised when synchronous anchor re-resolution is required for a
    privileged action but the directory cannot be reached within deadline."""


@dataclass(frozen=True)
class AnchorSet:
    anchors: Mapping[str, bytes]
    authority_published_at: float  # epoch seconds, signed by directory


@dataclass(frozen=True)
class Credential:
    chain: tuple[str, ...]  # anchor key id is chain[-1]
    not_before: float
    not_after: float


# Actions whose consequences are irreversible or privilege-escalating.
PRIVILEGED_ACTIONS = frozenset({"funds_transfer", "credential_mint", "root_tool_call"})
DEFAULT_MAX_STALENESS = 300.0  # seconds, for non-privileged actions


def verify(
    cred: Credential,
    cached: AnchorSet,
    action_class: str,
    now: float,
    resolve_fresh: Callable[[], AnchorSet],
    resolve_deadline: float = 2.0,
) -> bool:
    if not (cred.not_before <= now <= cred.not_after):
        return False

    if action_class in PRIVILEGED_ACTIONS or action_class not in _KNOWN_ACTIONS:
        # Must not trust the cache for privileged or unknown actions.
        try:
            fresh = resolve_fresh()
        except TimeoutError as exc:
            raise AnchorResolutionUnavailable(
                f"synchronous anchor resolution failed for privileged "
                f"action {action_class!r}; refusing to fall back to cache"
            ) from exc
        if now - fresh.authority_published_at > resolve_deadline:
            raise StaleAnchorSetError(
                f"freshly resolved anchor set is itself stale by "
                f"{now - fresh.authority_published_at:.1f}s"
            )
        return cred.chain[-1] in fresh.anchors

    staleness = now - cached.authority_published_at
    if staleness > DEFAULT_MAX_STALENESS:
        raise StaleAnchorSetError(
            f"cached anchor set stale by {staleness:.1f}s "
            f"(bound {DEFAULT_MAX_STALENESS:.0f}s) for action {action_class!r}"
        )
    return cred.chain[-1] in cached.anchors


_KNOWN_ACTIONS = frozenset({"read_only", "status_probe", "telemetry_emit"})
