# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-replay-divergence-from-silently-re-authorizing-a-delegated-task-envelope-across-heterogeneous-a2a-v1-0-runtimes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-replay-divergence-from-silently-re-authorizing-a-delegated-task-envelope-across-heterogeneous-a2a-v1-0-runtimes.warrant.json
# Markdown SHA-256:   7fb57d0c2f812b6546b3a00fe5824f25d87d5f1ad19fc71bf1d25748e27c0231
# Code AST SHA-256:   b72fb5daab1de5045090d59e6f1bf7c69e5a8e0ba60da971dd058b58a4dd3dba
# Verified Classes:   CardBindingError, Envelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CardBindingError(RuntimeError):
    """Raised when a delegation envelope's card binding cannot be validated."""


@dataclass(frozen=True)
class Envelope:
    card_id: str
    card_version: int
    card_digest: str          # hex sha256 of canonical card body at signing time
    granted_skills: frozenset[str]


def canonical_digest(body_bytes: bytes) -> str:
    return hashlib.sha256(body_bytes).hexdigest()


def validate_envelope(env: Envelope, pinned_body_bytes: bytes | None,
                      current_version: int) -> frozenset[str]:
    """
    Fail-closed validation of a delegation envelope against a content-addressed
    card body. Returns the effective skill set, which is exactly the signed grant
    and nothing more.
    """
    if pinned_body_bytes is None:
        # Card body for the signed digest is unavailable (GC'd / never published).
        # Must fail closed. Falling back to 'latest' is the divergence bug.
        raise CardBindingError(
            f"card digest {env.card_digest} unresolvable for card_id={env.card_id}; "
            "refusing to fall back to current card"
        )

    actual = canonical_digest(pinned_body_bytes)
    if actual != env.card_digest:
        # Executor's registry served bytes whose hash differs from the signed digest.
        # This is a registry integrity failure, not a version skew.
        raise CardBindingError(
            f"digest mismatch: envelope={env.card_digest} body={actual}"
        )

    # Version equality is an independent cheap check; do not accept
    # 'env.card_version <= current_version' as sufficient.
    if env.card_version != current_version:
        raise CardBindingError(
            f"version skew: envelope={env.card_version} current={current_version}"
        )

    # The signed grant must be a subset of the pinned body's declared skills.
    # Parse pinned_body_bytes here (omitted) to obtain pinned_skills.
    pinned_skills = frozenset()  # placeholder; real impl parses pinned_body_bytes
    if not env.granted_skills.issubset(pinned_skills):
        raise CardBindingError(
            f"grant escalation: {env.granted_skills - pinned_skills} not in pinned card"
        )

    return env.granted_skills
