# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-aaif-credential-chain-at-the-delegation-depth-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-aaif-credential-chain-at-the-delegation-depth-boundary.warrant.json
# Markdown SHA-256:   dd9f477dc1ffd1c8a63d2e328e9f263ba41a2cd0b0be4820eb65a55980b622b6
# Code AST SHA-256:   72783295a68cb76c0685eead49d9fa1e033d11ae896a5db397d9cbf8e8b49c32
# Verified Classes:   CredentialChainViolation, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass

class CredentialChainViolation(RuntimeError):
    """Raised when an AAIF credential chain is cryptographically intact
    but violates scope attenuation or delegation-depth bounds."""

@dataclass
class Credential:
    issuer: str
    subject: str
    scopes: frozenset[str]
    declared_depth: int
    max_delegation_depth: int
    signature_valid: bool

def verify_chain(chain: list[Credential]) -> None:
    # Cryptographic provenance check (necessary, not sufficient).
    for parent, child in zip(chain, chain[1:]):
        if not (parent.signature_valid and child.signature_valid):
            raise CredentialChainViolation("signature invalid in chain")
        if child.issuer != parent.subject:
            raise CredentialChainViolation(
                f"issuer {child.issuer} does not match parent subject {parent.subject}"
            )

    root = chain[0]
    if root.declared_depth != 0:
        raise CredentialChainViolation("root credential must declare depth 0")

    # Recompute depth from the chain; never trust declared_depth alone.
    effective_scopes = set(root.scopes)
    for idx, cred in enumerate(chain[1:], start=1):
        if idx > root.max_delegation_depth:
            raise CredentialChainViolation(
                f"chain depth {idx} exceeds root max_delegation_depth "
                f"{root.max_delegation_depth}"
            )
        if cred.declared_depth != idx:
            raise CredentialChainViolation(
                f"declared depth {cred.declared_depth} != recomputed depth {idx}"
            )
        # Transitive attenuation: child scopes must be subset of the
        # intersection of all ancestor scopes, not just the immediate parent.
        if not cred.scopes.issubset(effective_scopes):
            extra = cred.scopes - effective_scopes
            raise CredentialChainViolation(
                f"scope escalation at depth {idx}: {sorted(extra)} not held by ancestors"
            )
        effective_scopes &= cred.scopes
        if not effective_scopes:
            raise CredentialChainViolation(
                f"authority fully attenuated at depth {idx}; leaf operation unbacked"
            )
