# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-scope-attenuation-break-in-an-aaif-capability-attestation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-scope-attenuation-break-in-an-aaif-capability-attestation-chain.warrant.json
# Markdown SHA-256:   a61f5902740d10c7e23586b5e4093eda2b14737eb2694233deb2302c3d1343e6
# Code AST SHA-256:   d06872f9e3a29bd7a750d3bc64312baa5942914c691ce721a285e707479f0922
# Verified Classes:   ScopeAttenuationError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated credential's root-anchored scope exceeds the root grant."""


@dataclass(frozen=True)
class Credential:
    depth: int
    scope: FrozenSet[str]
    grammar_version: str


def expand(scope: FrozenSet[str], grammar_version: str) -> FrozenSet[str]:
    # Pinned expansion: monotone, no sibling-surface leakage.
    if grammar_version != "v1":
        raise ScopeAttenuationError(
            f"unsupported grammar version {grammar_version!r}; cannot root-anchor"
        )
    return frozenset(scope)


def verify_chain(chain: list[Credential]) -> None:
    if not chain:
        raise ScopeAttenuationError("empty attestation chain")
    root = chain[0]
    root_set = expand(root.scope, root.grammar_version)
    for cred in chain[1:]:
        if cred.grammar_version != root.grammar_version:
            raise ScopeAttenuationError(
                f"grammar skew at depth {cred.depth}: "
                f"{cred.grammar_version!r} vs root {root.grammar_version!r}"
            )
        hop_set = expand(cred.scope, cred.grammar_version)
        if not hop_set.issubset(root_set):
            leaked = hop_set - root_set
            raise ScopeAttenuationError(
                f"root-anchored attenuation break at depth {cred.depth}: "
                f"capabilities {sorted(leaked)} not granted by root"
            )


# Reproduces the observed failure: hop-local subset holds, root-anchored fails.
chain = [
    Credential(depth=0, scope=frozenset({"repo:read", "repo:write", "billing:read"}), grammar_version="v1"),
    Credential(depth=1, scope=frozenset({"repo:read"}), grammar_version="v1"),
    Credential(depth=2, scope=frozenset({"repo:read", "report:write"}), grammar_version="v1"),
]
verify_chain(chain)  # raises ScopeAttenuationError on report:write
