# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-task-acceptance-when-a-signed-agent-card-s-declared-capability-set-diverges-from-the-negotiated.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-task-acceptance-when-a-signed-agent-card-s-declared-capability-set-diverges-from-the-negotiated.warrant.json
# Markdown SHA-256:   56dd5dcd9c2997afc09175937950b917be70d2beca1244a76b6b64edf39c1a58
# Code AST SHA-256:   5bc7de777c1177240de1df91227901a69d4f8c684077851665133f419287aa75
# Verified Classes:   CapabilityBindingDivergence, CapabilitySet, TaskAcceptance
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityBindingDivergence(RuntimeError):
    """Raised when a task acceptance binds a capability set that does not
    cover the client's required set, despite a validly signed Agent Card."""


@dataclass(frozen=True)
class CapabilitySet:
    skills: FrozenSet[str]
    streaming: bool
    input_modes: FrozenSet[str]
    output_modes: FrozenSet[str]


@dataclass
class TaskAcceptance:
    task_id: str
    bound: CapabilitySet | None
    checkpoint_committed: bool = False
    downstream_dispatched: bool = False


def normalize_bound(acceptance: TaskAcceptance) -> CapabilitySet:
    if acceptance.bound is None:
        # No binding echo: cannot prove coverage. Treat as unbound, not as
        # "assume declared" — the card attests intent, not delivery.
        raise CapabilityBindingDivergence(
            f"task {acceptance.task_id}: acceptance carried no boundCapabilities; "
            "cannot verify coverage against declared card"
        )
    return acceptance.bound


def enforce_binding(
    declared: CapabilitySet,
    required: CapabilitySet,
    acceptance: TaskAcceptance,
) -> None:
    # Phase one precondition: the client must never require what the card
    # did not attest. This is a programming error, not a remote fault.
    missing_from_card = required.skills - declared.skills
    if missing_from_card:
        raise CapabilityBindingDivergence(
            f"required skills {sorted(missing_from_card)} not present in signed "
            "Agent Card; refuse to request un-attested capability"
        )

    bound = normalize_bound(acceptance)

    # Phase two: the runtime must bind at least what the task requires.
    uncovered = required.skills - bound.skills
    if uncovered:
        if not acceptance.checkpoint_committed and not acceptance.downstream_dispatched:
            raise CapabilityBindingDivergence(
                f"task {acceptance.task_id}: bound skills {sorted(bound.skills)} "
                f"do not cover required {sorted(required.skills)}; "
                "reject before checkpoint commit"
            )
        if acceptance.downstream_dispatched:
            # Unrecoverable: a side effect already fired on a false acceptance.
            raise CapabilityBindingDivergence(
                f"task {acceptance.task_id}: divergence discovered after downstream "
                "dispatch; surface TaskStateInconsistency to orchestrator"
            )
        # Checkpoint committed but no side effect yet: rollback is safe.
        raise CapabilityBindingDivergence(
            f"task {acceptance.task_id}: divergence after checkpoint; "
            "rollback to pre-acceptance state and renegotiate"
        )

    if required.streaming and not bound.streaming:
        raise CapabilityBindingDivergence(
            f"task {acceptance.task_id}: required streaming but runtime bound "
            "streaming=false; SSE progress events will not arrive"
        )

    if not required.input_modes.issubset(bound.input_modes):
        raise CapabilityBindingDivergence(
            f"task {acceptance.task_id}: input modes {sorted(required.input_modes)} "
            f"not covered by bound {sorted(bound.input_modes)}"
        )
