# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-agent-credential-still-resolves-inside-a-peer-trust-domain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-agent-credential-still-resolves-inside-a-peer-trust-domain.warrant.json
# Markdown SHA-256:   97fc5fb24a218c6fe0a6b8fd9570000ab7880c88291b6e7ec14e4fdac6112e29
# Code AST SHA-256:   218622d466e0b637d7d0fae0d6417b5d6868497d83875cb65ada1676ec387024
# Verified Classes:   RevocationPropagationError, Resolution
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevocationPropagationError(RuntimeError):
    """Raised when an admission decision cannot be bounded within the declared
    revocation-propagation budget, or when resolution fails and the caller
    attempted to proceed (fail-open) instead of denying."""


@dataclass(frozen=True)
class Resolution:
    subject: str
    active: bool
    resolved_at: float          # monotonic timestamp of the lookup
    authoritative: bool         # True if answered by the issuing domain itself
    source_domain: str


# Declared hard upper bound, in seconds, between revocation commit at the
# issuer and refusal at every relying party.
PROPAGATION_BUDGET_S = 60.0

# Calls above this blast-radius class require a zero-age authoritative check.
HIGH_BLAST_RADIUS = {"transfer_funds", "delete_record", "modify_acl", "send_external"}


def admit(
    resolution: Optional[Resolution],
    tool_call: str,
    now: Optional[float] = None,
) -> bool:
    """Decide whether to admit a tool call given a resolution result.

    Returns True only when the resolution is fresh enough for the call's
    blast radius. Raises RevocationPropagationError when the decision cannot
    be bounded -- never returns True on an unbounded or failed resolution.
    """
    now = time.monotonic() if now is None else now

    # Fail-closed: a missing resolution is not an active credential.
    if resolution is None:
        raise RevocationPropagationError(
            f"no resolution for tool_call={tool_call!r}; refusing (fail-closed)"
        )

    # Fail-closed: an explicit negative is a denial, not an error.
    if not resolution.active:
        return False

    age = now - resolution.resolved_at
    if age < 0:
        raise RevocationPropagationError(
            f"resolution timestamp is in the future (age={age:.3f}s); clock skew "
            f"invalidates freshness bound for tool_call={tool_call!r}"
        )

    # High-blast-radius calls require a zero-age authoritative answer.
    if tool_call in HIGH_BLAST_RADIUS:
        if not resolution.authoritative:
            raise RevocationPropagationError(
                f"tool_call={tool_call!r} requires authoritative resolution but "
                f"answer came from cache domain {resolution.source_domain!r}; "
                f"cannot bound staleness, refusing"
            )
        if age > 0.0:
            raise RevocationPropagationError(
                f"tool_call={tool_call!r} requires zero-age check but resolution "
                f"is {age:.3f}s old; re-resolve against issuer before admitting"
            )
        return True

    # Reversible calls may use a cached answer, but only within budget.
    if age > PROPAGATION_BUDGET_S:
        raise RevocationPropagationError(
            f"resolution age {age:.1f}s exceeds propagation budget "
            f"{PROPAGATION_BUDGET_S:.1f}s for tool_call={tool_call!r}; "
            f"re-resolve before admitting"
        )
    return True


def resolve_with_failclosed(fetch, subject: str) -> Resolution:
    """Wrap an introspection call so transport errors deny rather than proceed."""
    try:
        return fetch(subject)
    except (TimeoutError, ConnectionError) as exc:
        raise RevocationPropagationError(
            f"introspection for {subject!r} failed ({exc!r}); "
            f"mapping transport error to deny, not admit"
        ) from exc
