# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-agent-card-and-then-deadlock-the-task-lifecycle.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-agent-card-and-then-deadlock-the-task-lifecycle.warrant.json
# Markdown SHA-256:   1d07b9cc142f9c8bfb0a9848a89b201316a27028112104752593268b517e972d
# Code AST SHA-256:   8b0ec2eea88e6bcac330105579d15c224e873ac7db01ad089b1bade851d8f171
# Verified Classes:   StaleCardDeadlock, CachedCard, TaskHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class StaleCardDeadlock(RuntimeError):
    """Raised when a task is dispatched against an un-revalidated card and the
    remote parks it in a non-terminal state with no forward progress."""
    pass

@dataclass
class CachedCard:
    resolved_at: float
    skills: set
    push_notifications: bool

@dataclass
class TaskHandle:
    task_id: str
    skill: str
    submitted_at: float
    last_state: str = "submitted"
    last_transition_at: float = field(default_factory=time.monotonic)
    webhook_registered: bool = False
    webhook_received: bool = False

def dispatch(handle: TaskHandle, card: CachedCard, now: float,
             card_ttl: float, submitted_dwell: float,
             webhook_grace: float) -> None:
    # Invariant 1: card currency. A card older than the peer's deploy cadence
    # cannot be trusted to describe the current skill set.
    if now - card.resolved_at > card_ttl:
        raise StaleCardDeadlock(
            f"card resolved {now - card.resolved_at:.0f}s ago exceeds ttl "
            f"{card_ttl:.0f}s; re-resolve before dispatch"
        )
    # Invariant 2: skill binding against the *current* card, client-side,
    # because a permissive remote will enqueue-then-park unknown skills.
    if handle.skill not in card.skills:
        raise StaleCardDeadlock(
            f"skill {handle.skill!r} absent from current card {sorted(card.skills)}"
        )
    # Invariant 3: stasis detection. 'submitted' is not terminal; if it has
    # not advanced within submitted_dwell, fail locally and cancel remotely.
    if handle.last_state == "submitted":
        dwell = now - handle.last_transition_at
        if dwell > submitted_dwell:
            raise StaleCardDeadlock(
                f"task {handle.task_id} stuck in 'submitted' for {dwell:.0f}s "
                f"(budget {submitted_dwell:.0f}s); no forward transition"
            )
    # Invariant 4: webhook as positive obligation, not silence.
    if (handle.webhook_registered and card.push_notifications
            and not handle.webhook_received
            and now - handle.submitted_at > webhook_grace):
        raise StaleCardDeadlock(
            f"task {handle.task_id} registered webhook but no callback within "
            f"{webhook_grace:.0f}s; remote may be parked"
        )
