# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cached-a2a-agent-card-as-invalid-when-the-remote-peer-advertises-a-capability-superset-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cached-a2a-agent-card-as-invalid-when-the-remote-peer-advertises-a-capability-superset-mid-session.warrant.json
# Markdown SHA-256:   dac3aefbc281c66ae4652454930033349a33f637bf3f55d73858cbb77086f264
# Code AST SHA-256:   2eb2cf02aeef255721fee18d6f8f5dc68964c634778909eb667e952260207470
# Verified Classes:   CapabilitySupersetDrift, CardSnapshot, Negotiation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CapabilitySupersetDrift(RuntimeError):
    """Raised when a peer's AgentCard has grown relative to the card a
    session negotiated against. A superset is a breaking change: the
    caller's committed capability subset no longer describes the peer."""


@dataclass(frozen=True)
class CardSnapshot:
    version: str
    skills: frozenset
    streaming: bool
    push_notifications: bool
    input_modes: frozenset
    output_modes: frozenset
    security_schemes: frozenset


@dataclass
class Negotiation:
    card: CardSnapshot
    token: str
    mode: str = "sync"


def revalidate_or_raise(
    negotiated: Negotiation,
    current: CardSnapshot,
    in_flight_task_id: Optional[str] = None,
) -> Negotiation:
    cached = negotiated.card

    if current.version == cached.version and current == cached:
        return negotiated

    grew = (
        not cached.skills.issubset(current.skills)
        or (current.streaming and not cached.streaming)
        or (current.push_notifications and not cached.push_notifications)
        or not cached.input_modes.issubset(current.input_modes)
        or not cached.output_modes.issubset(current.output_modes)
        or not cached.security_schemes.issubset(current.security_schemes)
    )

    if grew:
        raise CapabilitySupersetDrift(
            f"peer card advanced from version {cached.version!r} to "
            f"{current.version!r} with a capability superset; "
            f"negotiation token {negotiated.token!r} is stale. "
            f"in_flight_task={in_flight_task_id!r}. "
            f"Re-negotiate before dispatching further tasks; do not "
            f"migrate the in-flight task across contracts."
        )

    # Strict subset or incomparable: also require re-negotiation, but the
    # failure is loud (name miss) rather than silent, so surface distinctly.
    raise CapabilitySupersetDrift(
        f"peer card {current.version!r} is not a superset of negotiated "
        f"{cached.version!r}; contract changed, re-negotiation required."
    )
