# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-agent-card-when-its-jws-capability-manifest-verifies-cryptographically-but-its-declared-capabil.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-agent-card-when-its-jws-capability-manifest-verifies-cryptographically-but-its-declared-capabil.warrant.json
# Markdown SHA-256:   4034fde92eaf2b5c1f9f8ac2d178a3f5d46f6e3a3a0123bc6e6ce23112c3292a
# Code AST SHA-256:   99a1b8b65d53888421ffc737edd6c4f591aa931df8fe4e949d055b33ddb215cd
# Verified Classes:   ManifestCoherenceError, SubManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any


class ManifestCoherenceError(RuntimeError):
    """Raised when a JWS-verified Agent Card's declared capabilities
    contradict the authorization state of its hash-chained sub-manifests."""


@dataclass
class SubManifest:
    uri: str
    digest: str
    prev: str | None
    granted: bool


def _verify_chain_links(extensions: list[dict[str, Any]]) -> list[SubManifest]:
    manifests: list[SubManifest] = []
    expected_prev: str | None = None
    for i, raw in enumerate(extensions):
        if raw.get("prev") != expected_prev:
            raise ManifestCoherenceError(
                f"chain break at index {i}: prev={raw.get('prev')!r} "
                f"expected {expected_prev!r}"
            )
        expected_prev = raw["digest"]
        manifests.append(
            SubManifest(
                uri=raw["uri"],
                digest=raw["digest"],
                prev=raw["prev"],
                granted=bool(raw.get("granted", False)),
            )
        )
    return manifests


def admit_agent_card(card: dict[str, Any], jws_verified: bool) -> list[SubManifest]:
    """Gate a peer Agent Card for capability-gated dispatch.

    Requires jws_verified=True (signature checked out-of-band against
    publisher JWKS). Then enforces the coherence invariant: the declared
    capability URI set must equal the granted sub-manifest URI set.
    """
    if not jws_verified:
        raise ManifestCoherenceError("card JWS did not verify; refusing admission")

    extensions = card.get("capabilities", {}).get("extensions", [])
    manifests = _verify_chain_links(extensions)

    granted_uris = {m.uri for m in manifests if m.granted}
    declared_uris = {raw["uri"] for raw in extensions}

    unauthorized = declared_uris - granted_uris
    if unauthorized:
        raise ManifestCoherenceError(
            "card advertises capabilities with no granted backing manifest: "
            f"{sorted(unauthorized)}"
        )

    return manifests
