# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transitions-are-acyclic-but-non-covering-and-how-does-late-artifa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-agent-card-whose-declared-taskstate-transitions-are-acyclic-but-non-covering-and-how-does-late-artifa.warrant.json
# Markdown SHA-256:   dcef1c0ad37b68b922e4215222c5b699cf0cef1bbc05e98cd8f80521f6535840
# Code AST SHA-256:   980c78f81c96fb31ab0991a04617a5d1b2346a8e9a834247561355fb608807fb
# Verified Classes:   NonCoveringAgentCardError, AgentCard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping

TERMINAL = frozenset({"completed", "failed", "canceled"})


class NonCoveringAgentCardError(RuntimeError):
    """Raised when a peer Agent Card is acyclic but has no satisfiable
    path from a reachable state to a terminal state under the pinned
    acceptedOutputModes. This is a discovery-time rejection, not a
    runtime strand."""


@dataclass(frozen=True)
class AgentCard:
    card_hash: str
    transitions: Mapping[str, FrozenSet[str]]   # state -> declared successors
    skill_output_modes: FrozenSet[str]          # modes peer may emit
    input_required_modes: FrozenSet[str]        # modes peer requests on input-required


def _reachable(transitions: Mapping[str, FrozenSet[str]], start: str = "submitted") -> FrozenSet[str]:
    seen, frontier = set(), [start]
    while frontier:
        s = frontier.pop()
        if s in seen:
            continue
        seen.add(s)
        frontier.extend(transitions.get(s, frozenset()) - seen)
    return frozenset(seen)


def _has_satisfiable_exit(
    transitions: Mapping[str, FrozenSet[str]],
    card: AgentCard,
    state: str,
    accepted: FrozenSet[str],
    visited: FrozenSet[str] = frozenset(),
) -> bool:
    if state in TERMINAL:
        return True
    if state in visited:                      # cycle guard; cards are DAGs but be defensive
        return False
    # If this state forces artifact widening, the widening must be within `accepted`.
    if state == "input-required" and not card.input_required_modes.issubset(accepted):
        return False
    return any(
        _has_satisfiable_exit(transitions, card, nxt, accepted, visited | {state})
        for nxt in transitions.get(state, frozenset())
    )


def validate_card(card: AgentCard, accepted_output_modes: FrozenSet[str]) -> None:
    reachable = _reachable(card.transitions)
    for s in reachable:
        if s in TERMINAL:
            continue
        if not _has_satisfiable_exit(card.transitions, card, s, accepted_output_modes):
            raise NonCoveringAgentCardError(
                f"card {card.card_hash}: state {s!r} has no satisfiable path to a "
                f"terminal state under acceptedOutputModes={sorted(accepted_output_modes)}; "
                f"peer input-required modes={sorted(card.input_required_modes)}. "
                f"Rejecting at discovery to avoid working<->input-required strand."
            )


def send_task(card: AgentCard, accepted_output_modes: FrozenSet[str], payload: dict) -> dict:
    validate_card(card, accepted_output_modes)
    return {"taskId": payload["taskId"], "pinnedCardHash": card.card_hash,
            "acceptedOutputModes": sorted(accepted_output_modes)}


if __name__ == "__main__":
    bad = AgentCard(
        card_hash="sha256:deadbeef",
        transitions={
            "submitted": frozenset({"working"}),
            "working": frozenset({"input-required", "completed", "failed", "canceled"}),
            "input-required": frozenset({"working"}),   # <-- the hole: no terminal exit
        },
        skill_output_modes=frozenset({"application/json", "image/png"}),
        input_required_modes=frozenset({"image/png"}),
    )
    # Coordinator policy forbids image/png -> input-required is unsatisfiable.
    send_task(bad, frozenset({"application/json"}), {"taskId": "t-1"})
