# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-exchanges-a-delegated-token-for-a-scope-it-can-only-partially-satisfy-the-aaif-attenuation-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-exchanges-a-delegated-token-for-a-scope-it-can-only-partially-satisfy-the-aaif-attenuation-gap.warrant.json
# Markdown SHA-256:   17dfbb5faed0fc326e5d24e5af18df3301fee07e07655ea839ecd2842c4af18c
# Code AST SHA-256:   1fce83c407296213d9765ebf724a90f8ef01d954b06f1f69df6e49219c9e3129
# Verified Classes:   AttenuationGapError, DelegatedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class AttenuationGapError(RuntimeError):
    """Raised when an agent attempts to act outside the effective scope of an exchanged token,
    or falls back to presenting a pre-exchange token after a denied exchange."""


@dataclass
class DelegatedToken:
    subject: str
    scope: frozenset[str]
    act_chain: tuple[str, ...] = field(default_factory=tuple)

    def __post_init__(self) -> None:
        if len(set(self.act_chain)) != len(self.act_chain):
            raise AttenuationGapError(
                f"self-delegation loop in act chain: {self.act_chain}"
            )


def exchange(
    presented: DelegatedToken,
    requested_scope: set[str],
    exchange_actor: str,
) -> DelegatedToken:
    req = frozenset(requested_scope)
    if not req.issubset(presented.scope):
        # C1: the authorization server refuses to widen authority.
        # The caller MUST NOT fall back to presenting `presented` — that token
        # carries a different actor and broader authority than requested.
        raise AttenuationGapError(
            f"invalid_scope: requested {sorted(req)} not subset of "
            f"presented {sorted(presented.scope)}; do not present pre-exchange token"
        )
    return DelegatedToken(
        subject=presented.subject,
        scope=req,
        act_chain=presented.act_chain + (exchange_actor,),
    )


def authorize_action(token: DelegatedToken, action_scope: str) -> None:
    # C3: authority is the *effective* (response) scope, never the requested scope.
    if action_scope not in token.scope:
        raise AttenuationGapError(
            f"action {action_scope!r} outside effective scope {sorted(token.scope)} "
            f"for actor {token.act_chain[-1] if token.act_chain else token.subject}"
        )


# Trace replay of the observed failure:
root = DelegatedToken("O", frozenset({"repo:read", "repo:write", "issues:write"}))
t1 = exchange(root, {"repo:read", "issues:write"}, exchange_actor="P")
try:
    # E requests a scope exceeding T1 — must be denied, must not fall back.
    t2 = exchange(t1, {"repo:read", "repo:write", "issues:write"}, exchange_actor="E")
except AttenuationGapError as denied:
    # Correct behavior: abort, do not present t1. A fallback here would execute
    # a repo:write under P's identity — the confused-deputy leak.
    print(f"aborted sub-task: {denied}")
