# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-binding-during-a2a-v1-0-task-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-binding-during-a2a-v1-0-task-continuation.warrant.json
# Markdown SHA-256:   33cd821fce6723ca231ae70830a71872a3b042f42d2dcfdddfb77cffea1625fd
# Code AST SHA-256:   dc9e0790a8e47af60bf90100832e32e121330c2a4d08dc7a7ccd980a581307fc
# Verified Classes:   StaleCardBindingError, CardBinding, TaskRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleCardBindingError(RuntimeError):
    """Raised when a task continuation is attempted against a card binding
    that no longer matches the binding under which the task was created."""


@dataclass(frozen=True)
class CardBinding:
    url: str
    skill_ids: tuple[str, ...]
    streaming: bool
    version: str

    def hash(self) -> str:
        payload = json.dumps(
            {"url": self.url, "skills": sorted(self.skill_ids),
             "streaming": self.streaming, "version": self.version},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class TaskRecord:
    task_id: str
    binding_hash: str
    binding_url: str
    skill_id: str


def resolve_continuation(
    record: TaskRecord,
    fresh_card: CardBinding,
    *,
    task_reachable_under_new_url: bool,
) -> CardBinding:
    """Decide whether to continue, reconcile, or escalate a task continuation.

    Invariant: a taskId is only valid against the card binding under which it
    was created. A hash mismatch is a reconciliation event, not a transient
    retry.
    """
    if fresh_card.hash() == record.binding_hash:
        return fresh_card

    if not task_reachable_under_new_url:
        raise StaleCardBindingError(
            f"task {record.task_id} unreachable under new binding "
            f"{fresh_card.url} (was {record.binding_url}); "
            f"task lost, escalate to caller"
        )

    if record.skill_id not in fresh_card.skill_ids:
        raise StaleCardBindingError(
            f"task {record.task_id} was dispatched under skill "
            f"{record.skill_id!r} which is absent from new card "
            f"{fresh_card.url}; artifacts may be incompatible, "
            f"do not re-dispatch"
        )

    return fresh_card
