# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-its-capability-epoch-stale-skill-dispatch-and-the-negotiation-replay-gap-in-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-its-capability-epoch-stale-skill-dispatch-and-the-negotiation-replay-gap-in-a2a-v1-0.warrant.json
# Markdown SHA-256:   90b6fbeeed2ed4fe9bd6198da13df6512291375327652d6cbbaf46a01fcb91b1
# Code AST SHA-256:   1c4d21c4d6d40c3cdad400c1efaec528348356a82da1bec36e5f7f4dd871eff6
# Verified Classes:   StaleCapabilityEpochError, SkillContract
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class StaleCapabilityEpochError(RuntimeError):
    """Raised when a peer's live skill contract diverges from the cached Agent Card."""


@dataclass(frozen=True)
class SkillContract:
    skill_id: str
    input_modes: tuple[str, ...]
    output_modes: tuple[str, ...]
    description: str

    def fingerprint(self) -> str:
        payload = json.dumps(
            {
                "id": self.skill_id,
                "in": sorted(self.input_modes),
                "out": sorted(self.output_modes),
                "desc": self.description,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def dispatch_task(cached_card: dict, live_echo: dict, skill_id: str, task: dict) -> dict:
    """Dispatch only if the peer's echoed contract matches the cached contract.

    live_echo is the peer's response to a conditional card re-validation
    (or the fingerprint it echoes back in task acceptance metadata).
    """
    cached = _contract_for(cached_card, skill_id)
    live = _contract_for(live_echo, skill_id)

    if cached.fingerprint() != live.fingerprint():
        raise StaleCapabilityEpochError(
            f"skill {skill_id!r} contract drifted: cached={cached.fingerprint()[:12]} "
            f"live={live.fingerprint()[:12]}; refusing to dispatch across trust boundary"
        )
    return {"skill": skill_id, "task": task, "contract": cached.fingerprint()}


def _contract_for(card: dict, skill_id: str) -> SkillContract:
    for skill in card.get("skills", []):
        if skill.get("id") == skill_id:
            return SkillContract(
                skill_id=skill_id,
                input_modes=tuple(skill.get("inputModes", [])),
                output_modes=tuple(skill.get("outputModes", [])),
                description=skill.get("description", ""),
            )
    raise StaleCapabilityEpochError(f"skill {skill_id!r} absent from card")
