# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-advertised-defaultoutputmodes-as-a-hard-capability-ceiling-rather-than-a-negotia.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-s-advertised-defaultoutputmodes-as-a-hard-capability-ceiling-rather-than-a-negotia.warrant.json
# Markdown SHA-256:   285864e1b622e60881185593b290d421b6f58661730a9d53d4b352f9dc68b32b
# Code AST SHA-256:   c3c3eb0f9f068e46ddeb171e714fb445d5f496a428250348e8ed31647f8f513a
# Verified Classes:   CapabilityMismatch, StaleAgentCard, Skill, AgentCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CapabilityMismatch(RuntimeError):
    """Raised when a requested artifact modality is not backed by the
    card-level output set intersected with the targeted skill's output set."""
    pass


class StaleAgentCard(RuntimeError):
    """Raised when the cached card cannot be trusted as an authoritative
    capability ceiling (version drift or protocol mismatch)."""
    pass


@dataclass
class Skill:
    id: str
    output_modes: list[str]


@dataclass
class AgentCard:
    version: str
    protocol_version: str
    default_output_modes: list[str]
    skills: dict[str, Skill] = field(default_factory=dict)


def resolve_output_ceiling(
    card: AgentCard,
    target_skill_id: Optional[str],
    *,
    cached_version: Optional[str],
    client_protocol: str = "1.0",
) -> set[str]:
    # Guard 1: the card must be authoritative before its modes bound anything.
    if cached_version is not None and cached_version != card.version:
        raise StaleAgentCard(
            f"cached card version {cached_version!r} != live {card.version!r}; "
            "re-fetch before treating output modes as a ceiling"
        )
    if card.protocol_version != client_protocol:
        raise StaleAgentCard(
            f"card protocol {card.protocol_version!r} != client {client_protocol!r}"
        )

    card_level = set(card.default_output_modes)

    # Guard 2: without an explicit skill, the ceiling is the union over all
    # routable skills -- i.e. not a bound. Refuse to pretend otherwise.
    if target_skill_id is None:
        raise CapabilityMismatch(
            "no target_skill_id: card-level modes are a union, not a ceiling; "
            "disambiguate the skill before submitting"
        )

    skill = card.skills.get(target_skill_id)
    if skill is None:
        raise CapabilityMismatch(
            f"skill {target_skill_id!r} not present on card {card.version!r}"
        )

    return card_level & set(skill.output_modes)


def preflight_submit(
    card: AgentCard,
    target_skill_id: Optional[str],
    desired_mime: str,
    *,
    cached_version: Optional[str],
) -> str:
    allowed = resolve_output_ceiling(
        card, target_skill_id, cached_version=cached_version
    )
    if desired_mime not in allowed:
        raise CapabilityMismatch(
            f"requested {desired_mime!r} not in effective ceiling "
            f"{sorted(allowed)} for skill {target_skill_id!r}; "
            "refuse locally instead of submitting a doomed task"
        )
    return desired_mime


# Trace replay: the summarize+pdf request that produced a retry storm.
card = AgentCard(
    version="r7",
    protocol_version="1.0",
    default_output_modes=["text/plain", "application/json", "application/pdf"],
    skills={
        "summarize": Skill("summarize", ["text/plain", "application/json"]),
        "render-report": Skill("render-report", ["application/pdf"]),
    },
)

try:
    preflight_submit(card, "summarize", "application/pdf", cached_version="r7")
except CapabilityMismatch as exc:
    # Correct behavior: zero remote calls, no retry storm.
    print("refused:", exc)
