# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-delegated-a2a-task-after-its-peer-s-agent-card-has-been-re-signed-and-its-input-required-prompt-has-silently-e.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-delegated-a2a-task-after-its-peer-s-agent-card-has-been-re-signed-and-its-input-required-prompt-has-silently-e.warrant.json
# Markdown SHA-256:   cbf92db834ed4e57a4658d54178d74b531eb4e3d56da7ef6ccb1e1c18791fae8
# Code AST SHA-256:   0ff47cec07c8be2179d48e1d724d6444748f981159a5abf09076cdb2d9041232
# Verified Classes:   StaleContinuationError, PersistedTask, LiveCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleContinuationError(RuntimeError):
    """Raised when a persisted A2A continuation token is bound to a card
    generation that no longer matches the peer's current AgentCard."""


@dataclass(frozen=True)
class PersistedTask:
    task_id: str
    continuation_id: str
    card_signature: str      # signature under which continuation was minted
    card_url: str            # url at mint time


@dataclass(frozen=True)
class LiveCard:
    signature: str
    url: str


def resume_task(task: PersistedTask, live_card: LiveCard) -> str:
    """Decide whether a parked input-required task is safe to resume.

    Returns the continuation_id to send, or raises if the card generation
    has rotated and the token must be treated as untrusted.
    """
    if live_card.signature != task.card_signature:
        raise StaleContinuationError(
            f"task {task.task_id}: continuation {task.continuation_id!r} "
            f"was minted under card signature {task.card_signature!r} "
            f"but peer now advertises {live_card.signature!r}; "
            f"re-discover and re-fetch before resuming"
        )
    if live_card.url != task.card_url:
        # Same signature but relocated endpoint: also untrusted, because the
        # continuation may be scoped per-host even when the key is unchanged.
        raise StaleContinuationError(
            f"task {task.task_id}: card url moved {task.card_url!r} -> "
            f"{live_card.url!r}; continuation binding is host-scoped"
        )
    return task.continuation_id


def fingerprint(signature: str, continuation_id: str) -> str:
    return hashlib.sha256(f"{signature}:{continuation_id}".encode()).hexdigest()
