# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-peer-issued-trust-score-after-a-cross-domain-a2a-handoff-and-what-breaks-if-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-peer-issued-trust-score-after-a-cross-domain-a2a-handoff-and-what-breaks-if-it-doesn-t.warrant.json
# Markdown SHA-256:   187e058d3e904fbb6c306f0f7c6f5272ede45ea4f42197a31b82506d8fb60ae5
# Code AST SHA-256:   9f4cef04ce10cb77626074572dd7de3946b6a388cf2d5b53d9e94baa067eb26f
# Verified Classes:   StaleAttestationError, TrustAttestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a cached peer trust score is used past its currency boundary."""
    pass


@dataclass(frozen=True)
class TrustAttestation:
    peer_id: str
    issuer_id: str
    score: float
    policy_version: int
    delegation_edge_set_hash: str
    signature_valid: bool


def authorize_mutation(
    attestation: TrustAttestation,
    issuer_current_policy_version: Optional[int],
    issuer_current_edge_hash: Optional[str],
    required_score: float,
) -> bool:
    # Signature currency is necessary but nowhere near sufficient.
    if not attestation.signature_valid:
        raise StaleAttestationError(
            f"signature invalid for peer {attestation.peer_id}"
        )

    # If we cannot reach the issuer, we cannot confirm currency.
    # Fail closed on mutating actions rather than trust a snapshot.
    if issuer_current_policy_version is None or issuer_current_edge_hash is None:
        raise StaleAttestationError(
            f"issuer {attestation.issuer_id} unreachable; "
            f"cannot confirm currency of cached score for {attestation.peer_id}"
        )

    # Policy currency: a version bump may have revoked a transitive delegation
    # edge the score depends on, without touching the signature.
    if attestation.policy_version != issuer_current_policy_version:
        raise StaleAttestationError(
            f"policy_version drift for {attestation.peer_id}: "
            f"attested {attestation.policy_version}, "
            f"issuer now {issuer_current_policy_version}"
        )

    # Warrant currency: the delegation edge set that produced the score
    # must be unchanged. This is the check that catches silent revocation.
    if attestation.delegation_edge_set_hash != issuer_current_edge_hash:
        raise StaleAttestationError(
            f"delegation edge set changed for {attestation.peer_id} since attestation; "
            f"score {attestation.score} is a stale read of issuer state"
        )

    if attestation.score < required_score:
        return False

    return True
