# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attenuation-reversal-in-a-delegated-aaif-credential-chain-when-a-re-issued-scope-silently-widens.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attenuation-reversal-in-a-delegated-aaif-credential-chain-when-a-re-issued-scope-silently-widens.warrant.json
# Markdown SHA-256:   08fb8a68424bbf6412a061883854c6a7bf37f4d1d6fc2a7de36eb0bb60f36609
# Code AST SHA-256:   28b2a8107c5fd86777066f6288ecd9f5947631eac8ab56df6c332fb359560a9e
# Verified Classes:   AttenuationReversalError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AttenuationReversalError(RuntimeError):
    """Raised when a delegated scope is incomparable to (not a subset of) its parent."""


@dataclass(frozen=True)
class Scope:
    verbs: FrozenSet[str]
    resource_prefix: str      # parsed, not opaque: subset = prefix containment
    purposes: FrozenSet[str]
    budget: int

    def is_subset_of(self, parent: "Scope") -> bool:
        return (
            self.verbs <= parent.verbs
            and self.resource_prefix.startswith(parent.resource_prefix)
            and self.purposes <= parent.purposes
            and self.budget <= parent.budget
        )


def delegate(parent: Scope, requested: Scope, delegator: str) -> Scope:
    if not requested.is_subset_of(parent):
        # Incomparable on at least one dimension: reject at mint, do not intersect silently.
        raise AttenuationReversalError(
            f"{delegator} requested scope incomparable to parent: "
            f"resource {requested.resource_prefix!r} vs {parent.resource_prefix!r}, "
            f"purposes {sorted(requested.purposes)} vs {sorted(parent.purposes)}"
        )
    return requested


def validate_chain(chain: list[Scope]) -> Scope:
    if not chain:
        raise AttenuationReversalError("empty credential chain")
    effective = chain[0]
    for hop in chain[1:]:
        if not hop.is_subset_of(effective):
            raise AttenuationReversalError(
                f"transitive intersection violated at hop: {hop} not subset of {effective}"
            )
        effective = hop
    return effective
