# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-it-cannot-execute-the-jws-signed-agent-card-capability-task-envelope-divergence-and-the-accepted-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-it-cannot-execute-the-jws-signed-agent-card-capability-task-envelope-divergence-and-the-accepted-fail.warrant.json
# Markdown SHA-256:   39b52b56aa87f0eb811ed04d6e3d8084304a2fc5fadaffb9fe40edcb5945823a
# Code AST SHA-256:   f1a60ce5db8c308f82e1163b22d7ac07826d1fdfd830099b11687b0f418ddcea
# Verified Classes:   CapabilityAcceptanceDivergence, SignedAgentCard, TaskEnvelope, TaskResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class CapabilityAcceptanceDivergence(RuntimeError):
    """Raised when a delegated task is accepted but cannot be confirmed executable
    within the caller's stage deadline, or when the signed card cannot bound the
    task's required capabilities."""
    pass


@dataclass
class SignedAgentCard:
    skills: list[str]
    max_input_tokens: Optional[int]   # None == undeclared
    signed_at: float
    worker_pool_version: Optional[str]


@dataclass
class TaskEnvelope:
    skill: str
    max_input_tokens: int
    output_schema: str


@dataclass
class TaskResponse:
    state: str                        # submitted | accepted | completed | failed
    worker_pool_version: Optional[str]
    task_id: str


def dispatch_or_hold(
    card: SignedAgentCard,
    task: TaskEnvelope,
    response: TaskResponse,
    stage_timeout_s: float,
    safety_margin_s: float = 2.0,
    assumed_worker_ceiling: int = 128_000,
    max_card_age_s: float = 3600.0,
) -> str:
    """
    Returns 'hold' if the caller must retain input context and block on a terminal
    state; returns 'release' only when every capability bound is verified.
    Raises CapabilityAcceptanceDivergence when acceptance cannot be trusted.
    """
    if task.skill not in card.skills:
        raise CapabilityAcceptanceDivergence(
            f"task skill {task.skill!r} not in signed card skills {card.skills!r}"
        )

    card_age = time.time() - card.signed_at
    if card_age > max_card_age_s:
        # Stale signed card: signature valid, fleet possibly rotated.
        raise CapabilityAcceptanceDivergence(
            f"card age {card_age:.0f}s exceeds max {max_card_age_s:.0f}s; "
            f"cannot bound worker capacity"
        )

    ceiling = card.max_input_tokens if card.max_input_tokens is not None else assumed_worker_ceiling
    if task.max_input_tokens > ceiling:
        # Card does not guarantee capacity for this task; hold and block.
        return "hold"

    if response.state == "accepted":
        if card.worker_pool_version is None:
            # No echo contract: acceptance is transport-only, never release.
            return "hold"
        if response.worker_pool_version != card.worker_pool_version:
            raise CapabilityAcceptanceDivergence(
                f"worker pool version drift: card={card.worker_pool_version!r} "
                f"response={response.worker_pool_version!r}; re-fetch and re-verify card"
            )

    if response.state in ("completed", "failed"):
        return "release"  # terminal; context no longer needed for this task

    # Non-terminal, unconfirmed: caller must own the wait.
    poll_deadline = stage_timeout_s - safety_margin_s
    if poll_deadline <= 0:
        raise CapabilityAcceptanceDivergence(
            f"stage_timeout {stage_timeout_s}s leaves no polling window after "
            f"safety margin {safety_margin_s}s"
        )
    return "hold"
