# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-capability-token-s-revocation-epoch-lags-its-downstream-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-capability-token-s-revocation-epoch-lags-its-downstream-replay-window.warrant.json
# Markdown SHA-256:   47f8d9cb91183adafd13ca2937a5cac4dd6ee0255efce84754e0c2326d344128
# Code AST SHA-256:   bf29de09eb72772655ed26738c9bd2ddfdfd54da722e015540c2c7e2aa97e864
# Verified Classes:   DeadAuthorityReplayError, CapabilityToken, CachedArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DeadAuthorityReplayError(RuntimeError):
    """Raised when a cached artifact would be served under a producing
    capability whose revocation epoch has been superseded, or whose
    lineage cannot be verified at consumption time."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    issuer_id: str
    revocation_epoch: int


@dataclass(frozen=True)
class CachedArtifact:
    tool: str
    args_hash: str
    producing_token: CapabilityToken
    payload: str


def serve_cached(
    artifact: Optional[CachedArtifact],
    presenting: CapabilityToken,
    issuer_epochs: dict[str, int],
) -> str:
    """Consume a cached artifact only if its producing authority is still live
    at the consumer's verification epoch. Returns payload or re-derives."""
    if artifact is None:
        return _rederive(presenting)

    producer = artifact.producing_token

    # Lineage check: producer and presenter must resolve to a known issuer epoch.
    current = issuer_epochs.get(producer.issuer_id)
    if current is None:
        raise DeadAuthorityReplayError(
            f"issuer {producer.issuer_id!r} unreachable for epoch check; "
            f"refusing to serve artifact produced under {producer.token_id!r}"
        )

    # The boundary: producer's epoch must not be superseded.
    if producer.revocation_epoch < current:
        raise DeadAuthorityReplayError(
            f"producing token {producer.token_id!r} at epoch "
            f"{producer.revocation_epoch} is superseded by issuer epoch {current}; "
            f"artifact is a replay of dead authority"
        )

    # Cross-authority reuse is permitted only when the producer's authority is
    # live *and* lineage is shared with the presenter's issuer epoch stream.
    presenter_epoch = issuer_epochs.get(presenting.issuer_id)
    if presenter_epoch is None or presenting.revocation_epoch < presenter_epoch:
        raise DeadAuthorityReplayError(
            f"presenting token {presenting.token_id!r} fails its own epoch check"
        )

    return artifact.payload


def _rederive(presenting: CapabilityToken) -> str:
    # Safe path: recompute under the presenting (live) authority.
    return f"rederived-under:{presenting.token_id}"
