# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-whose-capabilities-skills-matched-at-negotiation-time-but-whose-signed-agent-card-rotated-its-skillha.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-whose-capabilities-skills-matched-at-negotiation-time-but-whose-signed-agent-card-rotated-its-skillha.warrant.json
# Markdown SHA-256:   0eaa9970b7bd95142b86cb3311b7bed23de3c5b5de62d12e76b3d5a7322abee1
# Code AST SHA-256:   4bb2d1eb1d119d06ea57a131eb31d3da4f6b3d253b6acc30a8ba6fd522767ec9
# Verified Classes:   CardDigestMismatch, CapabilityNarrowed, DelegationEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib, json
from dataclasses import dataclass
from typing import Any

class CardDigestMismatch(RuntimeError):
    """Raised when a delegated task's accepted card digest differs from the card the server currently serves."""
    pass

class CapabilityNarrowed(RuntimeError):
    """Raised when the served card drops a skill/inputMode the client negotiated against."""
    pass

def canonical_digest(card_body: dict[str, Any]) -> str:
    canon = json.dumps(card_body, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(canon).hexdigest()

@dataclass
class DelegationEnvelope:
    skill_id: str
    input_mode: str
    accepted_card_digest: str

def accept_task(server_card_body: dict[str, Any], env: DelegationEnvelope) -> None:
    served = canonical_digest(server_card_body)
    if served != env.accepted_card_digest:
        # Rotation detected at accept time. Do NOT accept-then-fail.
        raise CardDigestMismatch(
            f"card rotated between negotiation and send: "
            f"client={env.accepted_card_digest[:12]} server={served[:12]}"
        )
    skills = {s["id"]: s for s in server_card_body.get("skills", [])}
    skill = skills.get(env.skill_id)
    if skill is None or env.input_mode not in skill.get("inputModes", []):
        # Same digest but narrowed capability — must reject, not widen-accept.
        raise CapabilityNarrowed(
            f"skill {env.skill_id!r} no longer advertises input mode {env.input_mode!r}"
        )
    # Safe: digest matches and capability is a superset of what was negotiated.
