# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-peer-s-declared-a2a-task-state-vocabulary-against-the-terminal-states-it-actually-emits-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-peer-s-declared-a2a-task-state-vocabulary-against-the-terminal-states-it-actually-emits-mid-handoff.warrant.json
# Markdown SHA-256:   9371d07ee49d415b72c3ba88a4749e63e3f1975cc7e616a8a72cf06c59d21080
# Code AST SHA-256:   ee0e053e7a0310a12ba2a5fdddcb32c518fe6d3c638d2b00dfc0c7c5b739920b
# Verified Classes:   A2ATerminalDivergenceError, RemoteTaskView, LocalTaskHandle
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

CANONICAL_STATES = {"submitted", "working", "input-required", "completed", "failed", "canceled"}
TERMINAL_STATES = {"completed", "failed", "canceled"}


class A2ATerminalDivergenceError(RuntimeError):
    """Raised when a caller would emit a local terminal that the remote state does not support."""
    pass


@dataclass
class RemoteTaskView:
    state: str
    artifacts: list = field(default_factory=list)
    message: Optional[dict] = None
    resolvable: bool = True


@dataclass
class LocalTaskHandle:
    remote_task_id: str
    peer_endpoint: str
    local_state: str = "submitted"
    last_remote_state: Optional[str] = None
    artifact_signature: Optional[tuple] = None
    stable_reads: int = 0


def reconcile(handle: LocalTaskHandle, view: RemoteTaskView, poll_interval_s: float = 2.0) -> str:
    """
    Drive one reconciliation step. Returns the local state to persist.
    Never emits a local terminal on an unknown or payload-unstable remote state.
    """
    if not view.resolvable:
        # Transport gone: checkpoint, do not fail. Caller must reconcile later by task id.
        handle.local_state = "indeterminate"
        return handle.local_state

    handle.last_remote_state = view.state

    if view.state not in CANONICAL_STATES:
        # Vendor-extension state. Hold in the pen; do not map to failed.
        handle.local_state = "peer_undefined_state"
        return handle.local_state

    if view.state in TERMINAL_STATES:
        sig = tuple(sorted((a.get("name"), a.get("mimeType")) for a in view.artifacts))
        if sig == handle.artifact_signature:
            handle.stable_reads += 1
        else:
            handle.artifact_signature = sig
            handle.stable_reads = 0

        if view.state == "completed" and (not view.artifacts or handle.stable_reads < 1):
            # Terminal claim without stable payload: hold, re-poll.
            handle.local_state = "working"
            time.sleep(poll_interval_s)
            return handle.local_state

        if view.state == "failed" and not view.message:
            # Terminal claim without error detail: hold, re-poll.
            handle.local_state = "working"
            time.sleep(poll_interval_s)
            return handle.local_state

        handle.local_state = view.state
        return handle.local_state

    # Non-terminal canonical state.
    handle.local_state = view.state
    return handle.local_state


def assert_no_illegal_terminal(handle: LocalTaskHandle, proposed_local: str) -> None:
    if proposed_local in TERMINAL_STATES and handle.last_remote_state not in TERMINAL_STATES:
        raise A2ATerminalDivergenceError(
            f"local terminal {proposed_local!r} for remote task {handle.remote_task_id!r} "
            f"at {handle.peer_endpoint!r} while remote state is "
            f"{handle.last_remote_state!r}; hold and re-poll instead"
        )
