# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-task-state-transition-as-authoritative-when-the-remote-agent-card-s-declared-capabilities-div.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-task-state-transition-as-authoritative-when-the-remote-agent-card-s-declared-capabilities-div.warrant.json
# Markdown SHA-256:   9d30d9f5b69fd701e27e5ebebaeb1b7c4a409bbbc70c85d1375b66bf4eb7b65d
# Code AST SHA-256:   e59e371b65712ed4423de9ae4ec744f52a8a2fc4884d9fabac6b2953cd05146c
# Verified Classes:   CardRuntimeDivergenceError, PeerCapabilityCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

SPEC_STATES = {"submitted", "working", "input-required", "completed", "failed", "canceled"}
TERMINAL = {"completed", "failed", "canceled"}


class CardRuntimeDivergenceError(RuntimeError):
    """Raised when a task event cannot be reconciled with the peer's card or the spec FSM."""


@dataclass
class PeerCapabilityCache:
    peer_id: str
    card_states_advertised: set[str]
    observed_states: set[str] = field(default_factory=set)
    history_trusted: bool = True

    def record(self, state: str) -> None:
        self.observed_states.add(state)


def reconcile_event(cache: PeerCapabilityCache, event_state: str,
                    has_history: bool, task_id: str) -> Literal["accept", "accept_divergent", "reject"]:
    # Spec enumeration is the only binding guard. Card fields are hints.
    if event_state not in SPEC_STATES:
        raise CardRuntimeDivergenceError(
            f"task {task_id}: peer {cache.peer_id} emitted non-spec state {event_state!r}"
        )

    divergent = event_state not in cache.card_states_advertised
    cache.record(event_state)

    # input-required is always reachable; never gate on defaultInputModes.
    if event_state == "input-required":
        return "accept_divergent" if divergent else "accept"

    if event_state in TERMINAL and not has_history and cache.history_trusted:
        # Card said stateTransitionHistory:true but terminal history empty -> downgrade trust.
        cache.history_trusted = False
        return "accept_divergent"

    return "accept_divergent" if divergent else "accept"
