# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-chains-have-silently-widened-scope-at-attenuation-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-chains-have-silently-widened-scope-at-attenuation-boundaries.warrant.json
# Markdown SHA-256:   67b6ba93c04285e3bc8f6f4cc7d1c41bb398826f88aa836f20f60d7818672134
# Code AST SHA-256:   e749986c6fce20689638d38c65cc0df637b41272993a9b66fd5e1514d1321dd0
# Verified Classes:   ScopeShape, AttenuationMonotonicityError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ScopeShape(Enum):
    GLOB = "glob"        # e.g. fs:read:/data/reports/*
    LITERAL = "literal"  # e.g. fs:read:/data/reports/q3/summary.md
    WILDCARD = "wildcard"  # e.g. tool:http:*:...


class AttenuationMonotonicityError(RuntimeError):
    """Raised when a delegated child credential's evaluated permission set
    is not a subset of its parent's under the verifier's evaluation function."""


@dataclass(frozen=True)
class Scope:
    shape: ScopeShape
    value: str


def classify_shape(scope_str: str) -> ScopeShape:
    if scope_str.endswith("/*"):
        return ScopeShape.GLOB
    if "*" in scope_str:
        return ScopeShape.WILDCARD
    return ScopeShape.LITERAL


def attenuate(parent: Scope, child_str: str, *, verifier_eval) -> Scope:
    """Mint a child scope from a parent, enforcing evaluated-set monotonicity.

    verifier_eval(scope) -> frozenset of concrete permissions the scope grants
    under the resource verifier's canonicalize-before-match rules.
    """
    child = Scope(classify_shape(child_str), child_str)

    # Shape-preserving hops may use the cheap literal-subset check.
    if child.shape == parent.shape and child.shape != ScopeShape.WILDCARD:
        if not child.value.startswith(parent.value.rstrip("*")):
            raise AttenuationMonotonicityError(
                f"literal subset violation: {child.value!r} not under {parent.value!r}"
            )
        return child

    # Shape-changing hop: wildcard-into-concrete is a hard reject.
    if parent.shape == ScopeShape.LITERAL and "*" in child.value:
        raise AttenuationMonotonicityError(
            f"wildcard introduced into concrete parent position: "
            f"parent={parent.value!r} child={child.value!r}"
        )

    # Otherwise re-derive evaluated sets and check inclusion.
    parent_set = verifier_eval(parent)
    child_set = verifier_eval(child)
    if not child_set.issubset(parent_set):
        leaked = child_set - parent_set
        raise AttenuationMonotonicityError(
            f"evaluated-set widening across shape boundary "
            f"({parent.shape.value}->{child.shape.value}): "
            f"child grants {len(leaked)} permission(s) parent does not: {sorted(leaked)[:3]}"
        )
    return child


def delegate_chain(root: Scope, hops: list[str], *, verifier_eval) -> list[Scope]:
    chain = [root]
    for hop in hops:
        chain.append(attenuate(chain[-1], hop, verifier_eval=verifier_eval))
    return chain
