# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-claim-drift-from-corrupting-cross-vendor-agent-card-discovery-during-a2a-v1-0-delegation-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-claim-drift-from-corrupting-cross-vendor-agent-card-discovery-during-a2a-v1-0-delegation-handshakes.warrant.json
# Markdown SHA-256:   31a01be31f9be1320fc3b05f6120925f71ea89bd98e72eae7ba16b94e74ffa5e
# Code AST SHA-256:   e1605e446b68d5166943c7f7232e849944dbb2dfd3c857553545d9d2a13b802c
# Verified Classes:   CapabilityClaimDrift, ResolvedCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityClaimDrift(RuntimeError):
    """Raised when a delegation would proceed on an unconfirmed or drifted AgentCard."""
    pass


@dataclass(frozen=True)
class ResolvedCard:
    raw: dict
    version: str          # server-declared card version, e.g. an ETag or ISO timestamp
    authoritative: bool   # True only if fetched from a non-cached, version-echoing endpoint


def card_digest(card: dict) -> str:
    canonical = json.dumps(card, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def submit_task(card: ResolvedCard, skill: str, params: dict, transport) -> dict:
    # Invariant 1: never delegate on a card we cannot re-confirm as current.
    if not card.authoritative:
        raise CapabilityClaimDrift(
            f"refusing to delegate skill={skill!r}: card version {card.version!r} "
            f"is not authoritative (cached/registry projection); re-fetch from "
            f"the version-echoing endpoint before submission"
        )

    # Invariant 2: the skill must be present in the card we are about to cite.
    advertised = {s.get("id") for s in card.raw.get("skills", [])}
    if skill not in advertised:
        raise CapabilityClaimDrift(
            f"skill={skill!r} not advertised by card version {card.version!r}; "
            f"advertised={sorted(advertised)}"
        )

    digest = card_digest(card.raw)
    payload = {
        "skill": skill,
        "params": params,
        "card_version": card.version,
        "card_digest": digest,
    }

    response = transport.post("/tasks", payload)

    # Invariant 3: a completed task must echo the exact card we validated against.
    # A mismatch means the server executed under a different contract than we cited.
    echoed_version = response.get("card_version")
    echoed_digest = response.get("card_digest")
    if response.get("state") == "completed":
        if echoed_version != card.version or echoed_digest != digest:
            raise CapabilityClaimDrift(
                f"task returned completed but executed under card "
                f"version={echoed_version!r} digest={echoed_digest!r}, "
                f"expected version={card.version!r} digest={digest!r}; "
                f"result is non-diagnostic and must not be trusted"
            )
        # Invariant 4: completed must not be a generic-fallback masquerade.
        if response.get("executed_skill") not in (None, skill):
            raise CapabilityClaimDrift(
                f"task completed via fallback skill "
                f"{response.get('executed_skill')!r} instead of {skill!r}; "
                f"capability-claim drift detected at execution time"
            )

    return response
