# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-an-attenuated-aaif-capability-token-whose-revocation-epoch-trails-the-issuer-s-by-more-than-one-del.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-an-attenuated-aaif-capability-token-whose-revocation-epoch-trails-the-issuer-s-by-more-than-one-del.warrant.json
# Markdown SHA-256:   d1229b3ba6cd5aae626cc9c6044a48e5e6841fc03ea4307ee3198bfada12497d
# Code AST SHA-256:   fe768e147ce85cee85c8cd151c6900fe04f3eca6223e0f009b4218ec2915fefc
# Verified Classes:   StaleEpochError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleEpochError(RuntimeError):
    """Raised when a delegated AAIF token's revocation epoch cannot be proven
    fresh relative to the root authority at the moment of use."""


def verify_attenuated_token(token, root_epoch_source, max_staleness: int, now: int):
    # token: dict with keys depth, rev_epoch, epoch_chain, scope, parent_scope
    if not token["scope"].issubset(token["parent_scope"]):
        raise StaleEpochError("scope escalation: child scope not subset of parent")

    root_epoch = root_epoch_source.current_epoch()  # root-signed, authoritative
    root_freshness = now - root_epoch_source.last_signed_at()

    if token["depth"] >= 2:
        # epoch chain must be monotonic non-decreasing across hops
        chain = token["epoch_chain"]
        for prev, cur in zip(chain, chain[1:]):
            if cur < prev:
                raise StaleEpochError(
                    f"epoch chain regressed at hop: {prev} -> {cur}"
                )
        # terminal epoch must be within max_staleness of root
        if token["rev_epoch"] < root_epoch - max_staleness:
            raise StaleEpochError(
                f"rev_epoch {token['rev_epoch']} trails root {root_epoch} "
                f"by more than max_staleness {max_staleness}"
            )
        if root_freshness > max_staleness:
            raise StaleEpochError(
                f"root epoch source stale by {root_freshness}s "
                f"(> {max_staleness}s); cannot prove freshness"
            )
    return True
