# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-invalidating-in-flight-a2a-task-state-transitions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-invalidating-in-flight-a2a-task-state-transitions.warrant.json
# Markdown SHA-256:   fc81794d0e040666ebf17b9fb51a47ef40d6380a1be2cd85b9b7087c3e0698f5
# Code AST SHA-256:   b2f6db9cb0c9d31bdbcbecc76a0edc5eb415446ef807a40fade7a2aeea269b78
# Verified Classes:   CardRevisionDriftError, PinnedCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CardRevisionDriftError(RuntimeError):
    """Raised when a re-resolved Agent Card would retroactively change the
    interpretation of an already-created A2A task's lifecycle state."""
    pass


@dataclass
class PinnedCard:
    task_id: str
    context_id: str
    card_hash: str
    capabilities: dict
    skills: list
    raw: dict = field(default_factory=dict)


def _card_hash(card: dict) -> str:
    canonical = json.dumps(
        {
            "capabilities": card.get("capabilities", {}),
            "skills": sorted(
                (s.get("id"), s.get("version"), tuple(s.get("inputModes", [])))
                for s in card.get("skills", [])
            ),
        },
        sort_keys=True,
    )
    return hashlib.sha256(canonical.encode()).hexdigest()


def pin_card_for_task(task_id: str, context_id: str, card: dict) -> PinnedCard:
    return PinnedCard(
        task_id=task_id,
        context_id=context_id,
        card_hash=_card_hash(card),
        capabilities=card.get("capabilities", {}),
        skills=card.get("skills", []),
        raw=card,
    )


def resolve_task_view(
    pinned: PinnedCard,
    fresh_card: dict,
    remote_task: dict,
) -> dict:
    """Interpret a remote Task against the pinned card, not the fresh one.

    If the fresh card diverges in fields that gate state interpretation,
    raise CardRevisionDriftError rather than synthesizing a local failure.
    """
    fresh_hash = _card_hash(fresh_card)
    if fresh_hash != pinned.card_hash:
        # Divergence is an event, not a state transition. Do NOT mark the
        # task failed locally. Surface the drift and continue under the
        # pinned contract.
        raise CardRevisionDriftError(
            f"Card drift for task {pinned.task_id}: "
            f"pinned={pinned.card_hash[:12]} fresh={fresh_hash[:12]}; "
            f"task state must be read under pinned card"
        )

    # Under a matching card, interpret the remote state normally.
    state = remote_task.get("status", {}).get("state")
    if state not in {"submitted", "working", "input-required", "completed", "failed", "canceled"}:
        raise CardRevisionDriftError(
            f"Task {pinned.task_id} returned non-conformant state {state!r}"
        )
    return remote_task


def poll_task(pinned: PinnedCard, fresh_card: dict, remote_task: dict) -> str:
    try:
        view = resolve_task_view(pinned, fresh_card, remote_task)
    except CardRevisionDriftError:
        # Record drift; keep polling under the pinned contract.
        # The remote task's own status is authoritative for completion.
        return remote_task.get("status", {}).get("state", "unknown")
    return view["status"]["state"]
