# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-a2a-artifact-version-divergence-during-cross-vendor-task-resumption-after-a-peer-restarts-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-a2a-artifact-version-divergence-during-cross-vendor-task-resumption-after-a-peer-restarts-mid-stream.warrant.json
# Markdown SHA-256:   b7a3a5a3a036c9d4f48b4edfecaa02e250233bc6e0b9d10097c3ba55123a9247
# Code AST SHA-256:   a015124a1f85997cd2c798c35fef9926828e4a520857ed2a1deee8b547e3d533
# Verified Classes:   ArtifactCardDivergence, PinnedCard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ArtifactCardDivergence(RuntimeError):
    """Raised when a resumed A2A artifact is served under a card that differs
    from the card pinned at task submission, in an artifact-affecting field."""


@dataclass(frozen=True)
class PinnedCard:
    task_id: str
    fingerprint: str


def _artifact_affecting_subset(card: dict) -> dict:
    # Only the fields that change how artifact parts must be parsed.
    return {
        "skills": [
            {
                "id": s.get("id"),
                "artifacts": s.get("artifacts", []),
                "inputModes": s.get("inputModes", []),
                "outputModes": s.get("outputModes", []),
            }
            for s in card.get("skills", [])
        ],
        "defaultInputModes": card.get("defaultInputModes", []),
        "defaultOutputModes": card.get("defaultOutputModes", []),
        "capabilities": card.get("capabilities", {}),
    }


def fingerprint_card(card: dict) -> str:
    canonical = json.dumps(
        _artifact_affecting_subset(card),
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(canonical).hexdigest()


def pin_card_on_submit(task_id: str, card: dict) -> PinnedCard:
    return PinnedCard(task_id=task_id, fingerprint=fingerprint_card(card))


def verify_resumed_artifact(
    pinned: PinnedCard,
    current_card: dict,
    artifact: dict,
    previously_seen_artifact_ids: set[str],
) -> None:
    current_fp = fingerprint_card(current_card)
    artifact_id = artifact.get("artifactId")

    # Unchanged artifact identity: safe to accept regardless of card drift.
    if artifact_id in previously_seen_artifact_ids:
        return

    # New artifact under a drifted card: this is a replacement, not a continuation.
    if current_fp != pinned.fingerprint:
        raise ArtifactCardDivergence(
            f"task {pinned.task_id}: resumed artifact {artifact_id!r} "
            f"(name={artifact.get('name')!r}) served under card fingerprint "
            f"{current_fp[:12]} but task was pinned to {pinned.fingerprint[:12]}. "
            f"Refusing to interpret; renegotiate the task boundary."
        )
