# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-signature-endpoint-divergence-from-silently-degrading-a2a-v1-0-delegation-into-a-wrong-tenant-task.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-signature-endpoint-divergence-from-silently-degrading-a2a-v1-0-delegation-into-a-wrong-tenant-task.warrant.json
# Markdown SHA-256:   314a6b6ce91a320cf922a3201b18569af82a02afa523c57dabea36229f228b56
# Code AST SHA-256:   3506f339b9b43df17ddf5b1865d2cefd6b8894202e0de65e651df635d2f10563
# Verified Classes:   CardEndpointDivergence, AgentCard, ExecutorProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CardEndpointDivergence(RuntimeError):
    """Raised when a verified Agent Card cannot be bound to the live executor."""


@dataclass(frozen=True)
class AgentCard:
    raw_bytes: bytes
    url: str
    kid: str
    organization: str

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.raw_bytes).hexdigest()


@dataclass(frozen=True)
class ExecutorProbe:
    card_digest: str
    kid: str
    organization: str


def verify_and_bind(card: AgentCard, probe: ExecutorProbe) -> None:
    """Enforce card-identity == endpoint-identity == execution-identity.

    Signature verification of the card is assumed already done upstream.
    This function enforces the *binding* invariant that signature alone
    does not establish.
    """
    if probe.card_digest != card.digest:
        raise CardEndpointDivergence(
            f"card digest mismatch: cached={card.digest[:12]} "
            f"executor={probe.card_digest[:12]} url={card.url} "
            f"-> stale card or routing re-point; force no-cache refetch"
        )
    if probe.kid != card.kid:
        raise CardEndpointDivergence(
            f"key id mismatch: card_kid={card.kid} executor_kid={probe.kid} "
            f"-> key rotation or shard re-point mid-flight; re-resolve JWKS"
        )
    if probe.organization != card.organization:
        raise CardEndpointDivergence(
            f"tenant mismatch: card_org={card.organization} "
            f"executor_org={probe.organization} -> wrong-tenant execution risk"
        )


def delegate(card: AgentCard, probe: ExecutorProbe, payload: dict) -> dict:
    # Binding pre-flight must pass before any task payload leaves the caller.
    verify_and_bind(card, probe)
    # Only now is it safe to open the signed JSON-RPC tasks/send envelope.
    return {"jsonrpc": "2.0", "method": "tasks/send", "params": payload}
