# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-in-a2a-v1-0-agent-card-discovery-and-cross-vendor-task-delegation-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-in-a2a-v1-0-agent-card-discovery-and-cross-vendor-task-delegation-negotiation.warrant.json
# Markdown SHA-256:   230f3d6fc7c10d1c6d03d6651aad082739a62a5b49eeb66281a370c6b77b5bd4
# Code AST SHA-256:   2487269c119da04953800e92026f48ad6cfe6f6e5bcd9ce56fcf8d3a276e8252
# Verified Classes:   CapabilityDriftError, PinnedCard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityDriftError(RuntimeError):
    """Raised when a peer's live capability subtree diverges from the pinned hash."""


@dataclass(frozen=True)
class PinnedCard:
    endpoint: str
    card_version: str
    capability_hash: str


def capability_hash(card: dict) -> str:
    # Hash only the capability subtree; identity/version fields are excluded
    # because vendors mutate them inconsistently across behavioral changes.
    subtree = card.get("capabilities", {})
    canonical = json.dumps(subtree, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def negotiate_delegation(
    pinned: PinnedCard,
    live_card: dict,
    task_is_idempotent_safe: bool,
) -> None:
    live_hash = capability_hash(live_card)

    if live_hash == pinned.capability_hash:
        return  # cache is still a valid basis for delegation

    # Drift detected. Safe only if the task tolerates it AND the result
    # validator can independently detect truncation.
    if task_is_idempotent_safe:
        return

    raise CapabilityDriftError(
        f"capability drift at {pinned.endpoint}: "
        f"pinned={pinned.capability_hash[:12]} live={live_hash[:12]} "
        f"card_version={pinned.card_version} (version unchanged, subtree changed); "
        f"refusing non-idempotent delegation on stale cache"
    )
