# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-negotiation-as-a-two-phase-commit-rather-than-a-single-discovery-read.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-negotiation-as-a-two-phase-commit-rather-than-a-single-discovery-read.warrant.json
# Markdown SHA-256:   3795e0b0b232e2d89bfd09bda1de0a58e18cf839bd00d17ba4c0195ab0c8bc23
# Code AST SHA-256:   096d4a353aae28ee95c9755a8c511b109963280ef617c1e7990e1ba23ab719b9
# Verified Classes:   CardContractSkewError, CardContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CardContractSkewError(RuntimeError):
    """Raised when a task response was produced under a different agent-card
    version than the one the client derived its transport/schema contract from."""


@dataclass(frozen=True)
class CardContract:
    card_version: str
    streaming: bool
    skill_input_modes: frozenset
    digest: str


def derive_contract(card: dict) -> CardContract:
    # The commit target: the exact card snapshot we are willing to delegate under.
    skills = {s["id"]: frozenset(s.get("inputModes", [])) for s in card.get("skills", [])}
    blob = json.dumps(card, sort_keys=True).encode()
    return CardContract(
        card_version=card.get("version", "unversioned"),
        streaming=bool(card.get("capabilities", {}).get("streaming", False)),
        skill_input_modes=frozenset().union(*skills.values()) if skills else frozenset(),
        digest=hashlib.sha256(blob).hexdigest(),
    )


def commit_delegation(contract: CardContract, task_response: dict, skill_id: str) -> None:
    # Invariant: the executor must echo the card version it actually enforced.
    echoed = task_response.get("metadata", {}).get("cardVersion")
    if echoed is None:
        raise CardContractSkewError(
            f"executor did not echo cardVersion for skill={skill_id}; "
            f"cannot confirm contract {contract.card_version} was committed"
        )
    if echoed != contract.card_version:
        raise CardContractSkewError(
            f"card skew on skill={skill_id}: client derived contract from "
            f"{contract.card_version} (digest {contract.digest[:12]}), "
            f"executor enforced {echoed}; re-fetch card and re-issue under a "
            f"new idempotency key scoped to {echoed}"
        )
    # Skill-level mode check: top-level capabilities.streaming is NOT sufficient.
    task_modes = frozenset(task_response.get("metadata", {}).get("acceptedInputModes", []))
    if task_modes and not task_modes.issubset(contract.skill_input_modes):
        raise CardContractSkewError(
            f"skill={skill_id} accepted modes {sorted(task_modes)} not covered by "
            f"card contract {sorted(contract.skill_input_modes)}"
        )
