# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-a2a-push-notification-as-stale-when-the-remote-task-lifecycle-has-already-advanced-past-the-webhook.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-a2a-push-notification-as-stale-when-the-remote-task-lifecycle-has-already-advanced-past-the-webhook.warrant.json
# Markdown SHA-256:   f388f4b5a537a428ef21bb8a5f9b6221016e59ed80a76bce623d8687089618d0
# Code AST SHA-256:   f9b8fd09fbc807705ca12ebba7cecdf1e176f93fd4d294b10d4fb3d2b26129b5
# Verified Classes:   StaleWebhookError, AgentCardTransitions, TaskView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleWebhookError(RuntimeError):
    """Raised when a signed webhook describes a state unreachable from the
    last-confirmed state, or a terminal payload that disagrees with the
    most recent authoritative poll."""


@dataclass
class AgentCardTransitions:
    # Ordered DAG of legal transitions as declared in the remote Agent Card.
    edges: set[tuple[str, str]]
    absorbing: set[str] = field(default_factory=set)

    def reachable(self, src: str, dst: str) -> bool:
        if src == dst:
            return True
        # BFS over declared edges.
        frontier, seen = {src}, {src}
        while frontier:
            nxt = set()
            for s in frontier:
                for a, b in self.edges:
                    if a == s and b not in seen:
                        if b == dst:
                            return True
                        seen.add(b)
                        nxt.add(b)
            frontier = nxt
        return False


@dataclass
class TaskView:
    task_id: str
    state: str
    payload_hash: str
    last_confirmed_seq: int


def apply_webhook(
    view: TaskView,
    webhook_state: str,
    webhook_seq: int,
    webhook_payload_hash: str,
    graph: AgentCardTransitions,
    latest_poll_payload_hash: Optional[str],
) -> TaskView:
    if webhook_seq <= view.last_confirmed_seq:
        raise StaleWebhookError(
            f"webhook seq={webhook_seq} not newer than confirmed "
            f"seq={view.last_confirmed_seq} for task {view.task_id}"
        )

    if not graph.reachable(view.state, webhook_state):
        raise StaleWebhookError(
            f"webhook state {webhook_state!r} unreachable from "
            f"last-confirmed {view.state!r} for task {view.task_id}; "
            f"remote transition graph does not permit this edge"
        )

    # Terminal state: payload must be confirmed by a poll, never trusted from
    # the webhook alone -- the webhook is an enqueue-time snapshot.
    if webhook_state in graph.absorbing:
        if latest_poll_payload_hash is None:
            raise StaleWebhookError(
                f"terminal webhook for task {view.task_id} arrived with no "
                f"confirming poll; refusing to finalize on enqueue-time payload"
            )
        if latest_poll_payload_hash != webhook_payload_hash:
            raise StaleWebhookError(
                f"terminal webhook payload for task {view.task_id} "
                f"({webhook_payload_hash[:12]}) disagrees with authoritative "
                f"poll ({latest_poll_payload_hash[:12]}); webhook is a "
                f"stale-finalization snapshot"
            )

    return TaskView(
        task_id=view.task_id,
        state=webhook_state,
        payload_hash=webhook_payload_hash,
        last_confirmed_seq=webhook_seq,
    )
