# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-credential-chain-when-scope-narrowing-is-unverifiable-at-the-leaf.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-credential-chain-when-scope-narrowing-is-unverifiable-at-the-leaf.warrant.json
# Markdown SHA-256:   d7990a9b600257071040ef8d26f6b16c58329264ec2b83abbedf5e876b85a098
# Code AST SHA-256:   c03e382e93c3b26aa3e51f5db8c39c2c06d1dbed03c6fe5fc10ed4d716b5c1ff
# Verified Classes:   ScopeNarrowingUnverifiable
# Defensive Guards:   9 fail-closed invariants (zero external deps)

class ScopeNarrowingUnverifiable(RuntimeError):
    """Raised when a leaf cannot prove its scope is a subset of its parent's
    scope from signed, hash-bound credential bytes alone."""


def verify_delegated_chain(chain, leaf_scope):
    """
    chain: list of hops, root -> ... -> leaf.
    Each hop: {
        'issuer': str,
        'subject': str,
        'scope': set | None,          # inline scope, if materialized
        'scope_ref': str | None,      # opaque pointer, if used
        'scope_ref_hash': str | None, # hash binding, if present
        'signature_valid': bool,
        'expired': bool,
    }
    leaf_scope: the scope set the executing instance intends to exercise.
    """
    for hop in chain:
        if not hop["signature_valid"]:
            raise ScopeNarrowingUnverifiable(
                f"chain broken: hop {hop['issuer']}->{hop['subject']} signature invalid"
            )
        if hop["expired"]:
            raise ScopeNarrowingUnverifiable(
                f"chain expired at hop {hop['issuer']}->{hop['subject']}"
            )

    # Walk parent->child and enforce subset at every hop we can verify.
    parent_scope = None
    for hop in chain:
        child = hop["scope"]
        if child is not None:
            # inline scope: subset is directly checkable
            if parent_scope is not None and not child.issubset(parent_scope):
                raise ScopeNarrowingUnverifiable(
                    f"scope widened at {hop['subject']}: "
                    f"{child - parent_scope} not granted by parent"
                )
            parent_scope = child
            continue

        # opaque scope reference: only acceptable if hash-bound
        if hop["scope_ref"] is not None:
            if hop["scope_ref_hash"] is None:
                raise ScopeNarrowingUnverifiable(
                    f"hop {hop['subject']} uses unbound scope_ref {hop['scope_ref']}; "
                    "subset relation unprovable at leaf — refusing to execute"
                )
            # hash-bound: resolution must be verified against the hash before use;
            # if we cannot resolve-and-verify locally, we still cannot prove subset
            resolved = resolve_scope_ref(hop["scope_ref"])
            if resolved is None or hash_scope(resolved) != hop["scope_ref_hash"]:
                raise ScopeNarrowingUnverifiable(
                    f"hop {hop['subject']} scope_ref failed hash binding; "
                    "resolved bundle does not match credential"
                )
            if parent_scope is not None and not resolved.issubset(parent_scope):
                raise ScopeNarrowingUnverifiable(
                    f"resolved scope at {hop['subject']} exceeds parent"
                )
            parent_scope = resolved
            continue

        raise ScopeNarrowingUnverifiable(
            f"hop {hop['subject']} carries neither inline scope nor scope_ref"
        )

    if parent_scope is None:
        raise ScopeNarrowingUnverifiable("no verifiable scope found in chain")

    if not leaf_scope.issubset(parent_scope):
        raise ScopeNarrowingUnverifiable(
            f"leaf scope {leaf_scope - parent_scope} not covered by chain"
        )
    return True


def resolve_scope_ref(ref):
    # out-of-band resolution; caller must hash-verify the result
    ...


def hash_scope(scope_set):
    ...
