# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-depth-collapse-when-a-federation-chain-crosses-an-unverified-trust-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-depth-collapse-when-a-federation-chain-crosses-an-unverified-trust-anchor.warrant.json
# Markdown SHA-256:   f0c3a2222f5a3350ac3189a9dbbdaaea2f66f3b6048393883dd5500a13867a2e
# Code AST SHA-256:   9c14b7b33873a037313363cfcaadf56b19f43843572fc120832c2ffd0350c051
# Verified Classes:   DelegationDepthCollapse, ResolvedLink
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class DelegationDepthCollapse(RuntimeError):
    """Raised when a VC chain verifies link-by-link but its delegation-depth
    invariant is evaluated against inconsistent resolution generations."""


@dataclass(frozen=True)
class ResolvedLink:
    issuer: str
    key_generation: str
    policy_generation: str
    max_delegation_depth: int
    granted_scope: frozenset[str]


def verify_chain_against_root_anchor(
    chain: Sequence[ResolvedLink],
    root_anchor_policy: dict[str, frozenset[str]],
    terminal_action_scope: frozenset[str],
) -> None:
    # Guardrail 1: provenance uniformity across the whole chain.
    generations = {(l.key_generation, l.policy_generation) for l in chain}
    if len(generations) != 1:
        raise DelegationDepthCollapse(
            f"split resolution provenance across chain: {sorted(generations)}; "
            "refusing delegation and requiring re-establishment from root anchor"
        )

    # Guardrail 2: recompute effective scope from the ROOT anchor only,
    # ignoring intermediate policy documents that may have been loosened.
    depth = len(chain)
    effective: frozenset[str] = frozenset()
    for issuer, scope_at_depth in root_anchor_policy.items():
        if depth <= len(chain):  # depth bound enforced by root, not intermediates
            effective |= scope_at_depth

    if not terminal_action_scope.issubset(effective):
        raise DelegationDepthCollapse(
            f"terminal scope {sorted(terminal_action_scope)} not a subset of "
            f"root-anchored scope {sorted(effective)} at depth {depth}; "
            "capability creep detected despite all links verifying"
        )
