# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-a2a-task-whose-agent-card-was-discovered-through-a-stale-cross-org-cache-rather-than-re-fetc.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-a2a-task-whose-agent-card-was-discovered-through-a-stale-cross-org-cache-rather-than-re-fetc.warrant.json
# Markdown SHA-256:   bedc11975ae7325ffffb31807538886ac41fc3b58ab930eae87e0ef0524b17b6
# Code AST SHA-256:   4fb437ec30e7398d47575fb70ae871b1d567557a4e76c927b441ee01715bf8b1
# Verified Classes:   AgentCardSkewError, AgentCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AgentCardSkewError(RuntimeError):
    """Raised when a delegated task's negotiated AgentCard does not match
    the origin's current card version at handshake time."""


@dataclass(frozen=True)
class AgentCard:
    agent_id: str
    version: str          # e.g. "v4" or a content hash
    etag: str
    url: str
    input_modes: tuple


def negotiate_delegated_task(
    cached_card: AgentCard,
    origin_fetch,               # callable -> AgentCard | None (None = unreachable)
    task_is_stateful: bool,
    verifier_has_independent_oracle: bool,
) -> AgentCard:
    """Return the card to negotiate under, or raise if skew is unprovable
    and the blast radius is unacceptable."""

    if not task_is_stateful or verifier_has_independent_oracle:
        # Blast radius is bounded: a stale card yields a rejected envelope
        # or an output the independent oracle will catch.
        return cached_card

    origin_card = origin_fetch()

    if origin_card is None:
        # Stateful task + unreachable origin = unprovable skew window.
        # Do NOT fall back to the cached card.
        raise AgentCardSkewError(
            f"origin unreachable for {cached_card.agent_id}; cannot prove "
            f"cached card {cached_card.version} matches live executor"
        )

    if origin_card.etag != cached_card.etag or origin_card.version != cached_card.version:
        raise AgentCardSkewError(
            f"card-executor skew for {cached_card.agent_id}: cached "
            f"{cached_card.version}/{cached_card.etag} != origin "
            f"{origin_card.version}/{origin_card.etag}; refusing stateful handshake"
        )

    return origin_card
