# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-transitive-scope-inflation-when-re-delegating-an-aaif-capability-attestation-across-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-transitive-scope-inflation-when-re-delegating-an-aaif-capability-attestation-across-an-org-boundary.warrant.json
# Markdown SHA-256:   270036624b26df30a26a69854044f6f1f3eb9dc345c5e2a6eb3b13e537478562
# Code AST SHA-256:   af2300397e3bc0811918019af9ae39e60da0ba834b55ea06f7e591554df7d577
# Verified Classes:   ScopeInflationError, DelegationToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeInflationError(RuntimeError):
    """Raised when a child delegation would exceed the parent's effective scope."""


@dataclass(frozen=True)
class DelegationToken:
    issuer: str
    requested_scope: FrozenSet[str]
    attested_scope: FrozenSet[str] | None
    attested_signed: bool


def derive_child_scope(parent: DelegationToken, requested_child: FrozenSet[str]) -> FrozenSet[str]:
    # An unsigned or absent attestation means we cannot prove the parent's
    # effective scope. Falling back to requested_scope is the inflation vector.
    if parent.attested_scope is None or not parent.attested_signed:
        raise ScopeInflationError(
            f"parent token from {parent.issuer} has no signed attested_scope; "
            f"cannot safely derive child scope from requested_scope={sorted(parent.requested_scope)}"
        )

    if not parent.attested_scope.issubset(parent.requested_scope):
        raise ScopeInflationError(
            f"parent attested_scope {sorted(parent.attested_scope)} is not a subset of "
            f"requested_scope {sorted(parent.requested_scope)}; token is internally inconsistent"
        )

    effective_child = requested_child & parent.attested_scope
    if effective_child != requested_child:
        # Narrowing is fine, but log it: the child asked for more than the parent
        # could prove, which is a signal the child's planner is over-reaching.
        pass
    return effective_child
