# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-push-notification-callback-that-the-remote-agent-card-never-declared.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-push-notification-callback-that-the-remote-agent-card-never-declared.warrant.json
# Markdown SHA-256:   746c1415b9eb565508286e95361f44360472e20896b1668a632fe999d7635e3e
# Code AST SHA-256:   c4e68d62108900fbf7bec47e4e9ba4a12fdf324cbb05214aa7b6420e01b8a4e6
# Verified Classes:   PushCapabilityViolation, AgentCard, TaskRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class PushCapabilityViolation(RuntimeError):
    """Raised when a task would enter 'working' under an async-delivery
    contract that the remote AgentCard never declared."""
    pass


@dataclass
class AgentCard:
    name: str
    push_notifications: bool
    fetched_at: float


@dataclass
class TaskRecord:
    task_id: str
    state: str = "submitted"
    created_at: float = field(default_factory=time.time)
    delivery_mode: str = "async"


def register_callback(
    task: TaskRecord,
    card: AgentCard,
    set_response: dict,
    request_token: str,
) -> TaskRecord:
    """Gate the submitted -> working transition on a positive capability proof.

    Invariant: working under async delivery requires (1) card advertises
    pushNotifications, observed no earlier than task creation, and
    (2) the server minted a token distinct from the one we sent.
    """
    if task.created_at < card.fetched_at - 1.0:
        # Card observation predates the task; capability may have flipped.
        raise PushCapabilityViolation(
            f"card for {card.name} observed at {card.fetched_at:.0f} "
            f"predates task {task.task_id} created at {task.created_at:.0f}; "
            f"re-fetch required before async binding"
        )

    if not card.push_notifications:
        raise PushCapabilityViolation(
            f"remote {card.name} advertised pushNotifications=false; "
            f"refusing to bind callback for task {task.task_id}"
        )

    returned_token: Optional[str] = (
        set_response.get("result", {})
        .get("pushNotificationConfig", {})
        .get("token")
    )

    if not returned_token:
        raise PushCapabilityViolation(
            f"set RPC for {task.task_id} returned no token; "
            f"server likely stubbed the handler"
        )

    if returned_token == request_token:
        raise PushCapabilityViolation(
            f"set RPC for {task.task_id} echoed client token verbatim; "
            f"no evidence of a wired PushNotificationSender"
        )

    task.state = "working"
    task.delivery_mode = "async"
    return task
