# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-capability-tokens-have-silently-exceeded-their-attenuation-chain-depth.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-capability-tokens-have-silently-exceeded-their-attenuation-chain-depth.warrant.json
# Markdown SHA-256:   37288f2c6fdce4449a2d6fef06f0928e64245143dab27f03783812b53569d566
# Code AST SHA-256:   1157cc57cccb9182acf6caa459696a913072dbdbe1076d09383622c544b6dfbb
# Verified Classes:   AttenuationDriftError, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping, Optional


class AttenuationDriftError(RuntimeError):
    """Raised when a delegated token's effective authority is not a subset of its root's."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    root_id: str
    depth: int
    caveats: Mapping[str, object]          # class -> bound value
    signature_valid: bool


DECLARED_CLASSES = {
    "resource": lambda a, b: a if a == b else None,   # must be identical
    "ttl":      lambda a, b: min(a, b),               # numeric min
    "scope":    lambda a, b: a & b,                   # set intersection
}


def verify_delegated(token: CapabilityToken, root: CapabilityToken,
                     max_depth: int = 5) -> None:
    if not token.signature_valid:
        raise AttenuationDriftError("signature invalid; cannot evaluate authority")
    if token.depth > max_depth:
        raise AttenuationDriftError(
            f"chain depth {token.depth} exceeds max_depth {max_depth}"
        )

    # Class-closure: every caveat class must be declared.
    unknown = set(token.caveats) - set(DECLARED_CLASSES)
    if unknown:
        raise AttenuationDriftError(f"undeclared caveat classes: {unknown}")

    # Class-coverage subset: leaf must not introduce classes the root lacks.
    if not set(token.caveats).issubset(set(root.caveats)):
        extra = set(token.caveats) - set(root.caveats)
        raise AttenuationDriftError(
            f"class coverage drift: leaf adds classes {extra} not present at root"
        )

    # Conjunctive attenuation: for each class, leaf bound must be <= root bound
    # under the declared operator. Equality is allowed; widening is not.
    for cls, leaf_val in token.caveats.items():
        root_val = root.caveats[cls]
        narrowed = DECLARED_CLASSES[cls](root_val, leaf_val)
        if narrowed is None or narrowed != leaf_val:
            raise AttenuationDriftError(
                f"attenuation widening in class {cls!r}: "
                f"root={root_val!r} leaf={leaf_val!r}"
            )
