# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-skill-provenance-when-a-third-party-mcp-server-re-signs-an-a2a-agent-card-after-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-skill-provenance-when-a-third-party-mcp-server-re-signs-an-a2a-agent-card-after-capability-negotiation.warrant.json
# Markdown SHA-256:   dbe180116030e24961cd7f5584818d40b81ef9524c228ff5b76635b1dcb0a51d
# Code AST SHA-256:   ab6dfaaa0c3d1f29521c04104f532b529d26becf04a4512a4778c22c9cca3e19
# Verified Classes:   ProvenanceDriftError, ProvenanceTuple
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ProvenanceDriftError(RuntimeError):
    """Raised when the provenance tuple at dispatch differs from negotiation."""


@dataclass(frozen=True)
class ProvenanceTuple:
    skill_id: str
    schema_digest: str
    leaf_signer_thumbprint: str
    card_version: int


def canonical_schema_digest(schema: dict) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def verify_dispatch_provenance(
    negotiated: ProvenanceTuple,
    dispatch_card: dict,
    leaf_thumbprint: str,
) -> None:
    """Confirm the dispatch-time card matches the negotiated provenance tuple."""
    skill = next(
        (s for s in dispatch_card.get("skills", []) if s.get("id") == negotiated.skill_id),
        None,
    )
    if skill is None:
        raise ProvenanceDriftError(
            f"skill {negotiated.skill_id!r} absent from dispatch-time card"
        )

    dispatch_digest = canonical_schema_digest(skill.get("input_schema", {}))
    if dispatch_digest != negotiated.schema_digest:
        raise ProvenanceDriftError(
            f"schema drift for {negotiated.skill_id!r}: "
            f"negotiated={negotiated.schema_digest} dispatch={dispatch_digest}"
        )

    if leaf_thumbprint != negotiated.leaf_signer_thumbprint:
        raise ProvenanceDriftError(
            f"leaf signer substitution for {negotiated.skill_id!r}: "
            f"negotiated={negotiated.leaf_signer_thumbprint} dispatch={leaf_thumbprint}"
        )

    if dispatch_card.get("version", 0) != negotiated.card_version:
        raise ProvenanceDriftError(
            f"card version changed under dispatcher for {negotiated.skill_id!r}; "
            "renegotiation required"
        )
