# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a2a-v1-0-agent-card-discovery-silently-succeed-against-a-stale-non-authoritative-card-and-then-fail-only-at-the-third-delegati.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a2a-v1-0-agent-card-discovery-silently-succeed-against-a-stale-non-authoritative-card-and-then-fail-only-at-the-third-delegati.warrant.json
# Markdown SHA-256:   10b132491ca393948588628be3574a6f1f0c74d1d61a42346a253c76d0c8acd8
# Code AST SHA-256:   31f7ca1c0e1501318d60216e8b380108127fdf88821c02b79ba1d1a0f667b8bb
# Verified Classes:   StaleAgentCardError, ResolvedCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import FrozenSet


class StaleAgentCardError(RuntimeError):
    """Raised when a resolved Agent Card's advertised lifecycle no longer
    matches the executor's actual TaskState behavior (card authority skew)."""


@dataclass(frozen=True)
class ResolvedCard:
    agent_id: str
    advertised_states: FrozenSet[str]
    cache_ttl_seconds: int
    version: str


def verify_card_authority(
    card: ResolvedCard,
    observed_states: FrozenSet[str],
    required_transition: str,
    chain_length: int,
    max_cache_ttl_seconds: int = 300,
) -> None:
    """Guard invoked before delegating a stateful task across hops.

    Raises StaleAgentCardError if the card cannot be trusted to honor the
    required lifecycle transition. Callers must probe the executor first and
    pass the states it actually emitted as `observed_states`.
    """
    if required_transition not in card.advertised_states:
        raise StaleAgentCardError(
            f"{card.agent_id}: card does not advertise required state "
            f"{required_transition!r}; refusing delegation"
        )

    # The executor emitted a state the card never claimed: the card is not
    # merely stale, it describes a different state machine entirely.
    unadvertised = observed_states - card.advertised_states
    if unadvertised:
        raise StaleAgentCardError(
            f"{card.agent_id}: executor emitted unadvertised states "
            f"{sorted(unadvertised)}; card authority violated"
        )

    # Multi-hop chains amplify cache skew: a stale card at hop N poisons
    # every hop above it, so demand a tight TTL before trusting it.
    if chain_length > 1 and card.cache_ttl_seconds > max_cache_ttl_seconds:
        raise StaleAgentCardError(
            f"{card.agent_id}: cache TTL {card.cache_ttl_seconds}s exceeds "
            f"{max_cache_ttl_seconds}s on a {chain_length}-hop chain; "
            "re-resolve or pin digest before delegating"
        )

    if required_transition not in observed_states:
        raise StaleAgentCardError(
            f"{card.agent_id}: probe did not observe {required_transition!r} "
            "within the probe window; executor may have dropped the transition"
        )
