# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-attestation-chain-is-cryptographically-valid-but-semantically-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-attestation-chain-is-cryptographically-valid-but-semantically-stale.warrant.json
# Markdown SHA-256:   65a967e3f6e90cd576cf864771c0bbfbe3140becef0292f4c8e5c4691800a689
# Code AST SHA-256:   84940d715034498d6999d00c08b8c8b0205da90360bf819dd374b1dff0cb1d33
# Verified Classes:   StaleAttestationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleAttestationError(RuntimeError):
    """Raised when a delegated credential's chain verifies but its authority has decayed."""
    pass


def verify_delegated_warrant(chain, issuer_state, *, mutating: bool) -> None:
    """
    Enforce AAIF conditions 1-5. issuer_state exposes current_epoch() and
    supersession_set(). Raises StaleAttestationError on any currency failure.
    """
    # Conditions 1-2: signature + temporal bounds (assumed checked upstream)
    leaf = chain[-1]
    issuer = chain[-2].issuer if len(chain) > 1 else leaf.issuer

    # Condition 5: reject laundered re-attestations
    for hop in chain:
        if hop.is_reattestation and not hop.laundered_flag_cleared:
            raise StaleAttestationError(
                f"re-attestation hop {hop.id} lacks issuer epoch re-query; "
                f"freshness is laundered"
            )

    # Condition 3: epoch currency against LIVE issuer state
    live_epoch = issuer_state.current_epoch(issuer)
    if leaf.epoch < live_epoch:
        raise StaleAttestationError(
            f"leaf epoch {leaf.epoch} < issuer current epoch {live_epoch}; "
            f"delegation superseded"
        )

    # Condition 4: scope non-supersession
    if leaf.scope_digest in issuer_state.supersession_set(issuer):
        raise StaleAttestationError(
            f"scope {leaf.scope_digest} revoked by issuer {issuer}"
        )

    # Fail-closed on unverifiable epoch for mutations
    if mutating and live_epoch is None:
        raise StaleAttestationError(
            "issuer epoch unreachable; refusing mutating action under stale warrant"
        )
