# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-negotiation-drift-when-an-a2a-v1-0-agent-card-is-re-fetched-mid-handoff-across-heterogeneous-runtimes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-negotiation-drift-when-an-a2a-v1-0-agent-card-is-re-fetched-mid-handoff-across-heterogeneous-runtimes.warrant.json
# Markdown SHA-256:   a051861b98b284bb2633e664d1f40012cad3727d084e6ac4fd64c0ea7794ec3a
# Code AST SHA-256:   30cb08d73b668690c80db415e16457932ae1589af4441718338a130130c59c63
# Verified Classes:   CapabilityDriftError, PinnedTask, CardPinningClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class CapabilityDriftError(RuntimeError):
    """Raised when a re-fetched Agent Card diverges from the task-pinned snapshot
    on a capability-gating field mid-task."""


# Fields whose change alters dispatch or response parsing. Descriptive fields
# (description, examples, documentationUrl) are deliberately excluded.
GATING_FIELDS = (
    "capabilities.streaming",
    "capabilities.pushNotifications",
    "defaultInputModes",
    "defaultOutputModes",
)


def _gating_view(card: dict[str, Any]) -> dict[str, Any]:
    view: dict[str, Any] = {}
    for path in GATING_FIELDS:
        node: Any = card
        for key in path.split("."):
            node = node.get(key) if isinstance(node, dict) else None
        view[path] = node
    view["skills"] = sorted(
        (
            {
                "id": s.get("id"),
                "version": s.get("version"),
                "inputModes": sorted(s.get("inputModes") or []),
                "outputModes": sorted(s.get("outputModes") or []),
            }
            for s in (card.get("skills") or [])
        ),
        key=lambda s: (s["id"] or "", s["version"] or ""),
    )
    return view


def snapshot_hash(card: dict[str, Any]) -> str:
    payload = json.dumps(_gating_view(card), sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class PinnedTask:
    task_id: str
    card_hash: str
    card: dict[str, Any] = field(repr=False)


class CardPinningClient:
    def __init__(self) -> None:
        self._pinned: dict[str, PinnedTask] = {}

    def accept_task(self, task_id: str, card: dict[str, Any]) -> None:
        self._pinned[task_id] = PinnedTask(
            task_id=task_id, card_hash=snapshot_hash(card), card=card
        )

    def on_turn_refetch(self, task_id: str, fresh_card: dict[str, Any]) -> None:
        """Called when the client re-resolves the card mid-task.

        A mismatch on a gating field is a *signal*, not an instruction: the task
        must continue against the pinned snapshot. We raise so the caller pauses
        for review instead of silently adapting to the new contract.
        """
        pinned = self._pinned.get(task_id)
        if pinned is None:
            raise CapabilityDriftError(
                f"task {task_id!r} has no pinned card; refusing to negotiate live"
            )
        if snapshot_hash(fresh_card) != pinned.card_hash:
            raise CapabilityDriftError(
                f"capability drift on task {task_id!r}: "
                f"pinned={pinned.card_hash[:12]} fresh={snapshot_hash(fresh_card)[:12]}; "
                f"freeze snapshot and re-negotiate on next task, do not adapt mid-task"
            )

    def release_task(self, task_id: str) -> None:
        self._pinned.pop(task_id, None)


def handle_turn(
    client: CardPinningClient,
    task_id: str,
    fresh_card: dict[str, Any],
    is_new_task: bool,
) -> None:
    if is_new_task:
        client.accept_task(task_id, fresh_card)
        return
    try:
        client.on_turn_refetch(task_id, fresh_card)
    except CapabilityDriftError:
        # Pause, do not fork. Re-raising preserves the operator signal.
        raise
