# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-drift-between-a-cached-a2a-agent-card-and-the-live-peer-schema-during-task-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-drift-between-a-cached-a2a-agent-card-and-the-live-peer-schema-during-task-dispatch.warrant.json
# Markdown SHA-256:   e4356e489c3a5e7fecf10410577ac41a638b3bd23af08865a42f02f3ea3e669a
# Code AST SHA-256:   a8b108817e8e43b3780c14a76975c4b7be9403551680d3f754484d5fee548839
# Verified Classes:   CapabilityDriftError, AgentCard, TaskResponse, CardLease
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when a peer's response contradicts the cached AgentCard contract."""
    pass


@dataclass
class AgentCard:
    skills: set[str]
    input_modes: set[str]
    etag: str
    fetched_at: float


@dataclass
class TaskResponse:
    state: str            # "completed" | "failed" | "working"
    artifacts: list = field(default_factory=list)
    reason: Optional[str] = None


class CardLease:
    """Caches an AgentCard with a freshness lease and response-shape assertion."""

    def __init__(self, fetch_fn, max_age_s: float = 300.0):
        self._fetch = fetch_fn          # () -> AgentCard
        self._max_age = max_age_s
        self._card: Optional[AgentCard] = None

    def _fresh(self) -> bool:
        if self._card is None:
            return False
        return (time.monotonic() - self._card.fetched_at) <= self._max_age

    def card(self) -> AgentCard:
        if not self._fresh():
            self._card = self._fetch()
        return self._card

    def invalidate(self) -> None:
        self._card = None

    def dispatch(self, skill: str, response: TaskResponse) -> TaskResponse:
        card = self.card()
        if skill not in card.skills:
            # Planning should have caught this; treat as drift, not a plan bug.
            self.invalidate()
            raise CapabilityDriftError(
                f"skill '{skill}' absent from card at dispatch; cache invalidated"
            )

        # Response-shape assertion: a completed task for a declared skill
        # MUST yield at least one artifact. Empty success == silent drift.
        if response.state == "completed" and not response.artifacts:
            self.invalidate()
            raise CapabilityDriftError(
                f"skill '{skill}' returned completed with 0 artifacts "
                f"(card etag={card.etag}); peer likely dropped capability"
            )

        if response.state == "failed" and response.reason and "skill" in response.reason.lower():
            self.invalidate()
            raise CapabilityDriftError(
                f"peer reported unknown skill '{skill}': {response.reason}"
            )

        return response
