# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-agent-card-as-a-capability-superset-during-a2a-v1-0-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-agent-card-as-a-capability-superset-during-a2a-v1-0-negotiation.warrant.json
# Markdown SHA-256:   426d8b4f478fe94de5ee604a878bacd5aeca5091d23a9d0d2f0b2976b6d7996c
# Code AST SHA-256:   dd34d6a5ab5a73b986ff5b1a74ba8257236d0c3277a66984d47d343fdb503feb
# Verified Classes:   StaleCardSupersetError, AgentCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCardSupersetError(RuntimeError):
    """Raised when dispatch would rely on a capability present only in a stale card."""


@dataclass
class AgentCard:
    version: str
    revision: int
    skills: frozenset[str]
    capabilities: frozenset[str]
    max_sources: int
    verified_within_deadline: bool


def negotiate_dispatch(
    cached: AgentCard,
    live: Optional[AgentCard],
    requested_skill: str,
    requested_sources: int,
    opens_stream: bool,
) -> AgentCard:
    if cached.verified_within_deadline and live is None:
        return cached

    if live is None:
        # Unverified, no live observation: only idempotent, non-streaming, minimal payload.
        if opens_stream:
            raise StaleCardSupersetError(
                "refusing to open streaming transport on unverified card with no live observation"
            )
        if requested_skill not in cached.skills:
            raise StaleCardSupersetError(
                f"skill {requested_skill!r} not present in unverified card"
            )
        if requested_sources > min(cached.max_sources, 16):
            raise StaleCardSupersetError(
                "payload exceeds conservative clamp for unverified card"
            )
        return cached

    # Stale-but-observed: intersect, never union.
    surviving_skills = cached.skills & live.skills
    surviving_caps = cached.capabilities & live.capabilities

    if requested_skill not in surviving_skills:
        raise StaleCardSupersetError(
            f"skill {requested_skill!r} exists only in stale card; live instance dropped it"
        )
    if opens_stream and "streaming" not in surviving_caps:
        raise StaleCardSupersetError(
            "streaming advertised only by stale card; live instance does not support it"
        )
    if requested_sources > live.max_sources:
        raise StaleCardSupersetError(
            f"requested {requested_sources} sources exceeds live maxItems {live.max_sources}"
        )

    return AgentCard(
        version=live.version,
        revision=live.revision,
        skills=surviving_skills,
        capabilities=surviving_caps,
        max_sources=live.max_sources,
        verified_within_deadline=False,
    )
