# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-a2a-task-after-the-remote-agent-has-rotated-its-agent-card-and-re-keyed-its-push-webhook.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-a2a-task-after-the-remote-agent-has-rotated-its-agent-card-and-re-keyed-its-push-webhook.warrant.json
# Markdown SHA-256:   121010e4777482062f55b26ea6158e0cc9f2a07f20c8a69fb7fee87681114bea
# Code AST SHA-256:   adf05a7dfb27a244e4837765dab4a0d1a2832753611d791cb6f908c33b7e2e8e
# Verified Classes:   CardEpochDriftError, AgentCard, TaskCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CardEpochDriftError(RuntimeError):
    """Raised when a resumed A2A task's transport contract no longer matches the peer's current Agent Card."""
    pass


@dataclass
class AgentCard:
    etag: str
    security_schemes: dict
    push_notifications: dict  # e.g. {"required_fields": ["url", "token", "hmac"]}
    capabilities: dict


@dataclass
class TaskCheckpoint:
    task_id: str
    last_state: str
    card_etag: str
    push_binding: dict  # the binding the peer currently holds for us


CONSTITUTIVE_FIELDS = ("security_schemes", "push_notifications", "capabilities")


def resume_task(checkpoint: TaskCheckpoint, current_card: AgentCard, fetch_task_state) -> str:
    # Phase 1: card-epoch diff. Any constitutive change voids the cached contract.
    if checkpoint.card_etag != current_card.etag:
        required = set(current_card.push_notifications.get("required_fields", []))
        held = set(checkpoint.push_binding.keys())
        missing = required - held
        if missing:
            raise CardEpochDriftError(
                f"task {checkpoint.task_id}: card epoch {checkpoint.card_etag}->{current_card.etag} "
                f"tightened push binding; missing required fields {sorted(missing)}; "
                f"re-issue tasks/pushNotificationConfig/set before resume"
            )
        # binding still satisfiable; treat as cosmetic refresh only if no constitutive field changed
        if any(getattr(checkpoint, "_card_" + f, None) != current_card.__dict__.get(f)
               for f in CONSTITUTIVE_FIELDS):
            pass  # in a real impl, compare stored card snapshot; here we proceed to re-read

    # Phase 2: state read must happen AFTER the epoch check, never before.
    state = fetch_task_state(checkpoint.task_id)
    if state in ("completed", "failed", "canceled"):
        raise CardEpochDriftError(
            f"task {checkpoint.task_id}: peer transitioned to terminal '{state}' during suspension; "
            f"do not replay a stale branch"
        )
    return state
