# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-token-whose-attestation-chain-verifies-but-whose-scope-lattice-no-longer-covers-the-requested-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-token-whose-attestation-chain-verifies-but-whose-scope-lattice-no-longer-covers-the-requested-capability.warrant.json
# Markdown SHA-256:   77b9a76edbfb435636acf9f4c6fcc3a26095a4cbca3204c58bb99ff8130c03d0
# Code AST SHA-256:   46bc62278f735f3a4d00fe0e6e5cfb400bc3eedf926742d96ec92ae2afb7209c
# Verified Classes:   ScopeLatticeMismatchError, Link
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, List


class ScopeLatticeMismatchError(RuntimeError):
    """Raised when a token's signed effective scope diverges from the
    locally recomputed intersection of the delegation chain. This is a
    malformed-chain condition, not an authorization denial: it means the
    emitter failed to recompute the running intersection, and the signed
    'running' field cannot be trusted as the basis for admission."""


@dataclass(frozen=True)
class Link:
    subject: str
    granted: FrozenSet[str]
    running: FrozenSet[str]  # signed effective scope as emitted


def verify_and_authorize(chain: List[Link], requested: str) -> bool:
    if not chain:
        raise ScopeLatticeMismatchError("empty chain")

    # Recompute the lattice from raw grants; never trust signed 'running'.
    effective = frozenset(chain[0].granted)
    for link in chain[1:]:
        effective = effective & link.granted

    leaf_running = chain[-1].running
    if effective != leaf_running:
        raise ScopeLatticeMismatchError(
            f"leaf signed running={sorted(leaf_running)} but recomputed "
            f"intersection={sorted(effective)}; emitter failed to recompute "
            f"running scope at hop {chain[-1].subject!r}"
        )

    return requested in effective
