# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-scope-when-a-per-tool-token-exchange-silently-widens-the-effective-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-scope-when-a-per-tool-token-exchange-silently-widens-the-effective-capability-set.warrant.json
# Markdown SHA-256:   ce180a71a37c18f978abbc6de63ea79675e1074d1cf81d36b7b7df9c4af5ee8b
# Code AST SHA-256:   377694ada1ca95e5867e24ab422c1d17121b7cd2f3aa90e3b36f20fc98171d9c
# Verified Classes:   ScopeWideningError, Token, DelegationChain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when an exchanged token's scope is not a subset of the delegation chain's effective scope."""


@dataclass(frozen=True)
class Token:
    scope: FrozenSet[str]
    auxiliary_claims: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class DelegationChain:
    delegated_scope: FrozenSet[str]
    exchanges: list = field(default_factory=list)  # list[Token], most recent last

    def effective_delegated_scope(self) -> FrozenSet[str]:
        # Attenuation is monotone: each exchange may only remove capabilities.
        scope = self.delegated_scope
        for tok in self.exchanges:
            scope = scope & tok.scope
        return scope


def verify_token_against_chain(chain: DelegationChain, token: Token) -> None:
    if not chain.exchanges:
        raise ScopeWideningError(
            "delegation chain is empty; token cannot be validated against a delegation"
        )
    delegated = chain.effective_delegated_scope()
    if not token.scope.issubset(delegated):
        raise ScopeWideningError(
            f"token scope {sorted(token.scope)} not subset of delegated {sorted(delegated)}"
        )
    widening_claims = {c for c in token.auxiliary_claims
                       if c.startswith(("parent_", "inherited_", "session_"))}
    if widening_claims:
        raise ScopeWideningError(
            f"token carries widening auxiliary claims {sorted(widening_claims)}; "
            f"downstream authorizers may read these over scope"
        )


def guarded_tool_call(chain: DelegationChain, token: Token, tool: str) -> None:
    verify_token_against_chain(chain, token)
    # ... invoke tool with token only after subset + auxiliary-claim checks pass
    return None
