# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-task-lifecycle-against-a-stale-a2a-agent-card-the-taskstate-skew-boundary-in-cross-vendor-v1-0-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-task-lifecycle-against-a-stale-a2a-agent-card-the-taskstate-skew-boundary-in-cross-vendor-v1-0-handoffs.warrant.json
# Markdown SHA-256:   55858b0ff6543982f6641ea6953662a5053977bdd0ea1f35715c452606eaae58
# Code AST SHA-256:   47fa898785d29fdbf3f45e475a3d8a795a38d1fbfbe706a3ee1aa5c1344f5283
# Verified Classes:   StaleCardError, ZombieTaskError, TaskState, AgentCard, CallerSession
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class StaleCardError(RuntimeError):
    """Raised when a task continuation is issued under a card generation
    that no longer matches the callee's current lifecycle contract."""


class ZombieTaskError(RuntimeError):
    """Raised when a task reaches a state the caller's FSM cannot represent
    and no re-negotiation path exists."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


@dataclass(frozen=True)
class AgentCard:
    version: str
    etag: str
    declared_states: frozenset
    push_notifications: bool
    default_input_modes: frozenset
    default_output_modes: frozenset

    @classmethod
    def from_wire(cls, wire: dict) -> "AgentCard":
        blob = repr(sorted(wire.items())).encode()
        return cls(
            version=wire["version"],
            etag=hashlib.sha256(blob).hexdigest()[:16],
            declared_states=frozenset(wire.get("declaredStates", [])),
            push_notifications=bool(wire["capabilities"].get("pushNotifications", False)),
            default_input_modes=frozenset(wire["defaultInputModes"]),
            default_output_modes=frozenset(wire["defaultOutputModes"]),
        )


@dataclass
class CallerSession:
    cached_card: AgentCard
    task_id: Optional[str] = None
    last_known_state: Optional[TaskState] = None
    continuation_etag: Optional[str] = field(default=None)

    def submit(self, live_card: AgentCard, payload_modes: frozenset) -> None:
        # Guardrail 1: revalidate card generation at submission.
        if live_card.etag != self.cached_card.etag:
            raise StaleCardError(
                f"card mutated between fetch and submit: "
                f"cached={self.cached_card.etag} live={live_card.etag}"
            )
        if not payload_modes <= live_card.default_input_modes:
            raise StaleCardError(
                f"payload modes {payload_modes} not in live card input modes"
            )
        self.continuation_etag = live_card.etag

    def on_state_event(self, live_card: AgentCard, new_state: TaskState) -> None:
        # Guardrail 2: any state the cached FSM cannot represent is a hard
        # negotiation failure, never a silent drop.
        if live_card.etag != self.continuation_etag:
            raise StaleCardError(
                f"continuation under stale card: "
                f"session={self.continuation_etag} live={live_card.etag}"
            )
        if new_state.value not in live_card.declared_states:
            raise ZombieTaskError(
                f"callee emitted state {new_state.value!r} not in its own "
                f"declared lifecycle {sorted(live_card.declared_states)}; "
                f"task {self.task_id} is unaddressable"
            )
        if new_state is TaskState.INPUT_REQUIRED and not live_card.push_notifications:
            # No push channel to deliver the continuation prompt; the caller
            # must poll or the task becomes a zombie.
            raise ZombieTaskError(
                f"input-required reached with pushNotifications=false; "
                f"no delivery path for continuation on task {self.task_id}"
            )
        self.last_known_state = new_state


def drive_task(session: CallerSession, live_card: AgentCard, events: list) -> TaskState:
    for ev in events:
        session.on_state_event(live_card, TaskState(ev))
    if session.last_known_state not in (TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED):
        raise ZombieTaskError(
            f"task {session.task_id} ended in non-terminal state "
            f"{session.last_known_state}; caller FSM cannot close it"
        )
    return session.last_known_state
