# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-a2a-task-when-the-agent-card-s-capabilities-pushnotifications-flag-has-silently-flipped-between-discovery-epoc.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-a2a-task-when-the-agent-card-s-capabilities-pushnotifications-flag-has-silently-flipped-between-discovery-epoc.warrant.json
# Markdown SHA-256:   d9c34949670ab1b7851b7218b0e1a118e5610e0113d088ce0f17830149151e1a
# Code AST SHA-256:   9eeefcbe3b68d23060715b5f94a6090a357edd7e50ced9c9a5c2673807bb5992
# Verified Classes:   PushNotificationEpochRevoked, CardEpoch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class PushNotificationEpochRevoked(RuntimeError):
    """Raised when a resumed A2A task's webhook transport was withdrawn
    between the discovery epoch recorded at tasks/send and the epoch
    observed at resumption."""


@dataclass(frozen=True)
class CardEpoch:
    push_notifications: bool
    push_block_hash: str  # hash of the pushNotifications object, or "" if absent

    @classmethod
    def from_card(cls, card: dict) -> "CardEpoch":
        caps = card.get("capabilities", {}) or {}
        pn = card.get("pushNotifications")
        pn_hash = (
            hashlib.sha256(json.dumps(pn, sort_keys=True).encode()).hexdigest()
            if pn
            else ""
        )
        return cls(bool(caps.get("pushNotifications", False)), pn_hash)


def assert_resumable(recorded: CardEpoch, current: CardEpoch, task_id: str) -> None:
    """Gate every tasks/resume or tasks/get-for-resumption on this check.

    A taskId is durable; the webhook contract that made it observable is not.
    If the peer flipped pushNotifications off, or reshaped the push block
    (key rotation, URL allowlist change), the task may be alive but we have
    no channel to learn its terminal state. Refuse to wait on it.
    """
    if not current.push_notifications:
        raise PushNotificationEpochRevoked(
            f"task {task_id}: peer disabled capabilities.pushNotifications "
            f"between epochs; webhook will never fire. Downgrade to polling "
            f"tasks/get or fail the task as transport-withdrawn."
        )
    if recorded.push_block_hash != current.push_block_hash:
        raise PushNotificationEpochRevoked(
            f"task {task_id}: pushNotifications block changed "
            f"(recorded={recorded.push_block_hash[:12]!r}, "
            f"current={current.push_block_hash[:12]!r}); prior registration "
            f"is stale. Re-register via tasks/pushNotificationConfig/set "
            f"before resuming."
        )
