# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-scope-that-verifies-cryptographically-but-exceeds-the-delegation-depth-the-issuer-intended.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-scope-that-verifies-cryptographically-but-exceeds-the-delegation-depth-the-issuer-intended.warrant.json
# Markdown SHA-256:   728534464ff28160479e095d5228eb45c0825e9ae0291c299ee2e98faf48fa91
# Code AST SHA-256:   155bbbe32d159b0048534222c35762d8e1c5463628d6d9f03093815dda6917a7
# Verified Classes:   DelegationChainViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class DelegationChainViolation(RuntimeError):
    """Raised when a AAIF credential chain verifies cryptographically but the
    effective scope is not a subset of the intersection of all ancestor scopes,
    or the chain exceeds the root's declared maxDelegationDepth."""
    pass


def verify_delegated_scope(chain, requested_scope):
    # chain: list of VCs ordered root -> leaf. Each VC has .issuer, .subject,
    # .scope (set[str]), .max_delegation_depth (int | None), .signature_ok (bool)
    if not chain:
        raise DelegationChainViolation("empty chain: no principal to anchor trust")

    for i, vc in enumerate(chain):
        if not vc.signature_ok:
            raise DelegationChainViolation(f"hop {i}: bad signature")

    root = chain[0]
    depth_limit = root.max_delegation_depth
    if depth_limit is not None and len(chain) - 1 > depth_limit:
        raise DelegationChainViolation(
            f"chain depth {len(chain) - 1} exceeds root maxDelegationDepth {depth_limit}"
        )

    effective = set(root.scope)
    for i, vc in enumerate(chain[1:], start=1):
        if not set(vc.scope).issubset(effective):
            raise DelegationChainViolation(
                f"hop {i}: scope {sorted(vc.scope)} not subset of parent "
                f"effective {sorted(effective)} (composition widening)"
            )
        effective &= set(vc.scope)

    if not set(requested_scope).issubset(effective):
        raise DelegationChainViolation(
            f"requested {sorted(requested_scope)} not covered by effective "
            f"intersection {sorted(effective)}"
        )

    # A valid signature chain is evidence, not authorization. Only the
    # computed intersection authorizes execution.
    return frozenset(effective)
