# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-signed-manifest-but-the-credential-s-capability-set-silently-narrows-across-a-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-signed-manifest-but-the-credential-s-capability-set-silently-narrows-across-a-delegation-hop.warrant.json
# Markdown SHA-256:   f398fd38c168d9f403c9e50579720c0b4efb2b28d1b9535bf849c37b2738932b
# Code AST SHA-256:   847226614e21455c2eeed2fd44119a59bb197a2a5080f91fe8129b965c88fade
# Verified Classes:   CapabilityAttenuationError, Hop, Manifest, HandshakeResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityAttenuationError(RuntimeError):
    """Raised when a dispatch requests a capability not present in the
    delegation-chain intersection, despite the peer manifest advertising it."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str
    subject: str
    capability: FrozenSet[str]


@dataclass(frozen=True)
class Manifest:
    agent_id: str
    capabilities: FrozenSet[str]
    signature_valid: bool


@dataclass
class HandshakeResult:
    effective: FrozenSet[str]
    attenuated: dict = field(default_factory=dict)


def compute_effective_capability(manifest: Manifest, chain: list[Hop]) -> HandshakeResult:
    if not manifest.signature_valid:
        raise CapabilityAttenuationError(
            f"manifest signature invalid for {manifest.agent_id}; cannot establish trust root"
        )
    effective = set(manifest.capabilities)
    attenuated: dict[str, list[str]] = {}
    for hop in chain:
        removed = effective - hop.capability
        if removed:
            attenuated[hop.subject] = sorted(removed)
        effective &= hop.capability
    return HandshakeResult(effective=frozenset(effective), attenuated=attenuated)


def authorize_dispatch(manifest: Manifest, chain: list[Hop], requested: str) -> HandshakeResult:
    result = compute_effective_capability(manifest, chain)
    if requested not in result.effective:
        raise CapabilityAttenuationError(
            f"requested capability {requested!r} not in chain intersection "
            f"{sorted(result.effective)}; manifest advertised "
            f"{sorted(manifest.capabilities)}; attenuated at hops {result.attenuated}"
        )
    return result
