# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-agent-card-capabilities-streaming-true-at-discovery-time-yet-deadlock-at-the-first-tasks-send-because-the-card-s.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-agent-card-capabilities-streaming-true-at-discovery-time-yet-deadlock-at-the-first-tasks-send-because-the-card-s.warrant.json
# Markdown SHA-256:   677153378912adad97e9d79d72a6564abb17433493c28eedfef67b0b01cfd5f7
# Code AST SHA-256:   13ea1ae74d2c8eb05b656179294dc4f740d57efae64591098ae98ed3e9cfa4af
# Verified Classes:   StaleAgentCardDeadlock, AgentCard, TaskEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleAgentCardDeadlock(RuntimeError):
    """Raised when a task's artifact stream is pinned because the client's
    cached Agent Card modes no longer match the server's in-force modes."""
    pass


@dataclass
class AgentCard:
    version: str
    default_output_modes: list[str]
    capabilities_streaming: bool
    etag: str


@dataclass
class TaskEnvelope:
    task_id: str
    accepted_output_modes: list[str]
    card_version_used: str
    created_at: float = field(default_factory=time.time)


def negotiate_task(
    client_card: AgentCard,
    server_card: AgentCard,
    task: TaskEnvelope,
    frame_timeout_s: float = 5.0,
) -> None:
    """Validate that the card used to negotiate matches the in-force card.

    Enforces the invariant: the card used to negotiate a task equals the
    card in force when the task's artifacts are produced. If the client's
    cached card version differs from the server's in-force version, or if
    the accepted output modes do not intersect the server's default modes,
    raise StaleAgentCardDeadlock *before* the stream is opened — converting
    a silent deadlock into a loud, recoverable error.
    """
    if client_card.version != server_card.version:
        raise StaleAgentCardDeadlock(
            f"card version skew: client negotiated with {client_card.version!r}, "
            f"server in force is {server_card.version!r}; "
            f"re-fetch card (etag={server_card.etag}) and retry"
        )

    if task.card_version_used != server_card.version:
        raise StaleAgentCardDeadlock(
            f"task {task.task_id!r} was created against card "
            f"{task.card_version_used!r} but server is at {server_card.version!r}"
        )

    if not server_card.capabilities_streaming:
        raise StaleAgentCardDeadlock(
            f"task {task.task_id!r} requested streaming but server card "
            f"{server_card.version!r} does not advertise capabilities.streaming"
        )

    intersection = set(task.accepted_output_modes) & set(server_card.default_output_modes)
    if not intersection:
        raise StaleAgentCardDeadlock(
            f"task {task.task_id!r} accepted modes {task.accepted_output_modes!r} "
            f"do not intersect server default modes "
            f"{server_card.default_output_modes!r}; stream would pin indefinitely"
        )

    age = time.time() - task.created_at
    if age > frame_timeout_s and not intersection:
        raise StaleAgentCardDeadlock(
            f"task {task.task_id!r} has been in 'working' for {age:.1f}s "
            f"with no mode-compatible frame; aborting to prevent deadlock"
        )


# Example: the exact drift that caused the three-way stall.
client_cached = AgentCard(
    version="1.0.0",
    default_output_modes=["text/plain", "application/json"],
    capabilities_streaming=True,
    etag="abc123",
)
server_in_force = AgentCard(
    version="1.1.0",
    default_output_modes=["application/vnd.a2a.task+json;v=2"],
    capabilities_streaming=True,
    etag="def456",
)
task = TaskEnvelope(
    task_id="t-9001",
    accepted_output_modes=["application/json"],
    card_version_used="1.0.0",
)

try:
    negotiate_task(client_cached, server_in_force, task)
except StaleAgentCardDeadlock as e:
    # Correct handling: re-fetch card, update accepted_output_modes, retry once.
    # Do NOT retry with the stale card — that re-enters the deadlock.
    print(f"recovering: {e}")
