# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegated-credential-chain-in-aaif-agent-identity-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegated-credential-chain-in-aaif-agent-identity-attestation.warrant.json
# Markdown SHA-256:   32bcd67e71c627f9b5cbe15553b56f272f7b7da112a461c0db0bf1c096e13310
# Code AST SHA-256:   20eff2058c58d47c2213bf948ff6538a8fc974c6f78b198be3fd4d58a314d1ea
# Verified Classes:   ChainAuthorityIncoherent, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet

class ChainAuthorityIncoherent(RuntimeError):
    """Raised when a delegated credential chain's effective grant is not a
    monotone narrowing of the principal's grant, even if all signatures verify."""

@dataclass(frozen=True)
class Hop:
    parent_digest: str
    granted: FrozenSet[str]          # what this hop claims to hold
    removed: FrozenSet[str]          # what this hop claims to remove from parent
    delegation_depth: int
    signature_valid: bool

def fold_chain(principal_grant: FrozenSet[str], hops: list[Hop],
               max_depth: int) -> FrozenSet[str]:
    effective = principal_grant
    prev_depth = max_depth
    for i, hop in enumerate(hops):
        if not hop.signature_valid:
            raise ChainAuthorityIncoherent(f"hop {i}: signature invalid")
        # narrowing must be expressed as removal only
        if not hop.removed <= effective:
            raise ChainAuthorityIncoherent(
                f"hop {i}: removed set {hop.removed} not subset of parent {effective}")
        narrowed = effective - hop.removed
        # the hop's self-asserted grant must equal the recomputed narrowing
        if hop.granted != narrowed:
            raise ChainAuthorityIncoherent(
                f"hop {i}: asserted grant {hop.granted} != recomputed {narrowed} "
                "(scope-widening or canonicalization drift)")
        # depth must strictly decrease across re-delegation
        if hop.delegation_depth >= prev_depth:
            raise ChainAuthorityIncoherent(
                f"hop {i}: depth {hop.delegation_depth} not < parent {prev_depth} "
                "(depth reset on re-mint)")
        effective = narrowed
        prev_depth = hop.delegation_depth
    return effective
