# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-widened-its-scope-during-aaif-credential-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-widened-its-scope-during-aaif-credential-exchange.warrant.json
# Markdown SHA-256:   f0fe31617f2c48fa213c940033a938eae6778a1640c6d37fb7a01eb5a7649c53
# Code AST SHA-256:   80e428dd634b70b776f29eb093d1bfabb34cb3ee4c82ce920846e5e52d968c61
# Verified Classes:   ScopeAttenuationViolation, MissingScopeCeiling
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeAttenuationViolation(RuntimeError):
    """Raised when a delegated token's effective scope exceeds its declared scope."""
    pass


class MissingScopeCeiling(RuntimeError):
    """Raised when a delegated token lacks the scope_ceiling claim required for safe exchange."""
    pass


def verify_attenuation(
    declared_scope: frozenset[str],
    scope_ceiling: frozenset[str] | None,
    parent_effective_scope: frozenset[str],
    resolver_effective_scope: frozenset[str],
    chain_depth: int,
) -> frozenset[str]:
    """
    Enforce the AAIF attenuation invariant at the credential-exchange boundary.

    Returns the verified effective scope (declared ∩ ceiling ∩ parent).
    Raises on any structural signal of widening.
    """
    if scope_ceiling is None:
        # A child token without a ceiling claim is the structural tell that a
        # union-defaulting resolver will widen the scope at the next hop.
        raise MissingScopeCeiling(
            f"delegated token at depth {chain_depth} has no scope_ceiling claim; "
            f"refusing exchange to prevent scope drift"
        )

    # The locally re-derived intersection is the only trustworthy basis.
    derived = declared_scope & scope_ceiling & parent_effective_scope

    # The resolver's answer must not exceed the derived intersection.
    if not resolver_effective_scope.issubset(derived):
        widened = resolver_effective_scope - derived
        raise ScopeAttenuationViolation(
            f"resolver widened scope at depth {chain_depth}: "
            f"effective_scope includes {sorted(widened)} not present in "
            f"declared ∩ ceiling ∩ parent"
        )

    # Over-attenuation is safe but should be surfaced for config review.
    if resolver_effective_scope < derived:
        # Caller may log this; not fatal.
        pass

    return derived


def delegate(
    parent_effective_scope: frozenset[str],
    requested_scope: frozenset[str],
    chain_depth: int,
) -> dict:
    """Issue a child token with an explicit ceiling equal to the requested scope."""
    if not requested_scope.issubset(parent_effective_scope):
        raise ScopeAttenuationViolation(
            f"requested scope {sorted(requested_scope - parent_effective_scope)} "
            f"exceeds parent effective scope at depth {chain_depth}"
        )
    return {
        "scope": " ".join(sorted(requested_scope)),
        "scope_ceiling": " ".join(sorted(requested_scope)),
        "parent_scope_ref": True,  # placeholder for parent token ID
        "chain_depth": chain_depth + 1,
    }
