# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-card-s-declared-capability-set-has-silently-diverged-from-the-serving-agent-s-actual-skill-bindings-during-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-card-s-declared-capability-set-has-silently-diverged-from-the-serving-agent-s-actual-skill-bindings-during-a.warrant.json
# Markdown SHA-256:   5bf293793fbdcfb55998cef24c60bbb1d9f193ba62151438cddd5cc8dd4764ef
# Code AST SHA-256:   8a9862d4dcc9729346c1012de6571f299808a768e2f563dfb1bdb7a41dff13a2
# Verified Classes:   CapabilityDivergenceError, ProbeVerdict, SkillBinding, DelegationGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class CapabilityDivergenceError(RuntimeError):
    """Raised when a served AgentCard's skill binding does not match runtime behavior."""
    pass


class ProbeVerdict(Enum):
    VERIFIED = "verified"
    DIVERGED = "diverged"
    QUARANTINED = "quarantined"


@dataclass
class SkillBinding:
    vendor: str
    skill_id: str
    card_etag: str
    verdict: ProbeVerdict = ProbeVerdict.QUARANTINED
    reason: str = "unprobed"

    @property
    def cache_key(self) -> str:
        raw = f"{self.vendor}|{self.skill_id}|{self.card_etag}"
        return hashlib.sha256(raw.encode()).hexdigest()[:16]


@dataclass
class DelegationGate:
    bindings: dict[str, SkillBinding] = field(default_factory=dict)

    def register(self, binding: SkillBinding) -> None:
        self.bindings[binding.cache_key] = binding

    def probe(self, binding: SkillBinding, canary_payload: dict[str, Any],
              send_fn, timeout_s: float = 10.0) -> ProbeVerdict:
        try:
            task = send_fn(binding.skill_id, canary_payload, timeout_s)
        except TimeoutError:
            binding.verdict, binding.reason = ProbeVerdict.DIVERGED, "probe_timeout"
            return binding.verdict
        except Exception as exc:
            binding.verdict, binding.reason = ProbeVerdict.DIVERGED, f"probe_raised:{exc!r}"
            return binding.verdict

        state = task.get("status", {}).get("state")
        if state == "completed":
            binding.verdict, binding.reason = ProbeVerdict.VERIFIED, "canary_completed"
        elif state == "failed":
            msg = task.get("status", {}).get("message", "")
            code = task.get("status", {}).get("error", {}).get("code")
            if code is not None and str(code).startswith("-326"):
                binding.verdict, binding.reason = ProbeVerdict.DIVERGED, f"typed_reject:{code}"
            else:
                binding.verdict = ProbeVerdict.DIVERGED
                binding.reason = f"opaque_failure:{msg[:64]}"
        else:
            binding.verdict, binding.reason = ProbeVerdict.DIVERGED, f"unexpected_state:{state}"
        return binding.verdict

    def dispatch(self, binding: SkillBinding, payload: dict[str, Any], send_fn) -> Any:
        if binding.verdict is not ProbeVerdict.VERIFIED:
            raise CapabilityDivergenceError(
                f"refusing dispatch to {binding.vendor}/{binding.skill_id}: "
                f"verdict={binding.verdict.value} reason={binding.reason}"
            )
        return send_fn(binding.skill_id, payload, timeout_s=30.0)


def example_flow() -> None:
    gate = DelegationGate()
    b = SkillBinding(vendor="vendor-b", skill_id="invoice.reconcile.v2", card_etag="W/\"abc123\"")
    gate.register(b)

    def fake_send(skill_id: str, payload: dict[str, Any], timeout_s: float) -> dict[str, Any]:
        # Simulates the observed divergence: accepted, then opaque failure.
        return {"id": "task-1", "status": {"state": "failed", "message": "internal handler error"}}

    canary = {"line_items": [{"sku": "X", "qty": 1}]}  # taken verbatim from card.examples[0]
    verdict = gate.probe(b, canary, fake_send)
    if verdict is not ProbeVerdict.VERIFIED:
        # Quarantine; do not retry. This is the gate's whole purpose.
        gate.dispatch(b, canary, fake_send)  # raises CapabilityDivergenceError


if __name__ == "__main__":
    example_flow()
