# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-is-stale-but-valid-the-updatedat-monotonicity-trap-in-cross-vendor-task-lifecycle-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-is-stale-but-valid-the-updatedat-monotonicity-trap-in-cross-vendor-task-lifecycle-negotiation.warrant.json
# Markdown SHA-256:   0736809c94e4613221069fd847194bb820ac71b89e0bf7ada3e70cd79639141b
# Code AST SHA-256:   c8aa6582393640e97a211275130e452d52d3743005c423d182f809f84173d8bc
# Verified Classes:   ArtifactModeViolation, SkillTriple, CardCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ArtifactModeViolation(RuntimeError):
    """Raised when a completed A2A task returns an artifact whose mimeType
    does not conform to the requested acceptedOutputModes, or whose mimeType
    is absent from the peer's cached AgentCard skill outputModes (stale card)."""


@dataclass
class SkillTriple:
    skill_id: str
    input_modes: tuple[str, ...]
    output_modes: tuple[str, ...]
    conformance_confirmed_at: Optional[float] = None


@dataclass
class CardCache:
    peer: str
    updated_at: str
    skills: dict[str, SkillTriple] = field(default_factory=dict)
    mode_drifted: set[str] = field(default_factory=set)


def validate_completed_task(
    cache: CardCache,
    skill_id: str,
    requested_modes: list[str],
    artifact_mime: str,
    now: float,
) -> SkillTriple:
    """
    Called at tasks/get when state == 'completed'. Enforces the
    artifact-mode conformance invariant. Returns the (possibly refreshed)
    triple on success; raises on any non-conformance.
    """
    triple = cache.skills.get(skill_id)
    if triple is None:
        raise ArtifactModeViolation(
            f"skill {skill_id!r} on {cache.peer!r} not present in cached card"
        )

    if artifact_mime not in requested_modes:
        # Server ignored acceptedOutputModes. Do not retry with same card.
        raise ArtifactModeViolation(
            f"peer {cache.peer!r} skill {skill_id!r}: artifact mimeType "
            f"{artifact_mime!r} not in requested modes {requested_modes!r}; "
            f"re-discovery required before retry"
        )

    if artifact_mime not in triple.output_modes:
        # Card is stale-but-valid: metadata checks pass, surface drifted.
        cache.mode_drifted.add(skill_id)
        raise ArtifactModeViolation(
            f"peer {cache.peer!r} skill {skill_id!r}: artifact mimeType "
            f"{artifact_mime!r} absent from cached outputModes "
            f"{triple.output_modes!r} (card updatedAt={cache.updated_at!r}); "
            f"card is stale-but-valid, invalidate triple and re-fetch"
        )

    # Conformance confirmed: this is the only path that refreshes the triple.
    triple.conformance_confirmed_at = now
    cache.mode_drifted.discard(skill_id)
    return triple
