# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-binding-when-a2a-v1-0-task-delegation-crosses-a-vendor-boundary-mid-lifecycle.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-binding-when-a2a-v1-0-task-delegation-crosses-a-vendor-boundary-mid-lifecycle.warrant.json
# Markdown SHA-256:   9e14f4ffb7ea83c2de5dfcfe1c00b99e51146b43bc4245897ddd9159afaa1f8d
# Code AST SHA-256:   6575ab0f4e6721816aa7e679a2ae35abd75500bd9ee1987ae5d4fd96dc5f7cff
# Verified Classes:   CardDriftError, AgentCard, TaskBinding
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CardDriftError(RuntimeError):
    """Raised when a task continuation is validated against a card that no
    longer matches the card that authorized the task's creation."""


@dataclass
class AgentCard:
    version_hash: str
    streaming: bool
    auth_audience: str
    skill_ids: set[str]


@dataclass
class TaskBinding:
    task_id: str
    card_hash_at_creation: str
    skill_id: str
    continuation_token: str
    state: str = "working"
    card_drift: Optional[str] = None
    history: list[str] = field(default_factory=list)


def card_hash(card: AgentCard) -> str:
    payload = f"{card.streaming}|{card.auth_audience}|{','.join(sorted(card.skill_ids))}"
    return hashlib.sha256(payload.encode()).hexdigest()[:16]


def validate_continuation(
    binding: TaskBinding,
    current_card: AgentCard,
    presented_audience: str,
    requested_skill: Optional[str] = None,
) -> None:
    """Called before every lifecycle continuation (tasks/get, sendSubscribe,
    push registration, skill-targeted send). Raises CardDriftError on any
    contract divergence; never silently retries."""
    current_hash = card_hash(current_card)

    if current_hash != binding.card_hash_at_creation:
        binding.card_drift = (
            f"card changed: {binding.card_hash_at_creation} -> {current_hash}"
        )
        binding.history.append(f"drift-detected:{current_hash}")
        raise CardDriftError(
            f"task {binding.task_id} bound to card {binding.card_hash_at_creation}, "
            f"server now serves {current_hash}; continuation invalidated"
        )

    if presented_audience != current_card.auth_audience:
        binding.card_drift = f"audience mismatch: {presented_audience}"
        binding.history.append("auth-audience-mismatch")
        raise CardDriftError(
            f"task {binding.task_id}: presented audience {presented_audience!r} "
            f"does not match card audience {current_card.auth_audience!r}"
        )

    if requested_skill is not None and requested_skill not in current_card.skill_ids:
        binding.card_drift = f"skill {requested_skill!r} absent from current card"
        binding.history.append(f"skill-drift:{requested_skill}")
        raise CardDriftError(
            f"task {binding.task_id}: skill {requested_skill!r} not in current card; "
            f"vendor renumbering suspected, refusing fallback re-delegation"
        )


def on_stream_closed_without_terminal_state(
    binding: TaskBinding, current_card: AgentCard
) -> None:
    """A graceful stream close with no terminal task state is a card-drift
    signature, not a completion. Must not be marked completed."""
    if not current_card.streaming:
        binding.card_drift = "streaming disabled mid-lifecycle"
        binding.history.append("streaming-downgrade")
        raise CardDriftError(
            f"task {binding.task_id}: stream closed while card advertises "
            f"streaming=false; task state is indeterminate, not completed"
        )
    if binding.state not in ("completed", "failed", "canceled"):
        binding.card_drift = f"stream closed in state {binding.state}"
        binding.history.append("premature-stream-close")
        raise CardDriftError(
            f"task {binding.task_id}: stream closed in non-terminal state "
            f"{binding.state!r}; treating as card-drift, not completion"
        )
