# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-an-aaif-attested-handshake-when-the-peer-s-capability-proof-is-valid-but-its-revocation-epoch-lags-the-local-trust-ancho.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-an-aaif-attested-handshake-when-the-peer-s-capability-proof-is-valid-but-its-revocation-epoch-lags-the-local-trust-ancho.warrant.json
# Markdown SHA-256:   729e5b949259079b2bfd32581751fa6330a7a9d6eaac8275e3288fdaf361f6e3
# Code AST SHA-256:   613d47c0fb35231cc5eb245546fa6068a9826f612e0e804919c4f6cf8e22804a
# Verified Classes:   StaleCapabilityProofError, TrustAnchor, CapabilityProof
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class StaleCapabilityProofError(RuntimeError):
    """Raised when a peer capability proof predates the local revocation floor."""
    pass


@dataclass
class TrustAnchor:
    epoch: int
    # highest epoch at which each capability was revoked, as known locally
    revoke_floor: Dict[str, int] = field(default_factory=dict)

    def floor_for(self, capability: str) -> int:
        return self.revoke_floor.get(capability, 0)


@dataclass
class CapabilityProof:
    peer_id: str
    epoch: int
    capabilities: Dict[str, str]  # capability -> hash
    signature_valid: bool


def verify_handshake(
    proof: CapabilityProof,
    anchor: TrustAnchor,
    requested: list[str],
    *,
    allow_degraded: bool = True,
) -> list[str]:
    """
    Returns the set of capabilities cleared for the session warrant.
    Raises StaleCapabilityProofError if a requested capability is revoked
    at an epoch newer than the proof, unless allow_degraded drops it.
    """
    if not proof.signature_valid:
        raise StaleCapabilityProofError(
            f"peer {proof.peer_id} signature invalid"
        )

    cleared: list[str] = []
    for cap in requested:
        if cap not in proof.capabilities:
            continue  # capability not claimed at all; not a staleness fault
        floor = anchor.floor_for(cap)
        if proof.epoch < floor:
            # proof predates a revocation of this specific capability
            if not allow_degraded:
                raise StaleCapabilityProofError(
                    f"capability {cap!r} revoked at epoch {floor} "
                    f"but proof epoch is {proof.epoch} "
                    f"(local anchor {anchor.epoch})"
                )
            continue  # drop revoked capability, keep the rest
        cleared.append(cap)

    if not cleared:
        raise StaleCapabilityProofError(
            f"no capability of peer {proof.peer_id} survives "
            f"revocation floor check against anchor epoch {anchor.epoch}"
        )
    return cleared
