# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-task-after-tasks-send-returns-completed-and-how-does-cross-vendor-agent-card-re-resolution-s.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-task-after-tasks-send-returns-completed-and-how-does-cross-vendor-agent-card-re-resolution-s.warrant.json
# Markdown SHA-256:   6c948a39a5027362138e24390c17581c0ee803ab2159fffb2001fbfd42201368
# Code AST SHA-256:   b4498aa92611de754cce669d823764fb3a8ad341130736b11741bd52b2013d8d
# Verified Classes:   CardDriftUnverifiable, PinnedNegotiation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardDriftUnverifiable(RuntimeError):
    """Raised when the agent card digest changed between negotiation and completion.

    The task may be legitimately completed under the pinned contract, but the
    current card no longer authorizes the client to interpret the artifact.
    This is NOT a task failure and MUST NOT trigger automatic re-issue.
    """


@dataclass(frozen=True)
class PinnedNegotiation:
    task_id: str
    card_digest: str
    skill_id: str
    output_modes: tuple[str, ...]


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


def pin_at_send(card: dict[str, Any], task_id: str, skill_id: str) -> PinnedNegotiation:
    skill = next((s for s in card["skills"] if s["id"] == skill_id), None)
    if skill is None:
        raise CardDriftUnverifiable(f"skill {skill_id!r} absent from card at send time")
    return PinnedNegotiation(
        task_id=task_id,
        card_digest=digest_card(card),
        skill_id=skill_id,
        output_modes=tuple(skill.get("outputModes", [])),
    )


def validate_completion(
    pin: PinnedNegotiation,
    current_card: dict[str, Any],
    task_state: str,
    artifact_mime: str,
) -> None:
    if task_state != "completed":
        return
    current_digest = digest_card(current_card)
    if current_digest != pin.card_digest:
        raise CardDriftUnverifiable(
            f"task {pin.task_id}: card drift {pin.card_digest[:12]} -> "
            f"{current_digest[:12]}; terminal state unverifiable under pinned skill "
            f"{pin.skill_id!r}. Escalate, do not re-issue."
        )
    if artifact_mime not in pin.output_modes:
        raise CardDriftUnverifiable(
            f"task {pin.task_id}: artifact mime {artifact_mime!r} not in pinned "
            f"outputModes {pin.output_modes}; remote breached pinned contract."
        )
