# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-pin-the-a2a-v1-0-agent-card-signing-key-discovery-time-trust-anchoring-versus-envelope-time-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-pin-the-a2a-v1-0-agent-card-signing-key-discovery-time-trust-anchoring-versus-envelope-time-verification.warrant.json
# Markdown SHA-256:   5aed6e3744413233dd66ca9f3c72fab305401ac180dc6d492e903be0c5756654
# Code AST SHA-256:   15315c60900616aab1da7c67d5685ada64cc73c5525e17355e1d78be43aedba2
# Verified Classes:   EnvelopeTrustBoundaryError, KeyRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class EnvelopeTrustBoundaryError(RuntimeError):
    """Raised when a delegation envelope's key cannot be anchored to a
    delegation-purpose key set attested by the Agent Card."""


@dataclass(frozen=True)
class KeyRecord:
    kid: str
    purpose: str  # "card-attestation" | "delegation"


def resolve_envelope_key(
    envelope_kid: str,
    card_signing_kid: str,
    attested_key_set: Mapping[str, KeyRecord],
) -> KeyRecord:
    """Resolve an envelope signing key strictly through the card-attested
    key set, never through the card's own signing key."""
    if envelope_kid == card_signing_kid:
        raise EnvelopeTrustBoundaryError(
            f"envelope kid {envelope_kid!r} matches card-signing key; "
            "card attestation does not confer delegation authority"
        )
    record = attested_key_set.get(envelope_kid)
    if record is None:
        raise EnvelopeTrustBoundaryError(
            f"envelope kid {envelope_kid!r} absent from attested key set"
        )
    if record.purpose != "delegation":
        raise EnvelopeTrustBoundaryError(
            f"key {envelope_kid!r} has purpose {record.purpose!r}, "
            "not 'delegation'"
        )
    return record


def verify_delegation_envelope(
    envelope_kid: str,
    card_signing_kid: str,
    attested_key_set: Mapping[str, KeyRecord],
    signature_valid: bool,
) -> None:
    key = resolve_envelope_key(envelope_kid, card_signing_kid, attested_key_set)
    if not signature_valid:
        raise EnvelopeTrustBoundaryError(
            f"signature invalid for delegation key {key.kid!r}"
        )
