# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-loss-when-an-a2a-v1-0-agent-card-is-parsed-by-a-peer-that-negotiates-against-a-stale-or-partial-view-of-the.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-loss-when-an-a2a-v1-0-agent-card-is-parsed-by-a-peer-that-negotiates-against-a-stale-or-partial-view-of-the.warrant.json
# Markdown SHA-256:   f482649625f7bf761756aa75296f7fc6d52a3fb46703d53d3bb1ee3c471b5bcf
# Code AST SHA-256:   26890ca3a962ec1b6451040ab5af68609298c269c2ba4b611ebd6948bec25ff4
# Verified Classes:   LifecycleConformanceError, TaskState, AgentCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class LifecycleConformanceError(RuntimeError):
    """Raised when a peer's reachable task states exceed the client's transition domain."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


# A2A v1.0 base state machine: every conformant remote may reach these.
BASE_REACHABLE: FrozenSet[TaskState] = frozenset({
    TaskState.SUBMITTED,
    TaskState.WORKING,
    TaskState.INPUT_REQUIRED,  # reachable regardless of stateTransitionHistory
    TaskState.COMPLETED,
    TaskState.FAILED,
    TaskState.CANCELED,
})


@dataclass(frozen=True)
class AgentCard:
    name: str
    streaming: bool = False
    push_notifications: bool = False
    state_transition_history: bool = False
    # Positive narrowing only: an explicit enumeration the client may trust.
    declared_terminal_states: FrozenSet[TaskState] = field(default_factory=frozenset)
    declared_supported_states: FrozenSet[TaskState] = field(default_factory=frozenset)


def remote_reachable_states(card: AgentCard) -> FrozenSet[TaskState]:
    """Derive S_remote. Absent flags do NOT narrow the base machine."""
    reachable = set(BASE_REACHABLE)
    if card.declared_supported_states:
        # Only an explicit, positive enumeration narrows the set.
        reachable &= set(card.declared_supported_states)
    return frozenset(reachable)


def assert_lifecycle_conformance(card: AgentCard, client_handlers: FrozenSet[TaskState]) -> None:
    """
    Gate card acceptance on lifecycle coverage.

    state_transition_history=False is a replay flag, not a reachability flag.
    It must never be used to shrink S_remote.
    """
    s_remote = remote_reachable_states(card)
    uncovered = s_remote - client_handlers
    if uncovered:
        # If the card gave no positive narrowing, we cannot trust uncovered == empty.
        if not card.declared_supported_states and not card.declared_terminal_states:
            raise LifecycleConformanceError(
                f"card '{card.name}' exposes states {sorted(s.value for s in uncovered)} "
                f"with no positive narrowing; client handlers cover only "
                f"{sorted(s.value for s in client_handlers)}. "
                f"state_transition_history={card.state_transition_history} does not license omission."
            )
        raise LifecycleConformanceError(
            f"card '{card.name}' declares supported states "
            f"{sorted(s.value for s in s_remote)} but client lacks handlers for "
            f"{sorted(s.value for s in uncovered)}; refuse or negotiate narrowing."
        )


def negotiate(card: AgentCard, client_handlers: FrozenSet[TaskState]) -> FrozenSet[TaskState]:
    """Return the negotiated state set, or raise before any remote compute is spent."""
    assert_lifecycle_conformance(card, client_handlers)
    return remote_reachable_states(card) & client_handlers


# --- Demonstration: the observed failure ---
if __name__ == "__main__":
    observed_card = AgentCard(
        name="vendor-summarizer",
        streaming=True,
        push_notifications=False,
        state_transition_history=False,  # read by the buggy client as "linear only"
        # no declared_supported_states -> base machine fully reachable
    )
    # Buggy client registered only a linear lifecycle.
    buggy_handlers = frozenset({TaskState.SUBMITTED, TaskState.WORKING,
                                TaskState.COMPLETED, TaskState.FAILED})
    try:
        negotiate(observed_card, buggy_handlers)
    except LifecycleConformanceError as exc:
        print(f"REFUSED before delegation: {exc}")
        # Correct remediation: register input-required, or negotiate narrowing.
        fixed_handlers = buggy_handlers | {TaskState.INPUT_REQUIRED}
        negotiated = negotiate(observed_card, fixed_handlers)
        print(f"accepted with negotiated states: {sorted(s.value for s in negotiated)}")
