# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-forking-task-state-across-a2a-v1-0-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-forking-task-state-across-a2a-v1-0-vendors.warrant.json
# Markdown SHA-256:   0d3b348a6bc1e9f077476a068a2e3d5ec0f392b609ae8ae1ee36317d71c5a2e8
# Code AST SHA-256:   4dac3628dab45c4d3c35cfb181aadf7540e0f3dffbc46ee205dcbd637537f065
# Verified Classes:   CardDriftForkError, PinnedTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardDriftForkError(RuntimeError):
    """Raised when a mid-task resume is validated against a different Agent Card
    than the one pinned at task creation, or when no fingerprint is available
    to prove the contract is unchanged."""


@dataclass
class PinnedTask:
    task_id: str
    card_hash: str
    local_state: str = "submitted"
    artifacts_emitted: list = field(default_factory=list)


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


def resume_task(
    pinned: PinnedTask,
    resume_response: dict,
    current_card: dict,
) -> PinnedTask:
    """Advance a pinned task only if the server's resume echo proves contract continuity."""
    status = resume_response.get("status", {})
    server_fingerprint: Optional[str] = status.get("metadata", {}).get("cardVersion")

    if server_fingerprint is None:
        # Absence of fingerprint is not "probably fine" — it collapses clean and
        # drifted resumes into the same shape. Treat as unverified.
        raise CardDriftForkError(
            f"task {pinned.task_id}: resume response carries no cardVersion; "
            "cannot prove continuity, refusing to advance local state"
        )

    if server_fingerprint != pinned.card_hash:
        raise CardDriftForkError(
            f"task {pinned.task_id}: card drifted mid-task "
            f"(pinned={pinned.card_hash[:12]}, server={server_fingerprint[:12]}); "
            "discard optimistic state, re-discover, re-plan from last checkpoint"
        )

    if pin_card(current_card) != pinned.card_hash:
        raise CardDriftForkError(
            f"task {pinned.task_id}: live card no longer matches pinned contract; "
            "resume would fork lineage against a server that re-advertised"
        )

    pinned.local_state = status.get("state", pinned.local_state)
    return pinned
