# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-identity-attestation-has-gone-stale-mid-task-the-posture-epoch-divergence-failure-in-hardware-backed-agent-cr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-identity-attestation-has-gone-stale-mid-task-the-posture-epoch-divergence-failure-in-hardware-backed-agent-cr.warrant.json
# Markdown SHA-256:   dd73d4ef40f9c5c81d8e2e06e30a877d5c8ea1e11eb6189069ce53f27937882e
# Code AST SHA-256:   d892b1c849aa15a846c5706d4176179cbe670b8b0dc615551f7c5891cf23d6d0
# Verified Classes:   PostureStaleError, PostureUnreadableError, Warrant, PlatformState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class PostureStaleError(RuntimeError):
    """Raised when a signed assertion would be produced under a warrant whose
    attested posture epoch no longer matches the platform's current epoch."""
    pass


class PostureUnreadableError(RuntimeError):
    """Raised when the platform measurement cannot be read; treated as fail-closed."""
    pass


@dataclass(frozen=True)
class Warrant:
    epoch: int          # posture epoch embedded at attestation time
    pcr_digest: str
    runtime_digest: str
    expires_at: float   # wall-clock expiry


@dataclass(frozen=True)
class PlatformState:
    epoch: int          # monotonic measurement epoch
    runtime_digest: str


def read_platform_state() -> PlatformState:
    """Read current measured posture. In production this is a TPM/measurement
    read; here it is a stub. Must be monotonic under a correct platform."""
    # ... hardware read ...
    raise NotImplementedError("wire to TPM/measurement backend")


def current_time() -> float:
    return time.time()


def sign_verdict(warrant: Warrant, payload: bytes, signer) -> bytes:
    """Sign a verdict ONLY if the warrant's posture epoch equals the current
    platform epoch. Enforces the posture-epoch coupling invariant at use time."""
    try:
        now_state = read_platform_state()
    except Exception as exc:  # unreadable posture is not a current posture
        raise PostureUnreadableError(
            "cannot read platform posture; refusing to sign (fail-closed)"
        ) from exc

    t = current_time()

    if t >= warrant.expires_at:
        raise PostureStaleError(
            f"warrant expired at {warrant.expires_at}, now {t}"
        )

    if now_state.epoch > warrant.epoch:
        # drift: platform moved ahead of the attested warrant
        raise PostureStaleError(
            f"posture epoch drift: warrant attests E={warrant.epoch}, "
            f"platform is E={now_state.epoch} "
            f"(runtime {warrant.runtime_digest} -> {now_state.runtime_digest}); "
            f"re-attest before signing or signal PostureStale to peers"
        )

    if now_state.epoch < warrant.epoch:
        # impossible under a monotonic epoch: rollback or measurement corruption
        raise PostureStaleError(
            f"epoch regression: warrant E={warrant.epoch} > platform E={now_state.epoch}; "
            f"possible rollback or compromised measurement path — halt and escalate"
        )

    # now_state.epoch == warrant.epoch: posture is current, sign
    return signer.sign(payload)
