# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-a2a-agent-card-rather-than-negotiate-against-it-the-signaturejws-vs-capabilities-skew-boundary-in-cross-org.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-a2a-agent-card-rather-than-negotiate-against-it-the-signaturejws-vs-capabilities-skew-boundary-in-cross-org.warrant.json
# Markdown SHA-256:   ffd774603815e17bcfaacc79498f6edd3c91ef73004f0367d10fbdb879581b8a
# Code AST SHA-256:   e60766970719f41584b60f27c5ca5dd7bfbbe117e700f8edcdde0bf483bb8f8e
# Verified Classes:   CardNegotiationError, SignedCard, CorroborationCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CardNegotiationError(RuntimeError):
    """Raised when a discovered A2A card must be rejected before message/send."""
    pass


@dataclass
class SignedCard:
    agent_url: str
    revision: int
    signed_expires: Optional[float]      # epoch seconds, inside signed envelope
    capabilities: dict                    # e.g. {"streaming": True, ...}
    jws_verified: bool


@dataclass
class CorroborationCache:
    # key: (agent_url, revision, capability) -> epoch seconds last observed working
    observed: dict = field(default_factory=dict)

    def record(self, url: str, rev: int, cap: str, now: float) -> None:
        self.observed[(url, rev, cap)] = now

    def fresh(self, url: str, rev: int, cap: str, now: float, max_age: float) -> bool:
        ts = self.observed.get((url, rev, cap))
        return ts is not None and (now - ts) <= max_age


REQUIRED_CAPS = ("streaming", "stateTransitionHistory")
PROBE_MAX_AGE = 300.0
CLOCK_SKEW = 30.0


def admit_card(
    card: SignedCard,
    cache: CorroborationCache,
    now: Optional[float] = None,
) -> None:
    """Gate entry to message/send. Raises CardNegotiationError on any violation."""
    now = time.time() if now is None else now

    if not card.jws_verified:
        raise CardNegotiationError(
            f"card at {card.agent_url} rev={card.revision} JWS unverified; "
            "refusing to negotiate against unanchored capability claims"
        )

    if card.signed_expires is None:
        # No signed expiry => unbounded trust grant => force per-call probe,
        # which we cannot satisfy here, so fail closed.
        raise CardNegotiationError(
            f"card at {card.agent_url} rev={card.revision} has no signed expiry; "
            "treating as max_age=0 is unsafe without a live probe, rejecting"
        )

    if now > card.signed_expires + CLOCK_SKEW:
        raise CardNegotiationError(
            f"card at {card.agent_url} rev={card.revision} expired at "
            f"{card.signed_expires:.0f}, now {now:.0f}"
        )

    for cap in REQUIRED_CAPS:
        if not card.capabilities.get(cap, False):
            raise CardNegotiationError(
                f"card at {card.agent_url} rev={card.revision} does not advertise "
                f"required capability {cap!r}"
            )
        if not cache.fresh(card.agent_url, card.revision, cap, now, PROBE_MAX_AGE):
            raise CardNegotiationError(
                f"capability {cap!r} on {card.agent_url} rev={card.revision} "
                "advertised but not corroborated within probe window; "
                "signature proves assertion, not liveness"
            )
    # admitted: caller may now issue message/send against this exact revision


def submit_task(card: SignedCard, cache: CorroborationCache, payload: dict) -> str:
    admit_card(card, cache)  # fail-closed gate before lifecycle entry
    # ... actual message/send omitted ...
    return "task-id"
