# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-token-replay-across-did-authenticated-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-token-replay-across-did-authenticated-agent-handoffs.warrant.json
# Markdown SHA-256:   0675c4a98aee8c1cfc3d5ac605ceeb0d5d4e7c4ce098466d37ecd49588ce8455
# Code AST SHA-256:   69fc183264f5cd85bb6894bff8fba050b27f2a2305d618882532e16380e8c261
# Verified Classes:   CapabilityReplayError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityReplayError(RuntimeError):
    """Raised when a capability token is presented under an execution epoch
    that precedes the verifier's recorded epoch floor for its audience."""


def verify_capability(token, presenter_did, epoch_registry):
    # Step 1: DID proof-of-possession (unchanged, and insufficient alone).
    if not token.verify_signature(presenter_did):
        raise CapabilityReplayError(
            f"signature invalid for presenter {presenter_did}"
        )

    # Step 2: scope and expiry (unchanged, and insufficient alone).
    if token.is_expired() or not token.covers(presenter_did):
        raise CapabilityReplayError("scope or expiry check failed")

    # Step 3: the invariant that actually bounds replay.
    floor = epoch_registry.get_floor(token.aud)
    if token.epoch < floor:
        raise CapabilityReplayError(
            f"replay: token epoch {token.epoch} < floor {floor} "
            f"for aud {token.aud}"
        )
    if token.jti in epoch_registry.seen_jtis(token.aud):
        raise CapabilityReplayError(
            f"replay: jti {token.jti} already spent for aud {token.aud}"
        )

    epoch_registry.record_spend(token.aud, token.jti, token.epoch)
    return True
