# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-capability-drift-when-a-peer-s-agent-card-is-cached-past-its-skill-contract-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-capability-drift-when-a-peer-s-agent-card-is-cached-past-its-skill-contract-revision.warrant.json
# Markdown SHA-256:   23e68c186424863e52c6ebc0aff10211d606c6dc3c2a779918e027920b3246ec
# Code AST SHA-256:   d9f961667eb5f770d04e6f81ff076be162e475fec355576333b40da2a17d48e0
# Verified Classes:   SkillContractDriftError, CachedCard, SkillSchema, Orchestrator
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class SkillContractDriftError(RuntimeError):
    """Raised when a peer's live skill semantics diverge from the cached card
    without a corresponding card version bump, or when a completed task's
    artifact fails local schema validation for the dispatched skillId."""


@dataclass
class CachedCard:
    peer_id: str
    version: str
    skills: dict[str, dict[str, Any]]
    etag: str


@dataclass
class SkillSchema:
    """Locally held, normative output schema. Never sourced from card.examples."""
    skill_id: str
    required_keys: frozenset[str]
    expected_root: type


@dataclass
class Orchestrator:
    cards: dict[str, CachedCard] = field(default_factory=dict)
    schemas: dict[str, SkillSchema] = field(default_factory=dict)
    quarantined: set[tuple[str, str]] = field(default_factory=set)

    def _validate_artifact(self, skill_id: str, artifact: Any) -> None:
        schema = self.schemas.get(skill_id)
        if schema is None:
            raise SkillContractDriftError(
                f"no local schema for skill {skill_id!r}; refusing to dispatch"
            )
        if not isinstance(artifact, schema.expected_root):
            raise SkillContractDriftError(
                f"skill {skill_id!r}: artifact root {type(artifact).__name__} "
                f"!= expected {schema.expected_root.__name__}"
            )
        if isinstance(artifact, dict):
            missing = schema.required_keys - artifact.keys()
            if missing:
                raise SkillContractDriftError(
                    f"skill {skill_id!r}: artifact missing keys {sorted(missing)}"
                )

    def dispatch(self, peer_id: str, skill_id: str, payload: Any) -> Any:
        if (peer_id, skill_id) in self.quarantined:
            raise SkillContractDriftError(
                f"skill {skill_id!r} on peer {peer_id!r} is quarantined pending operator review"
            )
        card = self.cards.get(peer_id)
        if card is None or skill_id not in card.skills:
            raise SkillContractDriftError(
                f"skill {skill_id!r} not present in cached card for {peer_id!r}"
            )
        # ... transport call elided; returns (task_state, artifact) ...
        task_state, artifact = self._call_peer(peer_id, skill_id, payload)
        if task_state != "completed":
            return artifact  # transport-level handling elsewhere

        # Completed task is transport-success; acceptance requires schema check.
        try:
            self._validate_artifact(skill_id, artifact)
        except SkillContractDriftError:
            # Invalidate cache, re-fetch, diff. If id/inputModes unchanged,
            # the peer drifted without signaling -> quarantine.
            fresh = self._refetch_card(peer_id)
            self.cards[peer_id] = fresh
            old = card.skills[skill_id]
            new = fresh.skills.get(skill_id, {})
            if new.get("id") == old.get("id") and new.get("inputModes") == old.get("inputModes"):
                self.quarantined.add((peer_id, skill_id))
                raise SkillContractDriftError(
                    f"silent drift: {skill_id!r} on {peer_id!r} changed artifact shape "
                    f"while card version {card.version!r} -> {fresh.version!r} and "
                    f"skill id/inputModes unchanged; quarantined"
                )
            raise
        return artifact

    def _call_peer(self, peer_id: str, skill_id: str, payload: Any) -> tuple[str, Any]:
        raise NotImplementedError

    def _refetch_card(self, peer_id: str) -> CachedCard:
        raise NotImplementedError
