# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-outlived-its-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-outlived-its-revocation-epoch.warrant.json
# Markdown SHA-256:   1c7ba8078ffb24bb2563bcb927cd4b4aee4dffc678bd1ef0ee3fc105e9c32d4f
# Code AST SHA-256:   66ca66584caa5f0bfcc36c5124dec88542b9e26c1310cb0647d6c2f7a2e9163a
# Verified Classes:   StaleRootEpochError, RootEpochUnresolvableError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StaleRootEpochError(RuntimeError):
    """Raised when a delegated credential's root epoch is behind the published epoch."""
    pass


class RootEpochUnresolvableError(RuntimeError):
    """Raised when the root delegator's revocation feed cannot be resolved within T_stale."""
    pass


def verify_delegated_credential(cred, epoch_feed, now, t_stale_seconds=30.0):
    """
    cred: object with .root_id, .rev_epoch, .signature_chain_valid, .caveats_satisfied
    epoch_feed: callable root_id -> (current_epoch, last_published_at) or None
    """
    if not cred.signature_chain_valid:
        raise StaleRootEpochError("signature chain invalid; cannot establish provenance")

    resolved = epoch_feed(cred.root_id)
    if resolved is None:
        # Fail closed: an unreachable root is indistinguishable from a revoked one.
        raise RootEpochUnresolvableError(
            f"root {cred.root_id} epoch unresolvable; denying per fail-closed invariant"
        )

    current_epoch, last_published_at = resolved
    if (now - last_published_at).total_seconds() > t_stale_seconds:
        raise RootEpochUnresolvableError(
            f"root {cred.root_id} epoch feed stale by "
            f"{(now - last_published_at).total_seconds():.1f}s > {t_stale_seconds}s"
        )

    if cred.rev_epoch < current_epoch:
        # The critical boundary: signature valid, caveats may pass, but authority withdrawn.
        raise StaleRootEpochError(
            f"credential root {cred.root_id} at epoch {cred.rev_epoch} "
            f"is behind published epoch {current_epoch}; authority withdrawn"
        )

    if cred.rev_epoch > current_epoch:
        # A descendant claiming a future epoch is a tamper signal, not a fast path.
        raise StaleRootEpochError(
            f"credential epoch {cred.rev_epoch} exceeds published {current_epoch}; "
            f"possible re-sign under forged root state"
        )

    if not cred.caveats_satisfied:
        raise StaleRootEpochError("caveats unsatisfied at verification time")

    return True
