# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transitions-are-a-superset-of-the-a2a-v1-0-canonical-state-machine.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transitions-are-a-superset-of-the-a2a-v1-0-canonical-state-machine.warrant.json
# Markdown SHA-256:   7380c3d077e97688684921ed2a474f22868dfd4ae692c19815740deaa002a7e1
# Code AST SHA-256:   d3fd1821822b015942ff00c1b4a5fd6d93aa2c8ce693a57a94055df241938d6f
# Verified Classes:   AgentCardConformanceError, TransitionVerdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum

CANONICAL_STATES = {"submitted", "working", "input-required", "completed", "failed", "canceled"}
TERMINAL = {"completed", "failed", "canceled"}
CANONICAL_EDGES = {
    ("submitted", "working"),
    ("working", "input-required"),
    ("working", "completed"),
    ("working", "failed"),
    ("working", "canceled"),
    ("input-required", "working"),
}


class AgentCardConformanceError(RuntimeError):
    """Raised when a peer Agent Card's task lifecycle is not acceptable."""


@dataclass
class TransitionVerdict:
    accept: bool
    cancelable: bool
    reentry_edges: list
    missing_edges: list


def validate_task_lifecycle(
    declared: list[tuple[str, str]],
    sink_is_idempotent: bool,
    peer_mints_fresh_task_on_retry: bool,
) -> TransitionVerdict:
    declared_set = set(map(tuple, declared))

    for src, dst in declared_set:
        if src not in CANONICAL_STATES or dst not in CANONICAL_STATES:
            raise AgentCardConformanceError(
                f"unknown state in transition {src}->{dst}; not an A2A v1.0 enum member"
            )

    reentry = sorted(
        (s, d) for (s, d) in declared_set if s in TERMINAL and d not in TERMINAL
    )
    missing = sorted(CANONICAL_EDGES - declared_set)

    if reentry and not peer_mints_fresh_task_on_retry and not sink_is_idempotent:
        raise AgentCardConformanceError(
            "peer declares re-entry from terminal states "
            f"{reentry} but does not mint a fresh taskId and the artifact sink "
            "is not idempotent; accepting this Card guarantees silent state "
            "divergence on post-terminal updates"
        )

    cancelable = ("working", "canceled") in declared_set
    return TransitionVerdict(
        accept=True,
        cancelable=cancelable,
        reentry_edges=reentry,
        missing_edges=missing,
    )


def discover_peer(card: dict, sink_is_idempotent: bool) -> TransitionVerdict:
    declared = card.get("capabilities", {}).get("taskLifecycle", {}).get("transitions", [])
    peer_mints = bool(card.get("capabilities", {}).get("taskLifecycle", {}).get("freshTaskOnRetry", False))
    return validate_task_lifecycle(declared, sink_is_idempotent, peer_mints)
