# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-audience-substitution-in-delegated-capability-tokens-when-a-downstream-agent-re-mints-a-short-lived-credential-for-a-sibli.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-audience-substitution-in-delegated-capability-tokens-when-a-downstream-agent-re-mints-a-short-lived-credential-for-a-sibli.warrant.json
# Markdown SHA-256:   fa733838bccde1762b522700a3dc9415c102624101581597efd75eadecef0a4d
# Code AST SHA-256:   d09f6b2e04225e89a6813f074074764cb5ee3dd2dc1aeded8b2dba64ae0817b6
# Verified Classes:   AudienceSubstitutionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AudienceSubstitutionError(RuntimeError):
    """Raised when a delegation request exceeds the root principal's authority."""
    pass


def validate_delegation_request(
    inbound_token: dict,
    requested_aud: str,
    requested_scope: list[str],
    root_policy: dict,
) -> dict:
    act_chain = inbound_token["act"]
    root = act_chain[0]

    # 1. Audience must be in the caller's declared delegation set.
    allowed_auds = inbound_token.get("may_delegate_to", [])
    if requested_aud not in allowed_auds:
        raise AudienceSubstitutionError(
            f"audience {requested_aud!r} not in may_delegate_to={allowed_auds!r} "
            f"for caller act={act_chain!r}"
        )

    # 2. Scope must be a subset of the transitive intersection, not the
    #    caller's grantable set.
    effective = set(root_policy["scope"])
    for hop in act_chain[1:]:
        effective &= set(hop.get("scope", []))
    effective &= set(inbound_token.get("scope", []))
    if not set(requested_scope).issubset(effective):
        raise AudienceSubstitutionError(
            f"scope {requested_scope!r} exceeds transitive intersection "
            f"{sorted(effective)!r} rooted at {root!r}"
        )

    # 3. act depth bound is anchored at the root principal, not the caller.
    if len(act_chain) + 1 > root_policy.get("max_act_depth", 1):
        raise AudienceSubstitutionError(
            f"act depth {len(act_chain) + 1} exceeds root max_act_depth="
            f"{root_policy.get('max_act_depth', 1)} for {root!r}"
        )

    return {
        "sub": inbound_token["sub"],
        "aud": requested_aud,
        "scope": requested_scope,
        "act": act_chain + [inbound_token["sub"]],
    }
