# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-warrant-after-its-issuer-s-revocation-epoch-has-advanced.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-warrant-after-its-issuer-s-revocation-epoch-has-advanced.warrant.json
# Markdown SHA-256:   99541056dd7734932cd5482db27d20dc08a055be68563baf6d7fa84adfb40479
# Code AST SHA-256:   e5727a7823ac1f0d6912b1a52880a587459b62828be4d110d3de14f5fa9943e5
# Verified Classes:   StaleWarrantReDerivationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleWarrantReDerivationError(RuntimeError):
    """Raised when an agent attempts to re-derive a delegated warrant
    without a fresh epoch attestation covering the full ancestry."""
    pass


def rederive_warrant(leaf, ancestry_epochs, attest_fn):
    # leaf: dict with issuer, subject, scope, not_after, recorded_epoch,
    #       parent_epoch (epoch of the immediate parent link at issuance)
    # ancestry_epochs: list of ancestor ids, root-first
    # attest_fn: callable(ancestor_id) -> current epoch or None if unreachable

    live = {}
    for ancestor in ancestry_epochs:
        epoch = attest_fn(ancestor)
        if epoch is None:
            raise StaleWarrantReDerivationError(
                f"epoch attestation unreachable for ancestor {ancestor!r}; "
                f"cannot re-derive leaf for {leaf['subject']!r} — fail closed"
            )
        live[ancestor] = epoch

    max_live = max(live.values()) if live else 0
    if max_live > leaf["recorded_epoch"]:
        raise StaleWarrantReDerivationError(
            f"ancestry epoch advanced to {max_live} but leaf records "
            f"{leaf['recorded_epoch']} (parent epoch {leaf['parent_epoch']}); "
            f"re-derivation would launder a revocation — re-issue instead"
        )

    if leaf["recorded_epoch"] != leaf["parent_epoch"]:
        raise StaleWarrantReDerivationError(
            f"leaf epoch {leaf['recorded_epoch']} inconsistent with parent "
            f"epoch {leaf['parent_epoch']}; chain integrity violated"
        )

    # Safe to mint a successor leaf only now.
    return {**leaf, "rederived": True, "epoch_verified_at": max_live}
