# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-failure-when-an-oauth-2-1-token-exchange-silently-upgrades-a-delegated-agent-s-authority-mid-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-failure-when-an-oauth-2-1-token-exchange-silently-upgrades-a-delegated-agent-s-authority-mid-swarm.warrant.json
# Markdown SHA-256:   2745e4e4dabaef21a88857cb7ac511f8347b32ab30a5205b79844f01da33bc08
# Code AST SHA-256:   50af4c5574aa579dc673c57652dedfff2e698205781d03b779dc0e356ddbc557
# Verified Classes:   ScopeAttenuationError, EffectiveScope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated token's effective permissions are not a subset
    of the parent's effective permissions under the resource server's mapping."""


@dataclass(frozen=True)
class EffectiveScope:
    atoms: FrozenSet[str]
    permissions: FrozenSet[str]


def effective_scope(
    scope_string: str,
    rs_mapping: Mapping[str, FrozenSet[str]],
) -> EffectiveScope:
    atoms = frozenset(s for s in scope_string.split() if s)
    perms: set[str] = set()
    for atom in atoms:
        if atom not in rs_mapping:
            # Unknown atom: cannot verify attenuation. Fail closed downstream.
            raise ScopeAttenuationError(
                f"scope atom {atom!r} has no RS mapping; attenuation unverifiable"
            )
        perms |= rs_mapping[atom]
    return EffectiveScope(atoms=atoms, permissions=frozenset(perms))


def verify_attenuation(
    parent_scope: str,
    child_scope: str,
    rs_mapping: Mapping[str, FrozenSet[str]],
    operation_is_write: bool,
) -> EffectiveScope:
    parent_eff = effective_scope(parent_scope, rs_mapping)
    child_eff = effective_scope(child_scope, rs_mapping)

    # Atom-set monotonicity: the AS must not have widened the scope string.
    if not child_eff.atoms.issubset(parent_eff.atoms):
        raise ScopeAttenuationError(
            f"AS widened scope: child atoms {sorted(child_eff.atoms)} "
            f"not subset of parent {sorted(parent_eff.atoms)}"
        )

    # Effective-permission monotonicity: the RS's lattice must agree.
    leaked = child_eff.permissions - parent_eff.permissions
    if leaked:
        raise ScopeAttenuationError(
            f"semantic escalation: child grants {sorted(leaked)} "
            f"not held by parent under RS mapping"
        )

    if operation_is_write and not rs_mapping:
        raise ScopeAttenuationError(
            "write operation with empty RS scope mapping; refusing unverified delegation"
        )

    return child_eff
