# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-overclaiming-from-silently-escalating-into-cross-vendor-task-misrouting-during-a2a-v1-0-discovery-hands.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-overclaiming-from-silently-escalating-into-cross-vendor-task-misrouting-during-a2a-v1-0-discovery-hands.warrant.json
# Markdown SHA-256:   6cc816406dc7100f2d99b2bf78aa8b53ade308e665c31983823e76e8541e3367
# Code AST SHA-256:   4f0abbd79993614ac2ea94f5b63a60add0d8705bb6ee97bd3e53be1411088eac
# Verified Classes:   CapabilityOverclaimError, AgentCard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CapabilityOverclaimError(RuntimeError):
    """Raised when a skills[] match is used as dispatch authority without proof."""


@dataclass(frozen=True)
class AgentCard:
    body: dict[str, Any]

    @property
    def card_hash(self) -> str:
        canonical = json.dumps(self.body, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


def _schema_is_discriminating(schema: dict[str, Any], sample_bad: dict[str, Any]) -> bool:
    # A schema that admits both the empty object and a known-bad payload
    # is not a proof of dispatch conformance.
    required = schema.get("required", [])
    if not required:
        return False
    return any(field in required for field in sample_bad)


def authorize_dispatch(
    card: AgentCard,
    skill_id: str,
    payload: dict[str, Any],
    known_bad_payload: dict[str, Any],
    probe_cache: dict[tuple[str, str], bool],
) -> None:
    skill = next((s for s in card.body.get("skills", []) if s.get("id") == skill_id), None)
    if skill is None:
        raise CapabilityOverclaimError(
            f"skill {skill_id!r} absent from card {card.card_hash[:12]}"
        )

    schema = skill.get("inputSchema")
    if schema is not None:
        if not _schema_is_discriminating(schema, known_bad_payload):
            raise CapabilityOverclaimError(
                f"skill {skill_id!r} schema is non-discriminating; "
                f"cannot serve as dispatch proof for card {card.card_hash[:12]}"
            )
        # local validation would run here; a passing schema with required
        # fields is accepted as proof.
        return

    # No machine-readable schema: probe is mandatory and must be bound to card hash.
    probe_key = (card.card_hash, skill_id)
    if not probe_cache.get(probe_key):
        raise CapabilityOverclaimError(
            f"no probe result bound to card hash {card.card_hash[:12]} for skill "
            f"{skill_id!r}; refusing optimistic dispatch"
        )
