# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-exchange-that-is-cryptographically-valid-but-semantically-unbound.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-exchange-that-is-cryptographically-valid-but-semantically-unbound.warrant.json
# Markdown SHA-256:   dd3eaea5145f058a7b40f578fa9d066c675dc45e996e64417dc8554ddeeb24c9
# Code AST SHA-256:   339cf358de4c08213e6e841053d19f5794c5984e306803685f2183fc0e39c6bf
# Verified Classes:   DelegationBindingError, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationBindingError(RuntimeError):
    """Raised when a token exchange would mint a token whose scopes are not
    bound to the original subject grant (scope-subject decoupling)."""


@dataclass(frozen=True)
class Token:
    sub: str
    scope: FrozenSet[str]
    act_chain: tuple = field(default_factory=tuple)  # outermost actor first


def exchange(
    parent: Token,
    requested: FrozenSet[str],
    requester_allowed: FrozenSet[str],
    subject_grant: FrozenSet[str],
    requester_id: str,
    redelegation_allowed: bool = False,
) -> Token:
    # 1. Registry check: requester may only request what it is permitted to request.
    if not requested.issubset(requester_allowed):
        raise DelegationBindingError(
            f"requester {requester_id} requested scopes outside allowed_scopes: "
            f"{requested - requester_allowed}"
        )

    # 2. Monotonic narrowing against the immediate parent token.
    if not requested.issubset(parent.scope):
        # Widening across a hop is only legal if the subject explicitly
        # authorized re-delegation to this requester.
        if not redelegation_allowed:
            raise DelegationBindingError(
                f"requested {requested - parent.scope} exceeds parent scope "
                f"{parent.scope} and no re-delegation grant for {requester_id}"
            )

    # 3. Binding invariant: the parent token itself must be within the
    #    subject grant, or it is tainted and must not be laundered.
    if not parent.scope.issubset(subject_grant):
        raise DelegationBindingError(
            f"parent token scope {parent.scope - subject_grant} exceeds subject "
            f"grant {subject_grant}; parent is tainted, refusing to mint child"
        )

    # 4. Final scope must be within the subject grant regardless of path.
    if not requested.issubset(subject_grant):
        raise DelegationBindingError(
            f"requested {requested - subject_grant} is not delegated by subject "
            f"{parent.sub}"
        )

    return Token(
        sub=parent.sub,
        scope=requested,
        act_chain=(requester_id,) + parent.act_chain,
    )
