# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-attestation-whose-delegation-chain-exceeds-the-verifier-s-re-derivation-depth.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-attestation-whose-delegation-chain-exceeds-the-verifier-s-re-derivation-depth.warrant.json
# Markdown SHA-256:   d3386e9397e9bc5ae84fe2622def637da3600ea9390ee4a8779585abdeccadc5
# Code AST SHA-256:   5b7203e0c8c4f47b1a05afcd7a8ad4f13b026c5e53643ceaaabaeb0637e80324
# Verified Classes:   TruncatedRederivationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TruncatedRederivationError(RuntimeError):
    """Raised when an AAIF delegation chain cannot be fully re-derived to the root issuer."""
    pass


def verify_aaif_chain(chain, root_scope, max_rederivation_depth):
    """
    Re-derive an AAIF delegation chain. Returns the terminal scope only if the
    entire chain was walked and every hop's authority is bounded by the root.
    """
    declared_len = chain.declared_length
    observed_len = len(chain.hops)

    if declared_len != observed_len:
        # A hop was dropped in transit; do not attempt partial verification.
        raise TruncatedRederivationError(
            f"declared chain length {declared_len} != observed {observed_len}"
        )

    if observed_len > max_rederivation_depth:
        # We cannot walk to the root. Emitting VALID here would assert chain
        # validity we never established. Fail closed with INDETERMINATE.
        raise TruncatedRederivationError(
            f"chain length {observed_len} exceeds re-derivation depth "
            f"{max_rederivation_depth}; terminal scope unverified"
        )

    parent_scope = root_scope
    for i, hop in enumerate(chain.hops):
        if not verify_signature(hop):
            raise TruncatedRederivationError(f"hop {i} signature invalid")
        if not hop.scope.issubset(parent_scope):
            raise TruncatedRederivationError(
                f"hop {i} scope {hop.scope} not bounded by parent {parent_scope}"
            )
        if i + 1 < observed_len and hop.sub != chain.hops[i + 1].act:
            raise TruncatedRederivationError(
                f"hop {i} sub does not bind to hop {i + 1} act principal"
            )
        parent_scope = hop.scope

    return chain.hops[-1].scope
