# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-widening-during-delegated-oauth-re-delegation-across-aaif-agent-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-widening-during-delegated-oauth-re-delegation-across-aaif-agent-chains.warrant.json
# Markdown SHA-256:   90fa0850650771557338c20c965617e1dee5667695138f3daf532ac149133209
# Code AST SHA-256:   c4d2bde2a7be3f4aa4b953929aa7daf713729248972e143eb52fd420e4c22995
# Verified Classes:   AAIFScopeWideningError, AgentCredential, DelegatedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AAIFScopeWideningError(RuntimeError):
    """Raised when a delegated scope exceeds the parent's effective authority,
    or when a resource server's effective set is not the intersection of
    token scope, VAC capabilities, and resource policy."""


@dataclass(frozen=True)
class AgentCredential:
    agent_id: str
    capabilities: FrozenSet[str]  # upper bound, NOT a grant
    iat: int
    exp: int


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    scope: FrozenSet[str]
    act_chain: tuple = field(default_factory=tuple)  # nested act.sub ancestors
    iat: int = 0
    exp: int = 0


def effective_authority(
    token: DelegatedToken,
    vac: AgentCredential,
    resource_policy: FrozenSet[str],
    max_act_depth: int = 3,
    skew_seconds: int = 300,
) -> FrozenSet[str]:
    if len(token.act_chain) > max_act_depth:
        raise AAIFScopeWideningError(
            f"act chain depth {len(token.act_chain)} exceeds max {max_act_depth}; "
            "refuse at issuance, do not truncate at enforcement"
        )
    if abs(vac.iat - token.iat) > skew_seconds:
        raise AAIFScopeWideningError(
            f"VAC iat {vac.iat} not pinned to token iat {token.iat} within "
            f"{skew_seconds}s skew; stale VAC could widen effective authority"
        )
    # The invariant: intersection, never union.
    return token.scope & vac.capabilities & resource_policy


def re_delegate(
    parent_token: DelegatedToken,
    parent_vac: AgentCredential,
    child_scope: FrozenSet[str],
    child_vac: AgentCredential,
    parent_resource_policy: FrozenSet[str],
) -> DelegatedToken:
    parent_effective = effective_authority(
        parent_token, parent_vac, parent_resource_policy
    )
    # Check against the PARENT's effective authority, not the child's capabilities.
    if not child_scope.issubset(parent_effective):
        widened = child_scope - parent_effective
        raise AAIFScopeWideningError(
            f"re-delegation to {child_vac.agent_id} requests {sorted(widened)} "
            f"not held by parent {parent_vac.agent_id} "
            f"(parent effective={sorted(parent_effective)})"
        )
    return DelegatedToken(
        subject=child_vac.agent_id,
        scope=child_scope,
        act_chain=parent_token.act_chain + (parent_token.subject,),
        iat=parent_token.iat,
        exp=parent_token.exp,
    )


def enforce_request(
    token: DelegatedToken,
    vac: AgentCredential,
    requested_action: str,
    resource_policy: FrozenSet[str],
) -> None:
    effective = effective_authority(token, vac, resource_policy)
    if requested_action not in effective:
        raise AAIFScopeWideningError(
            f"action {requested_action!r} not in effective authority "
            f"{sorted(effective)} for agent {vac.agent_id}; "
            f"token.scope={sorted(token.scope)} vac.capabilities={sorted(vac.capabilities)}"
        )
