# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-privilege-escalation-in-aaif-delegated-credential-chains-with-scoped-token-attenuation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-privilege-escalation-in-aaif-delegated-credential-chains-with-scoped-token-attenuation.warrant.json
# Markdown SHA-256:   855b1a35a5c1122e4af5b91fd455d9a561695e4bfdda96d10b294082f36fa359
# Code AST SHA-256:   aeb3cb8a51240d484b6d96765e6785b53b1b4780e415f08656e079ee4003a107
# Verified Classes:   ScopeAttenuationError, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated token would exceed its parent's effective authority."""


@dataclass(frozen=True)
class Token:
    scope: FrozenSet[str]                 # resolved resource identifiers
    constraints: FrozenSet[str]           # exclusion clauses, e.g. "deny:/data/pii/*"
    audience: FrozenSet[str]
    ttl: int
    depth: int


def attenuate(parent: Token, child_scope: FrozenSet[str],
              child_constraints: FrozenSet[str], child_audience: FrozenSet[str],
              child_ttl: int) -> Token:
    parent_effective = parent.scope - _resolve_exclusions(parent.constraints)

    if not child_scope <= parent_effective:
        leaked = child_scope - parent_effective
        raise ScopeAttenuationError(
            f"scope widening: child reaches {sorted(leaked)} outside parent authority"
        )
    if not parent.constraints <= child_constraints:
        dropped = parent.constraints - child_constraints
        raise ScopeAttenuationError(
            f"constraint closure violated: dropped {sorted(dropped)}"
        )
    if child_ttl > parent.ttl:
        raise ScopeAttenuationError(
            f"orphan authority: child ttl {child_ttl} exceeds parent ttl {parent.ttl}"
        )
    if not child_audience <= parent.audience:
        raise ScopeAttenuationError(
            f"audience escalation: {sorted(child_audience - parent.audience)}"
        )

    return Token(
        scope=child_scope,
        constraints=child_constraints,
        audience=child_audience,
        ttl=child_ttl,
        depth=parent.depth + 1,
    )


def _resolve_exclusions(constraints: FrozenSet[str]) -> FrozenSet[str]:
    # Placeholder: production resolves against the resource index.
    return frozenset(c.split(":", 1)[1] for c in constraints if c.startswith("deny:"))
