# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-capability-token-whose-attenuation-chain-is-syntactically-valid-but-semantically-widened-by.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-capability-token-whose-attenuation-chain-is-syntactically-valid-but-semantically-widened-by.warrant.json
# Markdown SHA-256:   6bdd96216cf7379bb41f8c7c46929fee23edc5eb2b584bbba335421dded6f938
# Code AST SHA-256:   eebee577749d283e3078b52e5d51f47c5c05a754d5d81f1881c74ac5b51ad1f9
# Verified Classes:   CapabilityAttenuationError, Scope, Token
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Iterable


class CapabilityAttenuationError(RuntimeError):
    """Raised when a delegated AAIF token is syntactically valid but semantically widened."""


@dataclass(frozen=True)
class Scope:
    selector: str          # e.g. "s3://tenant-42/reports/2024/*"
    verbs: frozenset[str]  # e.g. frozenset({"read", "list"})


@dataclass(frozen=True)
class Token:
    issuer: str
    subject: str
    scope: Scope
    parent_hash: str | None   # None for root tokens


# Denotation function: given a selector and a verb, return the set of concrete
# resource keys the capability reaches. Backend-supplied; must be verb-indexed.
DenotationFn = Callable[[str, str], frozenset[str]]


def verify_chain(
    chain: list[Token],
    denote: DenotationFn,
    descriptor_cache: dict[tuple[str, str], Scope],
) -> None:
    """
    Validate an A->B->C delegation chain. Rejects if any hop's child scope
    denotes a superset of its parent's scope under any child verb.
    """
    if not chain:
        raise CapabilityAttenuationError("empty delegation chain")

    root = chain[0]
    if root.parent_hash is not None:
        raise CapabilityAttenuationError("chain does not begin at a root token")

    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        # Freshness: never trust a cached descriptor whose key omits a dimension.
        cache_key = (parent.issuer, parent.scope.selector)
        cached = descriptor_cache.get(cache_key)
        if cached is not None and cached.verbs != parent.scope.verbs:
            raise CapabilityAttenuationError(
                f"stale descriptor at hop {i}: cache key {cache_key!r} "
                f"omitted verb dimension; cached verbs {sorted(cached.verbs)} "
                f"!= bound verbs {sorted(parent.scope.verbs)}"
            )

        # Verb monotonicity against the *freshly bound* parent scope.
        widened_verbs = child.scope.verbs - parent.scope.verbs
        if widened_verbs:
            raise CapabilityAttenuationError(
                f"verb escalation at hop {i}: {sorted(widened_verbs)} "
                f"not held by parent {parent.issuer}"
            )

        # Denotational containment, verb-indexed.
        for verb in child.scope.verbs:
            child_den = denote(child.scope.selector, verb)
            parent_den = denote(parent.scope.selector, verb)
            leaked = child_den - parent_den
            if leaked:
                raise CapabilityAttenuationError(
                    f"denotational widening at hop {i} under verb {verb!r}: "
                    f"{len(leaked)} keys reachable by {child.subject} "
                    f"exceed {parent.issuer}'s grant (e.g. {sorted(leaked)[:3]})"
                )


def _example() -> None:
    # Backend denotation: 'list' on a prefix reaches all keys under it;
    # 'read' on a prefix reaches only the prefix object itself.
    def denote(selector: str, verb: str) -> frozenset[str]:
        if verb == "list":
            return frozenset({selector + "k1", selector + "k2", selector + "sibling"})
        return frozenset({selector})

    root = Token("R", "O", Scope("s3://tenant-42/reports/", frozenset({"read"})), None)
    child = Token("O", "S", Scope("s3://tenant-42/reports/2024/", frozenset({"read", "list"})), "h0")
    cache = {("O", "s3://tenant-42/reports/"): Scope("s3://tenant-42/reports/", frozenset({"read", "list"}))}

    verify_chain([root, child], denote, cache)  # raises: stale descriptor + verb widening


if __name__ == "__main__":
    _example()
