# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-across-a-task-lifecycle-transition-and-the-remote-peer-s-artifact-mime-schema-has-silently-dr.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-across-a-task-lifecycle-transition-and-the-remote-peer-s-artifact-mime-schema-has-silently-dr.warrant.json
# Markdown SHA-256:   ed2a9d711c3364b61c237d41e42becb4172cdda64f4cb05e244966cfed720b62
# Code AST SHA-256:   09d0ad19ba0a2f65578befa7c27c50a1e6eb530ae647c425bd84d1e9aacddfc6
# Verified Classes:   ArtifactNegotiationDrift, DispatchPin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ArtifactNegotiationDrift(RuntimeError):
    """Raised when a terminal artifact's media type falls outside the
    dispatch-pinned output-mode subset, or when the cached AgentCard
    version changed between dispatch and completion."""
    pass


@dataclass
class DispatchPin:
    task_context_id: str
    card_version_hash: str
    accepted_mime_types: frozenset[str]
    idempotency_key: str


def _hash_card(card: dict) -> str:
    # Canonical hash of the capability envelope we actually relied on.
    payload = repr(sorted((card.get("skills") or [{}])[0].get("outputModes", []))).encode()
    return hashlib.sha256(payload).hexdigest()


def pin_contract(card: dict, requested_modes: list[str], context_id: str) -> DispatchPin:
    declared = set((card.get("skills") or [{}])[0].get("outputModes", []))
    accepted = declared.intersection(requested_modes)
    if not accepted:
        raise ArtifactNegotiationDrift(
            f"requested modes {requested_modes} disjoint from declared {declared}"
        )
    return DispatchPin(
        task_context_id=context_id,
        card_version_hash=_hash_card(card),
        accepted_mime_types=frozenset(accepted),
        idempotency_key=hashlib.sha256(context_id.encode()).hexdigest(),
    )


def validate_terminal_artifact(
    pin: DispatchPin,
    current_card: dict,
    artifact_part: dict,
    task_state: str,
) -> None:
    if task_state != "completed":
        return  # only terminal artifacts are frozen and validated here

    if _hash_card(current_card) != pin.card_version_hash:
        # Card drifted mid-flight; the pin is no longer anchored to a live card.
        raise ArtifactNegotiationDrift(
            f"card version changed between dispatch and completion for "
            f"context {pin.task_context_id}; refusing to trust artifact"
        )

    mime = (artifact_part.get("metadata") or {}).get("mimeType")
    if mime not in pin.accepted_mime_types:
        # Peer selected a declared-but-unpinned mode; do NOT re-dispatch.
        raise ArtifactNegotiationDrift(
            f"artifact mimeType {mime!r} outside dispatch-pinned subset "
            f"{sorted(pin.accepted_mime_types)} for context {pin.task_context_id}"
        )
