# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-a-peer-s-agent-card-signature-after-capability-negotiation-and-why-the-negotiated-schema-is-not-covered-by-the-sign.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-a-peer-s-agent-card-signature-after-capability-negotiation-and-why-the-negotiated-schema-is-not-covered-by-the-sign.warrant.json
# Markdown SHA-256:   68b2323d1ee7e39af3fa1542c90164727151f01f277306069b5ee047eb62fe6a
# Code AST SHA-256:   09648dd52713431ac73f3abe1bfc683ada87646c330f8543d4bbe15216d41a74
# Verified Classes:   CapabilityNegotiationError, SignedAgentCard, NegotiationAck
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityNegotiationError(RuntimeError):
    """Raised when a negotiation ack exceeds or aliases the signed Agent Card."""


@dataclass(frozen=True)
class SignedAgentCard:
    agent_id: str
    skills: FrozenSet[str]
    schema_versions: FrozenSet[str]
    streaming: bool
    push_notifications: bool
    signature_verified: bool


@dataclass(frozen=True)
class NegotiationAck:
    effective_skills: FrozenSet[str]
    schema_version: str
    streaming: bool
    push_notifications: bool
    session_id: str = field(default="")


def validate_negotiation_ack(
    card: SignedAgentCard, ack: NegotiationAck
) -> None:
    """Bind the ack to the signed card. Fail closed on any widening.

    The signature on `card` authorizes only the card's own fields.
    The ack is unsigned and must be validated as a strict subset.
    """
    if not card.signature_verified:
        raise CapabilityNegotiationError(
            f"card for {card.agent_id} not signature-verified; refusing to negotiate"
        )

    extra_skills = ack.effective_skills - card.skills
    if extra_skills:
        raise CapabilityNegotiationError(
            f"ack expands skills beyond signed card: {sorted(extra_skills)}"
        )

    if ack.schema_version not in card.schema_versions:
        raise CapabilityNegotiationError(
            f"ack schema_version {ack.schema_version!r} not in signed set "
            f"{sorted(card.schema_versions)} (downgrade/upgrade attack)"
        )

    if ack.streaming and not card.streaming:
        raise CapabilityNegotiationError(
            "ack enables streaming but signed card declared streaming=false"
        )

    if ack.push_notifications and not card.push_notifications:
        raise CapabilityNegotiationError(
            "ack enables pushNotifications but signed card declared false"
        )


def dispatch_task(card: SignedAgentCard, ack: NegotiationAck, skill: str) -> str:
    validate_negotiation_ack(card, ack)
    if skill not in ack.effective_skills:
        raise CapabilityNegotiationError(
            f"requested skill {skill!r} not in negotiated effective set"
        )
    # Dispatch by the verbatim signed identifier; never by a server alias.
    return f"dispatched {skill} to {card.agent_id} under schema {ack.schema_version}"


if __name__ == "__main__":
    signed = SignedAgentCard(
        agent_id="executor-B",
        skills=frozenset({"summarize"}),
        schema_versions=frozenset({"2.0", "2.1"}),
        streaming=True,
        push_notifications=False,
        signature_verified=True,
    )
    poisoned_ack = NegotiationAck(
        effective_skills=frozenset({"summarize", "summarize_private"}),
        schema_version="2.0",
        streaming=True,
        push_notifications=False,
        session_id="sess-42",
    )
    dispatch_task(signed, poisoned_ack, "summarize_private")  # raises
