# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-agent-card-as-non-authoritative-after-discovery-cache-warm-through.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-agent-card-as-non-authoritative-after-discovery-cache-warm-through.warrant.json
# Markdown SHA-256:   531beae57b2a6cee331cbd8ea2a4b0f21aabb7e98b32e03ec0877566c52cb528
# Code AST SHA-256:   899928341e0774033f9716990320c5cf9ecff3cceb297514cf9158f13d58f201
# Verified Classes:   StaleAuthorityError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleAuthorityError(RuntimeError):
    """Raised when a cached Agent Card is used to authorize a dispatch
    whose consequence class exceeds the card's freshness horizon."""
    pass


def authorize_dispatch(cached_card: dict, dispatch: dict, now: float) -> str:
    # Identity gate: signature already verified at cache time; re-verify bytes here.
    if not cached_card.get("signature_verified"):
        raise StaleAuthorityError("card signature not verified; refuse dispatch")

    # Freshness gate: separate from signature. Fail closed if absent.
    expires_at = cached_card.get("expiresAt")
    if expires_at is None:
        raise StaleAuthorityError(
            "card has no expiresAt; authority is unbounded and non-cacheable"
        )
    if now >= expires_at:
        raise StaleAuthorityError(
            f"card expired at {expires_at} (now={now}); re-fetch before dispatch"
        )

    # Consequence-escalation gate: probe-cached card cannot authorize
    # a high-consequence dispatch without a task-bound warrant nonce.
    if dispatch["consequence"] == "high":
        nonce = dispatch.get("warrant_nonce")
        if nonce is None or nonce != cached_card.get("issued_nonce"):
            raise StaleAuthorityError(
                "high-consequence dispatch lacks task-bound warrant nonce; "
                "cached scope is non-authoritative"
            )

    # Endpoint must be re-resolved at dispatch, never trusted from cache.
    if dispatch["endpoint"] != cached_card.get("endpoint"):
        raise StaleAuthorityError(
            "endpoint drift between cache and dispatch; re-resolve peer identity"
        )

    return dispatch["warrant_nonce"]
