# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-agent-card-signature-verifies-but-whose-declared-capabilities-were-never-covered-by-the-signed-payl.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-agent-card-signature-verifies-but-whose-declared-capabilities-were-never-covered-by-the-signed-payl.warrant.json
# Markdown SHA-256:   295288c568367271e9f83ca714d602c7d2f3d81e4cf4c655c931cd99b1f80bd8
# Code AST SHA-256:   2dc729f62a4e1a4a23dde6755a750f65ae800761cc82cc0f709b8f3627e2cb1a
# Verified Classes:   UnsignedCapabilityDispatchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import base64
import json
from typing import Any

class UnsignedCapabilityDispatchError(RuntimeError):
    """Raised when dispatch reads a field not covered by the Agent Card JWS payload."""
    def __init__(self, field_path: str, payload_keys: set[str]):
        self.field_path = field_path
        self.payload_keys = payload_keys
        super().__init__(
            f"dispatch field {field_path!r} is not present in the signed JWS payload "
            f"(signed top-level keys: {sorted(payload_keys)}); "
            f"capability is unsigned and must not be trusted cross-org"
        )


def _decode_jws_payload(detached_jws: str) -> dict[str, Any]:
    # JWS compact form: header.payload.signature ; payload is base64url
    _, payload_b64, _ = detached_jws.split(".")
    raw = base64.urlsafe_b64decode(payload_b64 + "=" * (-len(payload_b64) % 4))
    return json.loads(raw)


def assert_capability_signed(
    card: dict[str, Any],
    detached_jws: str,
    dispatch_path: tuple[str, ...],
) -> None:
    """Fail closed if the field the caller is about to dispatch on is not in the signed payload."""
    signed = _decode_jws_payload(detached_jws)
    signed_keys = set(signed.keys())

    # 1. Top-level key must be inside the signed payload.
    top = dispatch_path[0]
    if top not in signed_keys:
        raise UnsignedCapabilityDispatchError(top, signed_keys)

    # 2. Walk the signed payload; any missing intermediate or leaf is unsigned.
    cursor: Any = signed
    walked: list[str] = []
    for segment in dispatch_path:
        walked.append(segment)
        if not isinstance(cursor, dict) or segment not in cursor:
            raise UnsignedCapabilityDispatchError(".".join(walked), signed_keys)
        cursor = cursor[segment]

    # 3. The value the caller will dispatch on must equal the signed value.
    parsed_cursor: Any = card
    for segment in dispatch_path:
        if not isinstance(parsed_cursor, dict):
            raise UnsignedCapabilityDispatchError(".".join(dispatch_path), signed_keys)
        parsed_cursor = parsed_cursor.get(segment)

    if parsed_cursor != cursor:
        raise UnsignedCapabilityDispatchError(
            ".".join(dispatch_path) + " (value mismatch: parsed != signed)",
            signed_keys,
        )


# Example dispatch gate
def dispatch_task(card: dict[str, Any], detached_jws: str, task: dict[str, Any]) -> None:
    assert_capability_signed(card, detached_jws, ("capabilities", "streaming"))
    assert_capability_signed(card, detached_jws, ("skills",))
    # ... enqueue only after both assertions pass
