# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a2a-v1-0-task-lifecycle-against-a-peer-whose-agent-card-advertises-capabilities-the-runtime-silently-downgrad.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a2a-v1-0-task-lifecycle-against-a-peer-whose-agent-card-advertises-capabilities-the-runtime-silently-downgrad.warrant.json
# Markdown SHA-256:   77e1553b2a067e4ada4a36203155661d848a3945dd5e4ad871383d8714f866bd
# Code AST SHA-256:   a6b4d561bd6d6b7c19e8cfea46d3a629715daf8a5e6f16a9ec53fcaf2fe30c8a
# Verified Classes:   CapabilityDowngradeError, AgentCard, RequestedCapabilities, TerminalTask
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CapabilityDowngradeError(RuntimeError):
    """Raised when a peer returns a terminal task state that omits a capability
    the caller requested and the peer's Agent Card advertised."""


@dataclass
class AgentCard:
    streaming: bool
    artifacts: bool
    push_notifications: bool
    served_from: str  # control-plane identity


@dataclass
class RequestedCapabilities:
    streaming: bool = False
    artifacts: bool = False
    push_notifications: bool = False


@dataclass
class TerminalTask:
    state: Literal["completed", "failed", "canceled"]
    artifacts: list = field(default_factory=list)
    emitted_stream_frames: int = 0
    echoed_capabilities: RequestedCapabilities | None = None


def validate_terminal_task(
    card: AgentCard,
    requested: RequestedCapabilities,
    terminal: TerminalTask,
    worker_identity: str,
) -> None:
    """Enforce the capability-echo invariant before committing downstream state.

    If the card was served from a different process than the worker that
    executed the task, the card is advisory only and the caller must verify
    each requested capability against the terminal event.
    """
    card_is_authoritative = card.served_from == worker_identity

    if terminal.state != "completed":
        return  # non-terminal-success states are handled by the caller's retry path

    # Artifact invariant: requested artifacts but none emitted.
    if requested.artifacts and not terminal.artifacts:
        if not card_is_authoritative:
            raise CapabilityDowngradeError(
                f"peer {card.served_from} advertised artifacts=true but worker "
                f"{worker_identity} returned completed with empty artifacts; "
                f"card is non-authoritative for this worker"
            )
        raise CapabilityDowngradeError(
            "authoritative card advertised artifacts but terminal task omitted them"
        )

    # Streaming invariant: requested streaming but zero frames observed.
    if requested.streaming and terminal.emitted_stream_frames == 0:
        raise CapabilityDowngradeError(
            "streaming requested, zero SSE frames observed before terminal state"
        )

    # Push-notification invariant: only enforceable if the peer echoes it.
    if requested.push_notifications:
        if terminal.echoed_capabilities is None:
            raise CapabilityDowngradeError(
                "pushNotifications requested but peer did not echo capability set; "
                "cannot confirm webhook registration survived negotiation"
            )
        if not terminal.echoed_capabilities.push_notifications:
            raise CapabilityDowngradeError(
                "peer silently downgraded pushNotifications during negotiation"
            )
