# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-lifecycle-negotiation-across-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-lifecycle-negotiation-across-vendors.warrant.json
# Markdown SHA-256:   044d147c4561423326c6800424e61734d74931f743efa374ce929fe64e8337e7
# Code AST SHA-256:   01df2184472c335d323300e677bf679f57535869f52a2968e64f3cfc08d4ad94
# Verified Classes:   AgentCardSkewError, CardFingerprint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AgentCardSkewError(RuntimeError):
    """Raised when a task-lifecycle error coincides with a changed Agent Card fingerprint."""


@dataclass(frozen=True)
class CardFingerprint:
    version: str
    capabilities: tuple
    skill_ids: tuple
    security_scheme_keys: tuple
    input_modes: tuple

    @classmethod
    def from_card(cls, card: dict) -> "CardFingerprint":
        caps = card.get("capabilities", {})
        return cls(
            version=str(card.get("version", "")),
            capabilities=tuple(sorted((k, bool(v)) for k, v in caps.items())),
            skill_ids=tuple(sorted(s.get("id", "") for s in card.get("skills", []))),
            security_scheme_keys=tuple(sorted(card.get("securitySchemes", {}).keys())),
            input_modes=tuple(sorted(card.get("defaultInputModes", []))),
        )

    def digest(self) -> str:
        blob = json.dumps(self.__dict__, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()[:16]


def classify_lifecycle_error(
    wire_error_code: int,
    task_fingerprint: CardFingerprint,
    live_card: dict,
) -> str:
    """Classify a task-lifecycle error as genuine vs. card-endpoint skew.

    Returns 'genuine' or 'skew'. Raises AgentCardSkewError when the caller
    is about to replay across a fingerprint change, which is the unsafe action.
    """
    if wire_error_code not in (-32601, -32602, -32001):
        return "genuine"

    live_fp = CardFingerprint.from_card(live_card)
    if live_fp.digest() == task_fingerprint.digest():
        return "genuine"

    # Fingerprint changed: the peer redeployed under us. Replaying here would
    # duplicate side effects against a migrated task store.
    if wire_error_code == -32001:
        raise AgentCardSkewError(
            f"task-not-found under changed card fingerprint "
            f"{task_fingerprint.digest()} -> {live_fp.digest()}; "
            f"refusing replay, enter reconciliation"
        )
    return "skew"


def resume_task(task_id: str, task_fingerprint: CardFingerprint, live_card: dict) -> None:
    # Caller attempted tasks/get; peer returned -32001.
    classify_lifecycle_error(-32001, task_fingerprint, live_card)
