# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-agent-card-is-silently-downgrading-task-lifecycle-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-agent-card-is-silently-downgrading-task-lifecycle-negotiation.warrant.json
# Markdown SHA-256:   e3d0638cdd77e06e62a9063bd1cac4b73957bebef9905c8015661a772b5ab44c
# Code AST SHA-256:   d0d2f109129a6537a67e8abae0bcf4df7ee821f5722618cd99aa1a1b6dd0aa00
# Verified Classes:   CardDriftError, UnsupportedTransitionError, AgentCard, TaskState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CardDriftError(RuntimeError):
    """Raised when a lifecycle transition is attempted against a card that no longer supports it."""
    pass


class UnsupportedTransitionError(RuntimeError):
    """Raised when the live card does not advertise the capability a transition depends on."""
    pass


@dataclass
class AgentCard:
    version: str
    state_transition_history: bool
    default_input_modes: list
    skill_input_modes: dict = field(default_factory=dict)


@dataclass
class TaskState:
    task_id: str
    state: str  # submitted|working|input-required|completed|failed|canceled
    card_at_accept: AgentCard
    continuation_attempts: int = 0


ABSORBING = {"completed", "failed", "canceled"}


def revalidate_before_transition(
    task: TaskState,
    live_card: AgentCard,
    required_mode: str,
    skill_id: str,
) -> None:
    """Gate every topology-changing transition. Must be called before any continuation."""
    if task.state in ABSORBING:
        raise UnsupportedTransitionError(
            f"task {task.task_id} is in absorbing state {task.state}; "
            f"continuation is invalid, not transient"
        )

    cached = task.card_at_accept
    if live_card.version != cached.version:
        # Version drift alone is sufficient cause to re-read capability blocks.
        if live_card.state_transition_history != cached.state_transition_history:
            if not live_card.state_transition_history:
                # Cannot use history emptiness as a liveness signal anymore.
                task.state = "working"  # force polling path
        if live_card.default_input_modes != cached.default_input_modes:
            if required_mode not in live_card.default_input_modes:
                raise CardDriftError(
                    f"card drift {cached.version}->{live_card.version}: "
                    f"required mode {required_mode!r} absent from live defaultInputModes"
                )

    skill_modes = live_card.skill_input_modes.get(skill_id)
    if skill_modes is not None and required_mode not in skill_modes:
        raise CardDriftError(
            f"skill {skill_id!r} no longer accepts {required_mode!r} "
            f"(live modes: {skill_modes})"
        )

    if not live_card.state_transition_history and task.continuation_attempts > 0:
        raise UnsupportedTransitionError(
            f"live card suppresses stateTransitionHistory; "
            f"resumption of {task.task_id} cannot be verified"
        )


def send_continuation(task: TaskState, live_card: AgentCard, mode: str, skill_id: str) -> None:
    revalidate_before_transition(task, live_card, mode, skill_id)
    task.continuation_attempts += 1
    # ... emit tasks/send continuation only after the gate passes
