# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-verifies-cryptographically-but-whose-scope-narrowing-proof-was-minted.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-verifies-cryptographically-but-whose-scope-narrowing-proof-was-minted.warrant.json
# Markdown SHA-256:   f926119ccad1950ba16f0fa4b72679b48e819630d94722f63644e5ab6053b6b4
# Code AST SHA-256:   86e66debe211193e3593a5afdbe38a7f0a1ebfa794f877abc8bf4e6c873dda36
# Verified Classes:   ScopeIndeterminateError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScopeIndeterminateError(RuntimeError):
    """Raised when an AAIF delegated credential is chain-valid but its
    scope-narrowing proof is bound to an unresolvable or superseded
    capability-manifest digest. Never retryable; requires re-delegation."""
    pass


def verify_delegated_credential(cred, registry, now_epoch):
    # Phase 1: chain integrity (pure, cacheable for credential lifetime).
    if not cred.chain_verifies():
        raise ScopeIndeterminateError(
            f"chain invalid for {cred.subject}: signature/delegation broken"
        )

    # Phase 2: scope validity (NOT cacheable across manifest mutations).
    bound = cred.proof.bound_manifest_digest
    if not registry.has_digest(bound):
        raise ScopeIndeterminateError(
            f"proof bound to digest {bound!r} absent from registry window; "
            f"premise is stale and unresolvable — request fresh delegation"
        )

    parent_current = registry.current_digest(cred.parent_id)
    if parent_current is None:
        raise ScopeIndeterminateError(
            f"parent {cred.parent_id} in indeterminate revocation state; "
            f"fail closed"
        )

    if not registry.is_ancestor(bound, parent_current):
        raise ScopeIndeterminateError(
            f"proof premise {bound!r} is not an ancestor of parent's "
            f"current digest {parent_current!r}; scope over-broad"
        )

    # Recompute effective scope against LIVE parent manifest, not proof premise.
    effective = cred.proof.scope.intersect(registry.manifest(parent_current).scope)
    return effective


def resume_from_checkpoint(instance, cred, registry, now_epoch):
    try:
        effective = verify_delegated_credential(cred, registry, now_epoch)
    except ScopeIndeterminateError:
        # Hard stop: do NOT retry, do NOT delegate further from this state.
        instance.halt_and_request_redelegation(cred.parent_id)
        raise
    instance.activate(effective)
