# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-negotiation-deadlock-when-an-a2a-v1-0-agent-card-advertises-a-taskstate-transition-that-the-remote-executor-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-negotiation-deadlock-when-an-a2a-v1-0-agent-card-advertises-a-taskstate-transition-that-the-remote-executor-s.warrant.json
# Markdown SHA-256:   2df6cb03ec951affabb5843c9360459ba754f7d8738a505d4ae25fa35a1efcb6
# Code AST SHA-256:   0f06eccdea66a1b400aa2895098466556ba2ac1827863213f80d16d1d0dda51a
# Verified Classes:   TaskState, CapabilityNegotiationFault, TaskSnapshot, ClientTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


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


TERMINAL = {TaskState.COMPLETED, TaskState.CANCELED, TaskState.FAILED, TaskState.REJECTED}

# Conservative superset: every edge any conformant A2A v1.0 executor *may* take.
# Deliberately wider than the spec's illustrative diagram, because the spec
# does not constrain the executor's internal transition topology.
SUPERSET_EDGES: dict[TaskState, set[TaskState]] = {
    TaskState.SUBMITTED: {TaskState.WORKING, TaskState.REJECTED, TaskState.AUTH_REQUIRED},
    TaskState.WORKING: {
        TaskState.WORKING,
        TaskState.INPUT_REQUIRED,
        TaskState.COMPLETED,
        TaskState.FAILED,
        TaskState.CANCELED,
    },
    TaskState.INPUT_REQUIRED: {
        TaskState.WORKING,       # executor self-exit (the observed divergence)
        TaskState.INPUT_REQUIRED,
        TaskState.FAILED,
        TaskState.CANCELED,
        TaskState.COMPLETED,
    },
    TaskState.AUTH_REQUIRED: {TaskState.WORKING, TaskState.REJECTED, TaskState.FAILED},
}


class CapabilityNegotiationFault(RuntimeError):
    """Raised when an observed task state is unreachable from the client's
    modeled state, or when a state's semantics cannot be disambiguated
    across the trust boundary."""


@dataclass
class TaskSnapshot:
    state: TaskState
    status_message: Optional[str] = None
    revision: int = 0


@dataclass
class ClientTask:
    task_id: str
    peer_card_hash: str
    current: TaskState = TaskState.SUBMITTED
    faults: list[str] = field(default_factory=list)


def reconcile_transition(task: ClientTask, snap: TaskSnapshot) -> ClientTask:
    """Validate an observed snapshot against the conservative superset graph.

    Invariant: an unmodeled edge is a *negotiation fault*, never a protocol
    error and never a silent drop. The task ID is retained and a terminal
    snapshot is forced before release.
    """
    if task.current in TERMINAL:
        if snap.state != task.current:
            raise CapabilityNegotiationFault(
                f"task {task.task_id}: post-terminal transition "
                f"{task.current.value} -> {snap.state.value}"
            )
        return task

    allowed = SUPERSET_EDGES.get(task.current, set())
    if snap.state not in allowed:
        # Do NOT drop. Record the divergence keyed by the peer card hash so
        # the same peer is not re-trusted with this edge on future tasks.
        task.faults.append(
            f"unmodeled edge {task.current.value} -> {snap.state.value} "
            f"peer={task.peer_card_hash}"
        )
        raise CapabilityNegotiationFault(
            f"task {task.task_id}: transition {task.current.value} -> "
            f"{snap.state.value} not in superset graph for peer "
            f"{task.peer_card_hash}"
        )

    # Guard against the specific observed failure: input-required with no
    # status.message is an executor-internal pause, not a client action item.
    if snap.state is TaskState.INPUT_REQUIRED and not (snap.status_message or "").strip():
        task.faults.append(
            f"message-less input-required on task {task.task_id}; "
            f"treating as transient, continuing poll"
        )
        return task  # do not halt polling; do not require client action

    task.current = snap.state
    return task


def force_terminal_snapshot(task: ClientTask, fetch) -> TaskSnapshot:
    """On fault, force a terminal read so the task ID is not orphaned."""
    last = fetch(task.task_id)
    if last.state not in TERMINAL:
        # Best effort: request cancellation, then re-read once.
        try:
            fetch(task.task_id, cancel=True)
        finally:
            last = fetch(task.task_id)
    if last.state not in TERMINAL:
        raise CapabilityNegotiationFault(
            f"task {task.task_id}: could not reach terminal state; "
            f"peer={task.peer_card_hash} leaked a non-terminal task"
        )
    return last


def card_hash(card: dict) -> str:
    return hashlib.sha256(
        repr(sorted(card.items())).encode("utf-8")
    ).hexdigest()[:16]
