# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-capability-manifest-after-oauth-token-exchange-and-why-the-exchange-result-alone-is-not-a-proof-of-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-capability-manifest-after-oauth-token-exchange-and-why-the-exchange-result-alone-is-not-a-proof-of-scope.warrant.json
# Markdown SHA-256:   63f508372d6fb6874569e94a486ce76e24d5180928139100e7a5dcf765213dfc
# Code AST SHA-256:   0578c090b920bb9f3bbb7c341eea2ba2411eec0e327e6f6c075d7b89b40547c6
# Verified Classes:   DelegationScopeViolation, Delegation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationScopeViolation(RuntimeError):
    """Raised when token scopes are inconsistent with the signed manifest or plan."""


@dataclass(frozen=True)
class Delegation:
    manifest_requested: FrozenSet[str]
    token_granted: FrozenSet[str]
    resource_server_allowed: FrozenSet[str]
    plan_required: FrozenSet[str]
    delegation_depth: int


def verify_delegation(d: Delegation, max_depth: int = 2) -> FrozenSet[str]:
    if d.delegation_depth > max_depth:
        raise DelegationScopeViolation(
            f"delegation_depth {d.delegation_depth} exceeds max {max_depth}"
        )

    widened = d.token_granted - d.manifest_requested
    if widened:
        raise DelegationScopeViolation(
            f"scope widening: token grants undeclared scopes {sorted(widened)}"
        )

    narrowed = d.plan_required - d.token_granted
    if narrowed:
        # Terminal: do not retry; renegotiate the delegation.
        raise DelegationScopeViolation(
            f"scope narrowing: plan requires {sorted(narrowed)} not in token; "
            "delegation infeasible, do not retry"
        )

    inconsistent = d.token_granted - d.resource_server_allowed
    if inconsistent:
        raise DelegationScopeViolation(
            f"federation inconsistency: AS granted {sorted(inconsistent)} "
            "but resource server policy forbids them"
        )

    effective = d.token_granted & d.manifest_requested & d.resource_server_allowed
    if not d.plan_required <= effective:
        raise DelegationScopeViolation(
            f"effective authority {sorted(effective)} insufficient for plan"
        )
    return effective
