# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-extension-uri-it-can-parse-but-cannot-execute-the-parse-execute-gap-in-cross-framework-conformance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-extension-uri-it-can-parse-but-cannot-execute-the-parse-execute-gap-in-cross-framework-conformance.warrant.json
# Markdown SHA-256:   025d0b0734c28c84105822450b6a3d3f10b7a6a767d916f2513406ec7d44371e
# Code AST SHA-256:   1001ffcaad256f155bc567ef0ebfacfaaca301d622e834a09e17c81afda3f31d
# Verified Classes:   ExtensionCapabilityMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ExtensionCapabilityMismatch(RuntimeError):
    """Raised when an agent advertises an extension URI but has no bound handler."""
    pass


def admit_extension(agent_card: dict, uri: str, handler_registry: dict) -> dict:
    """
    Admit an extension payload only if the URI is both advertised AND handler-bound.
    Returns the bound handler descriptor. Raises if the parse-execute gap is open.
    """
    advertised = {e["uri"] for e in agent_card.get("extensions", [])}
    if uri not in advertised:
        raise ExtensionCapabilityMismatch(
            f"extension {uri} not advertised by peer; refusing admission"
        )
    handler = handler_registry.get(uri)
    if handler is None:
        # The load-bearing check: URI present, handler absent -> parse-execute gap.
        raise ExtensionCapabilityMismatch(
            f"extension {uri} advertised but no handler bound; "
            f"behavioral contract would be silently skipped"
        )
    return handler


def gate_destructive_action(agent_card: dict, uri: str, handler_registry: dict,
                            action: str) -> None:
    """Refuse the gated action unless the extension handler is provably bound."""
    try:
        admit_extension(agent_card, uri, handler_registry)
    except ExtensionCapabilityMismatch as exc:
        # Fail closed: do not run the action the extension was meant to serialize.
        raise ExtensionCapabilityMismatch(
            f"refusing destructive action {action!r}: {exc}"
        ) from exc
