# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-scope-attenuation-when-an-a2a-task-crosses-an-oauth-2-1-token-exchange-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-scope-attenuation-when-an-a2a-task-crosses-an-oauth-2-1-token-exchange-boundary.warrant.json
# Markdown SHA-256:   86005e0089339283cf03958d6d53c77b2b59d361efa7daeebf2fa350bcfe5b7e
# Code AST SHA-256:   92dbb56bc77dc7c2df55839887f0fe970e3f62929e3054642ffd21df5bb1390b
# Verified Classes:   ScopeAttenuationViolation, IdentityAttributionViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeAttenuationViolation(RuntimeError):
    """Raised when a token-exchange response widens scope beyond the requested bound."""
    pass


class IdentityAttributionViolation(RuntimeError):
    """Raised when a delegated token lacks an act claim naming the receiving agent."""
    pass


def validate_delegated_token(
    token_claims: dict,
    requested_scope: set[str],
    expected_actor: str,
) -> None:
    granted = set(token_claims.get("scope", "").split())

    # Invariant 1: minted scope must be a subset of the scope requested for the task.
    excess = granted - requested_scope
    if excess:
        raise ScopeAttenuationViolation(
            f"token scope {sorted(granted)} exceeds requested {sorted(requested_scope)}; "
            f"excess={sorted(excess)} aud={token_claims.get('aud')}"
        )

    # Invariant 2: delegated tokens must name the acting agent in the act claim.
    act = token_claims.get("act") or {}
    if act.get("sub") != expected_actor:
        raise IdentityAttributionViolation(
            f"act.sub={act.get('sub')!r} != expected actor {expected_actor!r}; "
            f"token is not a valid delegation for this agent"
        )


def receive_exchange_response(
    response: dict,
    requested_scope: set[str],
    expected_actor: str,
) -> dict:
    claims = response.get("access_token_claims")
    if claims is None:
        raise ScopeAttenuationViolation(
            "exchange response did not include introspectable claims; "
            "cannot verify attenuation, refusing to proceed"
        )
    validate_delegated_token(claims, requested_scope, expected_actor)
    return response
