# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-a2a-agent-card-when-the-signed-manifest-verifies-but-the-declared-capability-surface-exceeds-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-a2a-agent-card-when-the-signed-manifest-verifies-but-the-declared-capability-surface-exceeds-th.warrant.json
# Markdown SHA-256:   a4ffee9f2e61a11184e66e13b1e7fe1d07684f8415cba3839b717a7f34d7053e
# Code AST SHA-256:   d67dc585f173dd49d2020ef56b474ecb0099818b9cfaaffc52e79a9c7e565fbe
# Verified Classes:   CapabilityAuthorityMismatch, AuthorityScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilityAuthorityMismatch(RuntimeError):
    """Raised when a signed agent card asserts capabilities beyond its signing key's scope."""
    pass


@dataclass(frozen=True)
class AuthorityScope:
    kid: str
    granted_verbs: frozenset[str]


def verify_and_admit(
    card_jws: str,
    card_capabilities: frozenset[str],
    kid: str,
    signature_valid: bool,
    scope_registry: dict[str, AuthorityScope],
) -> frozenset[str]:
    # Predicate 1: signature authenticity.
    if not signature_valid:
        raise CapabilityAuthorityMismatch(f"card JWS failed signature verification for kid={kid}")

    # Predicate 2: authority binding. Must not be short-circuited by predicate 1.
    scope = scope_registry.get(kid)
    if scope is None:
        # Fail closed: unresolved authority is not permissive authority.
        raise CapabilityAuthorityMismatch(
            f"no authority scope on record for kid={kid}; refusing discovery"
        )

    excess = card_capabilities - scope.granted_verbs
    if excess:
        raise CapabilityAuthorityMismatch(
            f"kid={kid} signed a card asserting capabilities outside its authority scope: "
            f"{sorted(excess)} (granted: {sorted(scope.granted_verbs)})"
        )

    # Only the intersection that the authority actually covers may enter routing.
    return card_capabilities & scope.granted_verbs


def admit_card(card_jws: str, card_capabilities: frozenset[str], kid: str,
               signature_valid: bool, scope_registry: dict[str, AuthorityScope]) -> frozenset[str]:
    admitted = verify_and_admit(
        card_jws, card_capabilities, kid, signature_valid, scope_registry
    )
    digest = hashlib.sha256(card_jws.encode()).hexdigest()[:12]
    print(f"admitted {len(admitted)} verbs from card {digest} under kid={kid}")
    return admitted
