# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-a2a-agent-card-s-declared-taskstate-vocabulary-against-the-remote-task-s-actual-state-machine-before-resuming-a-p.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-a2a-agent-card-s-declared-taskstate-vocabulary-against-the-remote-task-s-actual-state-machine-before-resuming-a-p.warrant.json
# Markdown SHA-256:   bfb582857f9c64bc12c52bcf94afa9086fc6eefd8965f4d32a94dca7ad3203b8
# Code AST SHA-256:   7e1527557cc5fe92997ece70e24cd692e66429ee820d036fd552bfd8cebf3368
# Verified Classes:   TaskResumeViolation, CardBinding, TaskHandle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class TaskResumeViolation(RuntimeError):
    """Raised when a persisted A2A task handle is resumed under a card
    version whose taskStates vocabulary is not a superset of the persisted one."""


@dataclass(frozen=True)
class CardBinding:
    version: str
    etag: str
    task_states: FrozenSet[str]


@dataclass(frozen=True)
class TaskHandle:
    task_id: str
    context_id: str
    last_observed_state: str
    card: CardBinding


def reconcile_before_resume(
    handle: TaskHandle,
    current_card: CardBinding,
    remote_actual_state: Optional[str],
) -> str:
    """Return the authoritative state to resume from, or raise if reconciliation
    cannot be completed safely. Never coerces an unknown literal."""
    persisted = handle.card.task_states
    current = current_card.task_states

    if current_card.version == handle.card.version and current_card.etag == handle.card.etag:
        return handle.last_observed_state

    dropped = persisted - current
    added = current - persisted

    if dropped:
        # Rename or removal: the persisted reducer is stale. The remote's
        # actual state is the only authority; a guess here forks the task.
        if remote_actual_state is None:
            raise TaskResumeViolation(
                f"card {handle.card.version}->{current_card.version} dropped "
                f"states {sorted(dropped)}; tasks/get required before resume"
            )
        if remote_actual_state not in current:
            raise TaskResumeViolation(
                f"remote state {remote_actual_state!r} not in current vocabulary "
                f"{sorted(current)}; escalate to caller, do not map"
            )
        return remote_actual_state

    if added and handle.last_observed_state not in current:
        raise TaskResumeViolation(
            f"persisted state {handle.last_observed_state!r} absent from additive "
            f"card {current_card.version}; reducer rebuild required"
        )

    return handle.last_observed_state
