# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-when-a2a-v1-0-task-delegation-silently-degrades-across-vendor-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-when-a2a-v1-0-task-delegation-silently-degrades-across-vendor-boundaries.warrant.json
# Markdown SHA-256:   efa62243764badee15579495485b08d8061b072f9a8d2a4fcd39d802e74f3b6b
# Code AST SHA-256:   51c970f1ab151884c801058e30ba5a37c64971e5f82e1c49dbc6af32f898c4eb
# Verified Classes:   CardContractMismatch, LifecycleDivergence, PinnedCard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardContractMismatch(RuntimeError):
    """Raised when a received artifact does not conform to the Agent Card
    contract that was pinned at dispatch time. This is a *contract* failure,
    not a transient one: retrying is futile and re-discovery is required."""


class LifecycleDivergence(RuntimeError):
    """Raised when the remote executor enters a task state not present in the
    pinned Card's transition table. The caller must not unilaterally mark the
    task failed; it must refetch the Card or escalate."""


@dataclass
class PinnedCard:
    card_hash: str
    output_modes: list[str]
    allowed_states: set[str]
    artifact_skeleton: frozenset[str]  # sorted key paths of the expected artifact


def skeleton(obj: Any, prefix: str = "") -> frozenset[str]:
    """Structural fingerprint: sorted key paths, values ignored."""
    paths: set[str] = set()
    if isinstance(obj, dict):
        for k, v in obj.items():
            p = f"{prefix}.{k}" if prefix else k
            paths.add(p)
            paths |= skeleton(v, p)
    elif isinstance(obj, list):
        for item in obj:
            paths |= skeleton(item, f"{prefix}[]")
    return frozenset(paths)


def pin_card(card: dict) -> PinnedCard:
    card_hash = hashlib.sha256(
        json.dumps(card, sort_keys=True).encode()
    ).hexdigest()
    return PinnedCard(
        card_hash=card_hash,
        output_modes=card.get("capabilities", {}).get("outputModes", []),
        allowed_states=set(card.get("capabilities", {}).get("states", [])),
        artifact_skeleton=frozenset(),  # populated from declared schema
    )


def validate_artifact(pinned: PinnedCard, artifact: dict, retry_skeletons: list) -> None:
    if artifact.get("mimeType") not in pinned.output_modes:
        raise CardContractMismatch(
            f"artifact mimeType {artifact.get('mimeType')!r} not in pinned "
            f"outputModes {pinned.output_modes} (card {pinned.card_hash[:12]})"
        )
    body = artifact.get("body")
    if isinstance(body, str):
        body = json.loads(body)
    observed = skeleton(body)
    if pinned.artifact_skeleton and observed != pinned.artifact_skeleton:
        retry_skeletons.append(observed)
        if len(retry_skeletons) >= 2 and retry_skeletons[-1] == retry_skeletons[-2]:
            raise CardContractMismatch(
                f"deterministic artifact skeleton mismatch across retries; "
                f"pinned={sorted(pinned.artifact_skeleton)} "
                f"observed={sorted(observed)} card={pinned.card_hash[:12]} "
                f"-> invalidate cached card and re-discover, do not retry"
            )


def advance_state(pinned: PinnedCard, current: str, next_state: str) -> str:
    if next_state not in pinned.allowed_states:
        raise LifecycleDivergence(
            f"peer entered state {next_state!r} absent from pinned transition "
            f"table {sorted(pinned.allowed_states)} card={pinned.card_hash[:12]}; "
            f"refetch card or escalate, do not mark failed"
        )
    return next_state
