# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a2a-v1-0-contract-conformance-as-a-stateful-per-peer-invariant-rather-than-a-one-shot-handshake-and-what.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a2a-v1-0-contract-conformance-as-a-stateful-per-peer-invariant-rather-than-a-one-shot-handshake-and-what.warrant.json
# Markdown SHA-256:   9c1feeea2eafe2859ff79ec8b6df6923d7ba81d6205d7b18730194e5f60d18fe
# Code AST SHA-256:   7e873f30e1a1e186a0a9f7892a9cddcb9c012794fc6bd22824407378bfed3fa7
# Verified Classes:   A2AConformanceError, AgentCardView, TaskBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class A2AConformanceError(RuntimeError):
    """Raised when a per-exchange-conformant peer violates the stateful
    (client, peer, task) conformance invariant."""
    pass


@dataclass
class AgentCardView:
    peer_id: str
    capabilities: dict
    fetched_at: float
    freshness_window: float = 1800.0  # seconds

    def is_stale(self, now: float) -> bool:
        return (now - self.fetched_at) > self.freshness_window


@dataclass
class TaskBinding:
    task_id: str
    context_id: str
    transport: str  # "send" | "stream"
    superseded_contexts: set = field(default_factory=set)


def guard_exchange(
    card: AgentCardView,
    binding: TaskBinding,
    live_card: Optional[AgentCardView],
    incoming_context_id: str,
    now: float,
) -> TaskBinding:
    # Invariant 1: stale card must be re-verified before state-bearing exchange.
    if card.is_stale(now):
        if live_card is None:
            raise A2AConformanceError(
                f"peer {card.peer_id}: card stale at {now:.0f}, "
                f"no live re-fetch supplied; refusing state-bearing exchange"
            )
        # Capability rollback: demote transport, do not fail the task.
        if card.capabilities.get("streaming") and not live_card.capabilities.get("streaming"):
            if binding.transport == "stream":
                binding.transport = "send"

    # Invariant 2: contextId is server-mutable per taskId.
    if incoming_context_id != binding.context_id:
        binding.superseded_contexts.add(binding.context_id)
        binding.context_id = incoming_context_id

    # Invariant 3: never re-issue against a superseded scope (duplicate-task trigger).
    if incoming_context_id in binding.superseded_contexts:
        raise A2AConformanceError(
            f"task {binding.task_id}: input targets superseded context "
            f"{incoming_context_id}; would fork task on peer {card.peer_id}"
        )

    return binding
