# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-a2a-agent-card-advertises-a-skill-set-that-diverges-from-the-callee-s-actual-runtime-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-a2a-agent-card-advertises-a-skill-set-that-diverges-from-the-callee-s-actual-runtime-dispatch.warrant.json
# Markdown SHA-256:   7674b08d3842239d7974029f552ea7455550c2012e1c4c8fa0e43b5cdca4d89d
# Code AST SHA-256:   f25095c7bf0442cb743fb9792d67790dca75391e7782a75612705ba66002b318
# Verified Classes:   CardDispatchMismatch, DispatchEntry, AgentCard, A2ACallee
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, Optional


class CardDispatchMismatch(RuntimeError):
    """Raised when an advertised skill has no active handler, or a completed
    artifact violates the output contract declared in the AgentCard."""
    pass


@dataclass
class DispatchEntry:
    handler: str
    active: bool
    entitled_callers: Optional[set] = None  # None => open to all


@dataclass
class AgentCard:
    skills: Dict[str, dict]  # skill_id -> {outputModes, examples, ...}
    version: str

    def version_hash(self) -> str:
        blob = json.dumps({"skills": self.skills, "version": self.version},
                          sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()[:16]


class A2ACallee:
    def __init__(self, card: AgentCard, dispatch: Dict[str, DispatchEntry]):
        self.card = card
        self.dispatch = dispatch
        # Build-gate invariant: every advertised skill must have an active handler
        # and every active handler must be advertised. Fail construction otherwise.
        advertised = set(card.skills)
        active = {sid for sid, e in dispatch.items() if e.active}
        if advertised != active:
            missing = advertised - active
            orphan = active - advertised
            raise CardDispatchMismatch(
                f"card/dispatch referential integrity broken: "
                f"advertised-without-handler={sorted(missing)} "
                f"handler-without-advertisement={sorted(orphan)}"
            )

    def accept(self, skill_id: str, caller_id: str) -> DispatchEntry:
        if skill_id not in self.card.skills:
            raise CardDispatchMismatch(
                f"skill {skill_id!r} not advertised; reject at ingress"
            )
        entry = self.dispatch.get(skill_id)
        if entry is None or not entry.active:
            # Do NOT fall through to a generic handler. Reject loudly.
            raise CardDispatchMismatch(
                f"skill {skill_id!r} advertised but not active for caller "
                f"{caller_id!r}; return rejected:skill_unavailable"
            )
        if entry.entitled_callers is not None and caller_id not in entry.entitled_callers:
            raise CardDispatchMismatch(
                f"skill {skill_id!r} active but caller {caller_id!r} not "
                f"entitled; return rejected:not_entitled"
            )
        return entry

    def complete(self, skill_id: str, artifact: dict) -> dict:
        declared = set(self.card.skills[skill_id]["outputModes"])
        produced = set(artifact.get("modes", []))
        if not produced.issubset(declared):
            raise CardDispatchMismatch(
                f"artifact modes {sorted(produced)} violate declared "
                f"outputModes {sorted(declared)} for skill {skill_id!r}; "
                f"return failed:output_contract_violation"
            )
        return artifact


def delegate(callee: A2ACallee, skill_id: str, caller_id: str,
             artifact: dict) -> dict:
    callee.accept(skill_id, caller_id)
    return callee.complete(skill_id, artifact)


if __name__ == "__main__":
    card = AgentCard(
        skills={"summarize_contract": {"outputModes": ["text/plain"]}},
        version="2025-06-11a",
    )
    dispatch = {
        "summarize_contract": DispatchEntry(
            handler="contract_v2", active=False  # rolled back / flag-gated
        )
    }
    try:
        callee = A2ACallee(card, dispatch)
    except CardDispatchMismatch as e:
        # Build gate fires: card advertises a skill with no active handler.
        print(f"deploy blocked: {e}")
        raise CardDispatchMismatch(
            "refusing to serve card that advertises inactive skill "
            "summarize_contract"
        ) from e
