# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-agent-card-as-a-stale-capability-contract-rather-than-a-live-one.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-agent-card-as-a-stale-capability-contract-rather-than-a-live-one.warrant.json
# Markdown SHA-256:   cfcb3314402acbe8976585d9b8150479236401a6c99dc1d20dff246c256d20fc
# Code AST SHA-256:   605ed15ff2a564b418ebdfdff5bbee496b1019737879158b9efa57cc06832ffe
# Verified Classes:   StaleAgentCardError, NotificationUnreconciledError, AgentCard, TaskNegotiation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a task is negotiated against a card that no longer
    asserts the skill or push-notification contract the task depends on."""


class NotificationUnreconciledError(RuntimeError):
    """Raised when a task reached a terminal server state but neither a
    confirmed push delivery nor a tasks/get reconciliation occurred within
    the bounded window."""


@dataclass
class AgentCard:
    fetched_at: float
    skills: set[str]
    push_supported: bool
    push_auth_schemes: set[str]


@dataclass
class TaskNegotiation:
    skill_id: str
    card: AgentCard
    push_scheme: Optional[str] = None
    registered_at: Optional[float] = None
    terminal_server_state: Optional[str] = None
    notification_confirmed: bool = False
    reconciled: bool = False


def negotiate_task(
    task: TaskNegotiation,
    live_card: AgentCard,
    card_max_age_s: float = 60.0,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # Invariant 1: the card used for negotiation must be fresh at task start.
    if now - live_card.fetched_at > card_max_age_s:
        raise StaleAgentCardError(
            f"card age {now - live_card.fetched_at:.1f}s exceeds "
            f"{card_max_age_s}s; re-fetch before negotiating {task.skill_id!r}"
        )

    # Invariant 2: the skill must be asserted by the *current* card, not the
    # cached one. Lenient server acceptance of an unadvertised skill ID is
    # not proof of capability match.
    if task.skill_id not in live_card.skills:
        raise StaleAgentCardError(
            f"skill {task.skill_id!r} absent from live card "
            f"(has: {sorted(live_card.skills)}); cached card is stale"
        )

    # Invariant 3: if the task depends on push, the live card must still
    # advertise push AND the chosen scheme must be in the live scheme set.
    if task.push_scheme is not None:
        if not live_card.push_supported:
            raise StaleAgentCardError(
                "task requires push but live card no longer advertises "
                "capabilities.pushNotifications"
            )
        if task.push_scheme not in live_card.push_auth_schemes:
            raise StaleAgentCardError(
                f"push scheme {task.push_scheme!r} not in live card schemes "
                f"{sorted(live_card.push_auth_schemes)}; registration would "
                f"return 200 but delivery would fail asynchronously"
            )

    # Bind the negotiation to the live card, not the cached one.
    task.card = live_card


def reconcile_terminal(
    task: TaskNegotiation,
    now: float,
    t_notify_s: float = 30.0,
) -> None:
    # Invariant 4: a terminal server state with no confirmed push delivery
    # must be reconciled via tasks/get before the delegation turn closes.
    if task.terminal_server_state is None:
        return
    if task.notification_confirmed or task.reconciled:
        return
    if task.registered_at is None:
        raise NotificationUnreconciledError(
            f"task reached {task.terminal_server_state!r} with no push "
            f"registration and no reconciliation"
        )
    if now - task.registered_at > t_notify_s:
        raise NotificationUnreconciledError(
            f"task {task.terminal_server_state!r} for {t_notify_s}s with no "
            f"push confirmation and no tasks/get reconciliation; "
            f"delegation turn would exhaust token budget"
        )
