# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-silently-widened-its-scope-through-transitive-capability-intersection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-silently-widened-its-scope-through-transitive-capability-intersection.warrant.json
# Markdown SHA-256:   b4fb57cc6b202c75f918f58e3e726835a6e7a846db51f7fbb0983f5ac5c9ed2b
# Code AST SHA-256:   800226459ce65217884daa4695a1686a8160c8242b7d65af34c0bb5d5bb58dfc
# Verified Classes:   ScopeWideningError, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated credential would carry capability outside its parent's delegable scope."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    delegable_scope: FrozenSet[str]
    depth: int
    max_depth: int
    parent_subject: str | None = None


def issue_delegated_token(
    parent: CapabilityToken,
    subject: str,
    requested_scope: FrozenSet[str],
) -> CapabilityToken:
    # Depth guard: a token at max_depth may not re-delegate at all.
    if parent.depth >= parent.max_depth:
        raise ScopeWideningError(
            f"delegation depth exhausted: parent depth {parent.depth} == max_depth {parent.max_depth}"
        )

    # The single structural invariant: requested capability must be a subset
    # of what the parent was authorized to *delegate*, not what it holds.
    excess = requested_scope - parent.delegable_scope
    if excess:
        raise ScopeWideningError(
            f"requested scope {sorted(excess)} is outside parent delegable scope "
            f"{sorted(parent.delegable_scope)}; refusing issuance to {subject}"
        )

    # Effective scope is the meet (intersection), never the union. The child
    # inherits only what it explicitly requested and the parent may delegate.
    effective = requested_scope & parent.delegable_scope & parent.scope

    # Belt-and-suspenders: assert the lattice property holds after computation.
    if not effective <= parent.scope:
        raise ScopeWideningError(
            f"computed effective scope {sorted(effective)} escapes parent scope "
            f"{sorted(parent.scope)} after meet; issuer algebra is unsound"
        )

    return CapabilityToken(
        subject=subject,
        scope=effective,
        # Child's delegable scope is a strict subset of its own effective scope,
        # and never larger than the parent's delegable scope minus what it used.
        delegable_scope=effective & (parent.delegable_scope - requested_scope),
        depth=parent.depth + 1,
        max_depth=parent.max_depth,
        parent_subject=parent.subject,
    )


def verify_chain(tokens: list[CapabilityToken]) -> None:
    """Walk root-to-leaf and assert the subset invariant at every hop."""
    for i in range(1, len(tokens)):
        parent, child = tokens[i - 1], tokens[i]
        if not child.scope <= parent.scope:
            raise ScopeWideningError(
                f"hop {i}: child {child.subject} scope {sorted(child.scope)} "
                f"not subset of parent {parent.subject} scope {sorted(parent.scope)}"
            )
        if child.depth != parent.depth + 1:
            raise ScopeWideningError(f"hop {i}: depth discontinuity {parent.depth} -> {child.depth}")
