# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-renegotiating-an-in-flight-a2a-task-into-an-incompatible-terminal-state.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-capability-drift-from-silently-renegotiating-an-in-flight-a2a-task-into-an-incompatible-terminal-state.warrant.json
# Markdown SHA-256:   95b12be00a6ecee257fbf66d9fe939ff4530799f5c9b6e8e1718dccfdb91d815
# Code AST SHA-256:   da2cc1ad6167fdb3c3a1f7cbbf6b4a1990b688f26e626a52e68336fc584fa034
# Verified Classes:   CapabilityDriftError, NegotiationTuple, InFlightTask
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when an in-flight A2A task's pinned negotiation tuple no longer
    matches the currently advertised Agent Card. This is terminal for the task;
    the client must cancel and re-negotiate rather than adapt silently."""


@dataclass
class NegotiationTuple:
    card_hash: str
    skill_id: str
    required_capabilities: frozenset

    @classmethod
    def capture(cls, card: dict, skill_id: str, required: frozenset) -> "NegotiationTuple":
        canon = json.dumps(card, sort_keys=True, separators=(",", ":")).encode()
        return cls(
            card_hash=hashlib.sha256(canon).hexdigest(),
            skill_id=skill_id,
            required_capabilities=required,
        )


@dataclass
class InFlightTask:
    task_id: str
    context_id: str
    pinned: NegotiationTuple
    state: str = "working"


def verify_task_against_current_card(
    task: InFlightTask,
    current_card: dict,
    current_skill_ids: set,
) -> None:
    """Called on every tasks/get and every stream event. Enforces the invariant:
    an in-flight task is bound to its negotiation-time tuple; any divergence in
    skill resolvability or required capabilities is terminal."""
    if task.state in ("completed", "failed", "canceled"):
        return

    if task.pinned.skill_id not in current_skill_ids:
        raise CapabilityDriftError(
            f"task {task.task_id} bound to skill {task.pinned.skill_id!r} "
            f"which is no longer advertised; current skills={sorted(current_skill_ids)}"
        )

    advertised = frozenset(
        k for k, v in current_card.get("capabilities", {}).items() if v is True
    )
    missing = task.pinned.required_capabilities - advertised
    if missing:
        raise CapabilityDriftError(
            f"task {task.task_id} requires capabilities {sorted(missing)} "
            f"no longer advertised by current card"
        )

    current_hash = hashlib.sha256(
        json.dumps(current_card, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()
    if current_hash != task.pinned.card_hash:
        # Card changed but required surface is intact: log, do not fail.
        # The invariant only fails the task on *capability* divergence, not
        # on cosmetic card edits (description, provider, etc.).
        pass


def reconcile_on_deploy(
    non_terminal_tasks: list[InFlightTask],
    new_skill_registry: set,
) -> list[tuple[str, str]]:
    """Server-side guardrail: on startup after redeploy, eagerly fail any
    non-terminal task whose pinned skill is unresolvable, rather than letting
    the task TTL reap it silently."""
    orphans = []
    for task in non_terminal_tasks:
        if task.pinned.skill_id not in new_skill_registry:
            task.state = "failed"
            orphans.append((task.task_id, "capability_drift"))
    return orphans
