# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-before-acting-on-a-peer-s-cached-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-before-acting-on-a-peer-s-cached-warrant.warrant.json
# Markdown SHA-256:   816eabb084a8feab52462c4a011962080dedc1a9387496848982bff32c3e2b54
# Code AST SHA-256:   a6e7107e8b1809e69630fc0b3b2be22b6353a64d47a5c89f3969a8643f03c1e0
# Verified Classes:   StaleWarrantError, AttestationQuote, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when an action would proceed on a warrant whose attestation
    is not fresh relative to the action, or whose PCR set diverges."""
    pass


@dataclass
class AttestationQuote:
    peer_id: str
    pcr_digest: str
    issued_at: float
    signature_valid: bool


@dataclass
class Warrant:
    peer_id: str
    pcr_digest_at_signing: str
    issued_at: float
    scope: frozenset


def assert_warrant_fresh_for_action(
    warrant: Warrant,
    live_quote: AttestationQuote | None,
    delta_act: float,
    now: float | None = None,
) -> None:
    now = time.monotonic() if now is None else now

    if live_quote is None:
        raise StaleWarrantError(
            f"peer {warrant.peer_id}: no live quote; failing closed "
            f"(cached warrant age {now - warrant.issued_at:.1f}s)"
        )

    if not live_quote.signature_valid:
        raise StaleWarrantError(
            f"peer {warrant.peer_id}: live quote signature invalid"
        )

    if live_quote.pcr_digest != warrant.pcr_digest_at_signing:
        raise StaleWarrantError(
            f"peer {warrant.peer_id}: PCR drift — warrant signed under "
            f"{warrant.pcr_digest_at_signing[:12]}..., live state "
            f"{live_quote.pcr_digest[:12]}...; hardware identity rotated"
        )

    age = now - live_quote.issued_at
    if age > delta_act:
        raise StaleWarrantError(
            f"peer {warrant.peer_id}: quote age {age:.2f}s exceeds "
            f"delta_act {delta_act:.2f}s for this action's risk class"
        )


def execute_delegated_write(
    warrant: Warrant,
    live_quote: AttestationQuote | None,
    delta_act: float,
    path: str,
) -> None:
    # Freshness is enforced at the action site, synchronously — not by the
    # auditor's re-verification timer, which only bounds revocation latency.
    assert_warrant_fresh_for_action(warrant, live_quote, delta_act)
    if "filesystem.write" not in warrant.scope:
        raise StaleWarrantError(
            f"peer {warrant.peer_id}: write outside delegated scope"
        )
    # ... perform write ...
