# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-resolve-a-peer-s-reputation-attestation-mid-handoff-the-stale-attestation-replay-window-in-a2a-mcp-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-resolve-a-peer-s-reputation-attestation-mid-handoff-the-stale-attestation-replay-window-in-a2a-mcp-federation.warrant.json
# Markdown SHA-256:   404de5e05e45081a598e9b1eb9098acd8ecc9662b6db143dc0e5d3c170952a9d
# Code AST SHA-256:   0589e7c351e56b1a7f121e97a43548066137184f67693f5848109a9bb8d2e877
# Verified Classes:   AttestationSubstitutionError, TerminalAttestationExpiry, Attestation, HandoffToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class AttestationSubstitutionError(RuntimeError):
    """Raised when a re-resolved attestation changes peer identity mid-handoff."""


class TerminalAttestationExpiry(RuntimeError):
    """Raised when a pinned attestation has expired; handoff must return to planner."""


@dataclass(frozen=True)
class Attestation:
    peer_name: str
    instance_id: str
    epoch: int
    valid_until: float
    issuer_pubkey: str
    lineage_hash: str


@dataclass(frozen=True)
class HandoffToken:
    token_id: str
    pinned_epoch: int
    pinned_instance_id: str
    pinned_issuer_pubkey: str


def validate_pinned_attestation(
    token: HandoffToken,
    candidate: Attestation,
    now: float,
    warm_lineage_ok: bool,
) -> None:
    # 1. Expiry is terminal. Never re-resolve as a side effect of expiry.
    if now > candidate.valid_until:
        raise TerminalAttestationExpiry(
            f"pinned attestation epoch {token.pinned_epoch} expired at "
            f"{candidate.valid_until}; return handoff {token.token_id} to planner"
        )

    # 2. Identity continuity: instance_id must match, not just peer_name.
    if candidate.instance_id != token.pinned_instance_id:
        raise AttestationSubstitutionError(
            f"peer {candidate.peer_name} resolved to instance "
            f"{candidate.instance_id!r} but handoff pinned "
            f"{token.pinned_instance_id!r} (epoch {token.pinned_epoch} -> "
            f"{candidate.epoch}); refusing to execute on substituted peer"
        )

    # 3. Epoch must not advance under a pinned token unless explicitly re-issued.
    if candidate.epoch != token.pinned_epoch:
        raise AttestationSubstitutionError(
            f"epoch advanced {token.pinned_epoch} -> {candidate.epoch} under "
            f"pinned handoff {token.token_id}; re-planning required"
        )

    # 4. Issuer must match the pinned trust root.
    if candidate.issuer_pubkey != token.pinned_issuer_pubkey:
        raise AttestationSubstitutionError(
            f"issuer rotated {token.pinned_issuer_pubkey[:8]}... -> "
            f"{candidate.issuer_pubkey[:8]}... under pinned handoff; "
            f"cross-org trust root change requires re-planning"
        )

    # 5. Lineage warmth: replica must carry the auditor's warm attestation.
    if not warm_lineage_ok:
        raise AttestationSubstitutionError(
            f"instance {candidate.instance_id!r} lacks warm lineage "
            f"{candidate.lineage_hash[:12]}...; auditor replay would fail"
        )
