# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-scoped-capability-token-across-an-aaif-chain-and-the-attenuation-proof-silently-widens.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-scoped-capability-token-across-an-aaif-chain-and-the-attenuation-proof-silently-widens.warrant.json
# Markdown SHA-256:   c101d4926c0d155151a19919e1e7991027702f5dc7b0790016e4054fc2be5312
# Code AST SHA-256:   69a7c91a3b868168bc35390c9e24e0e0b832489ea4c95890b29034647023cf25
# Verified Classes:   ScopeWideningError, Scope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when an AAIF attenuation step fails lattice monotonicity."""
    pass


@dataclass(frozen=True)
class Scope:
    concrete: FrozenSet[str]
    has_opaque_literal: bool


def normalize(raw: str, resolver) -> Scope:
    # A closed normalizer must fully expand or reject. No opaque fallback.
    if "*" in raw:
        expanded = resolver.expand(raw)
        if expanded is None:
            raise ScopeWideningError(
                f"cannot expand wildcard scope {raw!r}; refusing opaque fallback"
            )
        return Scope(concrete=frozenset(expanded), has_opaque_literal=False)
    return Scope(concrete=frozenset({raw}), has_opaque_literal=False)


def attenuate(parent_raw: str, child_raw: str, resolver) -> Scope:
    parent = normalize(parent_raw, resolver)
    child = normalize(child_raw, resolver)
    if child.has_opaque_literal or parent.has_opaque_literal:
        raise ScopeWideningError(
            "opaque literal in scope algebra; subset check is unsound"
        )
    if not child.concrete.issubset(parent.concrete):
        raise ScopeWideningError(
            f"attenuation widens scope: {sorted(child.concrete)} "
            f"not subset of {sorted(parent.concrete)}"
        )
    return child


def verify_chain(root_raw: str, hops: list, resolver) -> Scope:
    # Terminal-boundary whole-lattice check: every hop's concrete set
    # must remain a subset of the ROOT warrant, not just its parent.
    root = normalize(root_raw, resolver)
    current = root
    for hop in hops:
        current = attenuate_scope(current, hop, resolver)
        if not current.concrete.issubset(root.concrete):
            raise ScopeWideningError(
                f"chain widened beyond root warrant at hop {hop!r}"
            )
    return current


def attenuate_scope(parent: Scope, child_raw: str, resolver) -> Scope:
    child = normalize(child_raw, resolver)
    if not child.concrete.issubset(parent.concrete):
        raise ScopeWideningError(
            f"hop widens parent: {sorted(child.concrete)} "
            f"not subset of {sorted(parent.concrete)}"
        )
    return child
