# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-cross-issuer-delegation-chain-that-is-individually-valid-but-collectively-unverifiable-at-the-point-of-scope-attenuation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-cross-issuer-delegation-chain-that-is-individually-valid-but-collectively-unverifiable-at-the-point-of-scope-attenuation.warrant.json
# Markdown SHA-256:   98f4c9fb58cb7406f601b09805e876fa0eb61465fc950f954eb929a3fc403b0c
# Code AST SHA-256:   36eaa70e92626e300d5776cda84a50c975da397defe2a7e2ce73211a20e6f96c
# Verified Classes:   UnanchoredDelegationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnanchoredDelegationError(RuntimeError):
    """Raised when a delegation chain is pairwise-valid but not root-anchored."""
    pass


def verify_chain(chain, root_grant_for_first_hop):
    """
    chain: list of hops, each with .issuer, .scope (set), .signature_valid, .aud_ok, .not_expired
    root_grant_for_first_hop: the scope set the trust root actually recorded
    for the first-hop intermediary. None if unavailable.
    """
    if root_grant_for_first_hop is None:
        raise UnanchoredDelegationError(
            "no root-anchored effective grant available; chain is only pairwise valid"
        )

    for i, hop in enumerate(chain):
        if not (hop.signature_valid and hop.aud_ok and hop.not_expired):
            raise UnanchoredDelegationError(
                f"hop {i} ({hop.issuer}) failed local validity"
            )
        if i > 0 and not hop.scope.issubset(chain[i - 1].scope):
            raise UnanchoredDelegationError(
                f"hop {i} ({hop.issuer}) scope {hop.scope} not subset of parent {chain[i-1].scope}"
            )

    terminal_scope = chain[-1].scope
    if not terminal_scope.issubset(root_grant_for_first_hop):
        raise UnanchoredDelegationError(
            f"terminal scope {terminal_scope} not contained in root grant "
            f"{root_grant_for_first_hop}; intermediate scope transformation "
            f"broke root anchoring"
        )

    return True
