# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-resuming-a2a-client-from-re-negotiating-artifact-mime-types-against-a-peer-whose-agent-card-has-silently-drifted-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-resuming-a2a-client-from-re-negotiating-artifact-mime-types-against-a-peer-whose-agent-card-has-silently-drifted-mid-task.warrant.json
# Markdown SHA-256:   8248ae248624a672252fe58dadb641da674bc5ddc6cc3c28f40e6fe36527a486
# Code AST SHA-256:   fbbd21c91b6097fba4e04ce1060e4f881769fa8650616776e8a97f0ae538b37d
# Verified Classes:   ContractDriftError, ContractInvalidCancelError, AgentCard, TaskHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet


class ContractDriftError(RuntimeError):
    """Raised when a resuming client tries to validate an in-flight task's
    artifact contract against a re-fetched Agent Card whose token has drifted."""


class ContractInvalidCancelError(RuntimeError):
    """Raised when a cancel is issued solely due to card-vs-task mode mismatch."""


@dataclass(frozen=True)
class AgentCard:
    card_etag: str
    default_output_modes: FrozenSet[str]


@dataclass
class TaskHandle:
    task_id: str
    accepted_output_modes: FrozenSet[str]
    frozen_card_etag: str
    artifacts_appended: int = 0
    terminal: bool = False


def resume_task(
    handle: TaskHandle,
    live_card: AgentCard,
    *,
    allow_renegotiate: bool = False,
) -> TaskHandle:
    """Resume an in-flight task. The frozen contract governs; the live card
    is advisory only and MUST NOT invalidate the task's accepted modes."""
    if handle.terminal:
        # Terminal tasks are immutable; nothing to re-validate.
        return handle

    card_drifted = live_card.card_etag != handle.frozen_card_etag
    contract_materialized = handle.artifacts_appended > 0

    if card_drifted and not contract_materialized:
        # No artifact yet: the frozen contract still binds. We may *offer*
        # renegotiation, but we must never cancel on the mismatch.
        if allow_renegotiate:
            # Explicit renegotiation is a new-task operation, not a mutation.
            raise ContractDriftError(
                f"task {handle.task_id}: card etag drifted "
                f"({handle.frozen_card_etag} -> {live_card.card_etag}); "
                f"renegotiation requires a new task, not mutation of the in-flight one"
            )
        # Default: proceed against the frozen contract, ignore the new card.
        return handle

    if card_drifted and contract_materialized:
        # Artifacts already exist under the frozen contract. Discovery-layer
        # drift MUST NOT retroactively invalidate them.
        return handle

    # No drift: the live card is consistent with the frozen contract.
    return handle


def cancel_on_mode_mismatch(handle: TaskHandle, live_card: AgentCard) -> None:
    """Reject the unsound pattern: canceling an in-flight task because the
    live card no longer lists the task's accepted output modes."""
    if handle.terminal:
        return
    if handle.accepted_output_modes.isdisjoint(live_card.default_output_modes):
        raise ContractInvalidCancelError(
            f"task {handle.task_id}: refusing to cancel on card/task mode mismatch "
            f"(task modes={sorted(handle.accepted_output_modes)}, "
            f"card defaults={sorted(live_card.default_output_modes)}); "
            f"frozen contract governs until terminal"
        )
