# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-delegated-credential-scope-exhaustion-during-multi-hop-aaif-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-delegated-credential-scope-exhaustion-during-multi-hop-aaif-task-delegation.warrant.json
# Markdown SHA-256:   8f49ec6c49cf1d38e061de670eca5c184822fd8ba71428e52c1b8b58ec62c4e5
# Code AST SHA-256:   a2c99b8f42892bb5672d9c12306c8c8504e66ec9bf41b9a2421cbffb1329c67c
# Verified Classes:   ScopeExhaustionError, Credential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

child_cred.scope = parent_cred.scope          # WRONG: copies declared, not effective

child_cred.scope = intersect(parent_cred.effective_scope, requested_scope)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeExhaustionError(RuntimeError):
    """Raised when declared scope exceeds effective (intersected) scope."""
    pass

@dataclass(frozen=True)
class Credential:
    declared: FrozenSet[str]
    attenuation_chain: tuple = field(default_factory=tuple)  # tuple of frozensets, root first

    @property
    def effective(self) -> FrozenSet[str]:
        if not self.attenuation_chain:
            return self.declared
        acc = self.attenuation_chain[0]
        for hop in self.attenuation_chain[1:]:
            acc = acc & hop
        return acc & self.declared

def delegate(parent: Credential, requested: FrozenSet[str]) -> Credential:
    """Attenuate by intersecting effective scope, propagating the chain."""
    eff = parent.effective
    granted = eff & requested
    if not granted:
        raise ScopeExhaustionError(
            f"delegation would yield empty scope: requested={set(requested)} "
            f"effective_parent={set(eff)}"
        )
    return Credential(
        declared=granted,
        attenuation_chain=parent.attenuation_chain + (granted,),
    )

def check_response(cred: Credential, required: FrozenSet[str], status: int) -> None:
    """Classify a 403 as ancestry exhaustion vs genuine capability gap."""
    if status != 403:
        return
    if required.issubset(cred.declared) and not required.issubset(cred.effective):
        raise ScopeExhaustionError(
            f"scope exhaustion by ancestry: required={set(required)} "
            f"declared={set(cred.declared)} effective={set(cred.effective)} "
            f"chain={[set(h) for h in cred.attenuation_chain]}"
        )
    # otherwise: genuine capability gap, escalate for re-consent, do not retry
