# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-a2a-task-envelope-whose-agent-card-capabilities-block-was-re-fetched-after-signing.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-a2a-task-envelope-whose-agent-card-capabilities-block-was-re-fetched-after-signing.warrant.json
# Markdown SHA-256:   e382ea98a57bfb5110d58f28c047f7d541d1958cb5c04b3eb269dc7d1abf54bc
# Code AST SHA-256:   a2a7b5bde640763c57c71d485f41dad842cad28937bb0a7faf74934620d62256
# Verified Classes:   CardDigestMismatchError, CardUnresolvableError, CapabilityCeilingViolationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class CardDigestMismatchError(RuntimeError):
    """Raised when the resolved Agent Card does not match the signed digest."""


class CardUnresolvableError(RuntimeError):
    """Raised when the Agent Card cannot be fetched at verification time."""


class CapabilityCeilingViolationError(RuntimeError):
    """Raised when effective runtime capabilities exceed the signed card's surface."""


def canonicalize(card: dict) -> bytes:
    # RFC 8785 JCS: sorted keys, no whitespace, UTF-8.
    return json.dumps(card, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def digest(card: dict) -> str:
    return "sha256:" + hashlib.sha256(canonicalize(card)).hexdigest()


def verify_envelope(envelope: dict, resolve_card, effective_capabilities: dict) -> dict:
    signed_digest = envelope["card_digest"]
    try:
        current_card = resolve_card(envelope["card_url"])
    except Exception as exc:
        raise CardUnresolvableError(
            f"cannot resolve {envelope['card_url']} at verification time; "
            f"refusing to fall back to cached card"
        ) from exc

    current_digest = digest(current_card)
    if current_digest != signed_digest:
        raise CardDigestMismatchError(
            f"envelope signed for {signed_digest} but callee card is now {current_digest}; "
            f"rejecting task and returning current digest for re-signing"
        )

    signed_caps = current_card.get("capabilities", {})
    for name, enabled in effective_capabilities.items():
        if enabled and not signed_caps.get(name, False):
            raise CapabilityCeilingViolationError(
                f"runtime capability {name!r} enabled but not advertised in signed card"
            )

    return current_card


def handle_task(envelope: dict, resolve_card, effective_capabilities: dict) -> dict:
    try:
        card = verify_envelope(envelope, resolve_card, effective_capabilities)
    except CardDigestMismatchError as exc:
        return {"state": "rejected", "reason": "card_digest_mismatch", "detail": str(exc)}
    except (CardUnresolvableError, CapabilityCeilingViolationError) as exc:
        return {"state": "rejected", "reason": "verification_failed", "detail": str(exc)}
    return {"state": "working", "card": card, "task": envelope["task_payload"]}
