# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-dpop-bound-delegated-credential-chain-collapse-when-intermediate-aaif-hops-silently-re-sign-with-attenuated-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-dpop-bound-delegated-credential-chain-collapse-when-intermediate-aaif-hops-silently-re-sign-with-attenuated-scope.warrant.json
# Markdown SHA-256:   7b750fb976aafc980282f0beab8a64340445a05ae198288e5d57d813b4949325
# Code AST SHA-256:   360b59fd43fa73975bec008f3ef2f96e085cd313631b0d4cafb84d40c7df98db
# Verified Classes:   ScopeSubstitutionError, ChainTruncationError, Link
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence

class ScopeSubstitutionError(RuntimeError):
    """Raised when a delegated child token's scope is not a subset of its parent's."""
    pass

class ChainTruncationError(RuntimeError):
    """Raised when the delegation chain is truncated and the ceiling cannot be proven."""
    pass

# Canonical scope grammar: hierarchical, colon-delimited, '*' is a wildcard segment.
def normalize(scope: str) -> tuple[str, ...]:
    parts = scope.split(":")
    return tuple(p if p else "*" for p in parts)

def is_subset(child: str, parent: str) -> bool:
    c, p = normalize(child), normalize(parent)
    if len(c) < len(p):
        return False
    for cs, ps in zip(c, p):
        if ps == "*":
            continue
        if cs != ps:
            return False
    return True

@dataclass(frozen=True)
class Link:
    hop_id: str
    scope: frozenset[str]
    jkt: str

def verify_chain(chain: Sequence[Link], leaf_scope: frozenset[str],
                 leaf_jkt: str, expected_root_len: int) -> None:
    if len(chain) < expected_root_len:
        raise ChainTruncationError(
            f"chain length {len(chain)} < expected {expected_root_len}; "
            "cannot prove authority ceiling"
        )
    # Leaf must be subset of its immediate parent, not the anchor.
    parent = chain[-1]
    for s in leaf_scope:
        if not any(is_subset(s, ps) for ps in parent.scope):
            raise ScopeSubstitutionError(
                f"leaf scope {s!r} not subset of parent {parent.hop_id!r} "
                f"scope {sorted(parent.scope)!r}"
            )
    if leaf_jkt != parent.jkt:
        raise ScopeSubstitutionError(
            f"leaf DPoP thumbprint {leaf_jkt!r} != parent {parent.jkt!r}"
        )
    # Walk pairwise contraction.
    for i in range(1, len(chain)):
        child, par = chain[i], chain[i - 1]
        for s in child.scope:
            if not any(is_subset(s, ps) for ps in par.scope):
                raise ScopeSubstitutionError(
                    f"hop {child.hop_id!r} scope {s!r} widens parent "
                    f"{par.hop_id!r} scope {sorted(par.scope)!r}"
                )
