# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-peer-whose-agent-card-advertises-a-capability-the-runtime-cannot-cryptographically-bind-to-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-peer-whose-agent-card-advertises-a-capability-the-runtime-cannot-cryptographically-bind-to-a.warrant.json
# Markdown SHA-256:   ab25dbf5c6f05477a71bfad3ed9438b741933d917769874f21d84f7a5092fede
# Code AST SHA-256:   656c8241746c1a240f73d6d5b27bccfd568d271ee0648ec93dbe9079524e0b7c
# Verified Classes:   CapabilityWarrantDivergence, HandshakeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityWarrantDivergence(RuntimeError):
    """Raised when a peer's Agent Card scopes cannot be bound to the
    scope set actually enforced by its task-execution endpoint."""
    pass


class HandshakeState:
    DISCOVERED = "discovered"          # card fetched, scopes untrusted
    BINDING = "binding"                # probing endpoint for enforced scopes
    BOUND = "bound"                    # endpoint confirmed generation match
    REJECTED = "rejected"


def bind_warrant(card: dict, endpoint_probe: dict | None) -> list[str]:
    """Return the verified scope set, or raise if the card cannot be bound.

    card: parsed Agent Card from /.well-known/agent.json
    endpoint_probe: response from GET /tasks/capabilities, or None if absent
    """
    card_scopes = set()
    for scheme in card.get("securitySchemes", {}).values():
        for flow in scheme.get("flows", {}).values():
            card_scopes.update(flow.get("scopes", {}).keys())
    card_scopes.update(s.get("id") for s in card.get("skills", []) if s.get("id"))

    if endpoint_probe is None:
        raise CapabilityWarrantDivergence(
            f"peer {card.get('name')!r} exposes no /tasks/capabilities; "
            f"card scopes {sorted(card_scopes)} are un-bindable, refusing to mint warrant"
        )

    probe_gen = endpoint_probe.get("generation")
    card_gen = card.get("version") or card.get("etag")
    if probe_gen != card_gen:
        raise CapabilityWarrantDivergence(
            f"generation mismatch: card={card_gen!r} endpoint={probe_gen!r}; "
            f"card advertises {sorted(card_scopes)} but endpoint enforces "
            f"{sorted(endpoint_probe.get('enforcedScopes', []))}"
        )

    enforced = set(endpoint_probe.get("enforcedScopes", []))
    unbound = card_scopes - enforced
    if unbound:
        raise CapabilityWarrantDivergence(
            f"card advertises scopes not enforced by endpoint: {sorted(unbound)}; "
            f"warrant would be downscoped silently"
        )

    return sorted(card_scopes)
