# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-remote-agent-card-as-invalid-mid-task-rather-than-at-discovery-signature-scope-drift-across-a2a-v1-0-task-lifecycle-tran.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-remote-agent-card-as-invalid-mid-task-rather-than-at-discovery-signature-scope-drift-across-a2a-v1-0-task-lifecycle-tran.warrant.json
# Markdown SHA-256:   2613334ed9af258eef43bcd67a668c3e5088235627c071fb02bdcfa19c9bbcf4
# Code AST SHA-256:   029f4177c26e1ca0d27ff67e5c1b876c2f6bdee9b63b3e9ad289390420c3a351
# Verified Classes:   CardScopeDriftError, AgentCard, TaskBinding
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CardScopeDriftError(RuntimeError):
    """Raised when a task transition would proceed under a card whose scope
    no longer covers the capabilities or security schemes the task exercises."""


@dataclass(frozen=True)
class AgentCard:
    kid: str
    card_hash: str
    capabilities: FrozenSet[str]
    security_schemes: FrozenSet[str]
    signed_by: str  # kid of the signing key


@dataclass
class TaskBinding:
    task_id: str
    discovery_card: AgentCard
    exercised_capabilities: set = field(default_factory=set)
    presented_schemes: set = field(default_factory=set)
    artifact_tags: list = field(default_factory=list)


def rebind_at_transition(
    binding: TaskBinding,
    current_card: AgentCard,
    key_transition_valid: bool,
) -> TaskBinding:
    """Called at every input-required / auth-required / resume boundary.
    Fails closed if the current card's scope no longer covers what the task
    has exercised or is about to present."""

    if current_card.kid != binding.discovery_card.kid and not key_transition_valid:
        raise CardScopeDriftError(
            f"task {binding.task_id}: signing key rotated "
            f"{binding.discovery_card.kid} -> {current_card.kid} with no "
            f"validatable transition chain; cannot attribute prior artifacts"
        )

    lost = binding.exercised_capabilities - current_card.capabilities
    if lost:
        raise CardScopeDriftError(
            f"task {binding.task_id}: exercised capabilities {sorted(lost)} "
            f"withdrawn by card {current_card.card_hash}; task cannot continue "
            f"under narrowed scope — transition to failed, do not downgrade"
        )

    missing_schemes = binding.presented_schemes - current_card.security_schemes
    if missing_schemes:
        raise CardScopeDriftError(
            f"task {binding.task_id}: presented schemes {sorted(missing_schemes)} "
            f"absent from card {current_card.card_hash}; next message will be "
            f"rejected — transition to auth-required, do not retry stale token"
        )

    binding.discovery_card = current_card
    return binding


def record_artifact(binding: TaskBinding, artifact_mime: str) -> None:
    """Tag each artifact with the card in force at its producing transition."""
    binding.artifact_tags.append(
        {"mime": artifact_mime, "kid": binding.discovery_card.kid,
         "card_hash": binding.discovery_card.card_hash}
    )
