# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-tee-peer-s-tool-execution-warrant-mid-handoff-and-why-does-quote-staleness-silently-break-the-integ.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-tee-peer-s-tool-execution-warrant-mid-handoff-and-why-does-quote-staleness-silently-break-the-integ.warrant.json
# Markdown SHA-256:   e642f805524ea864645b50863ca444556e9b636c0266d62de9ceadd9e788c8df
# Code AST SHA-256:   679ad655245b0ad4fe456a1c2e99caebb83da771c40f0de049b46eba4577dcb2
# Verified Classes:   AttestationContinuityError, AttestedPeer, ToolResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass

FRESHNESS_WINDOW_S = 0.0  # mutating tools: quote must accompany this result


class AttestationContinuityError(RuntimeError):
    """Raised when a tool result cannot be bound to a valid, fresh, current-epoch attestation."""


@dataclass(frozen=True)
class AttestedPeer:
    measurement: str
    epoch: int
    session_id: str
    cached_at: float


@dataclass(frozen=True)
class ToolResult:
    output: bytes
    quote_measurement: str
    quote_report_data: str   # must equal the outstanding nonce
    quote_time: float
    quote_epoch: int
    quote_session_id: str


def consume_tool_result(
    peer: AttestedPeer,
    result: ToolResult,
    outstanding_nonce: str,
    context_compacted_since_cache: bool,
    now: float | None = None,
) -> bytes:
    now = time.time() if now is None else now

    if context_compacted_since_cache:
        # The cached tuple may have lost its referent; force re-attestation.
        raise AttestationContinuityError(
            "context compacted since attestation cached; binding lost, re-attest required"
        )

    if result.quote_report_data != outstanding_nonce:
        raise AttestationContinuityError(
            f"nonce mismatch: quote bound to {result.quote_report_data!r}, "
            f"expected {outstanding_nonce!r} (possible replay)"
        )

    if result.quote_measurement != peer.measurement:
        raise AttestationContinuityError(
            f"measurement drift: peer attested as {peer.measurement!r}, "
            f"result signed under {result.quote_measurement!r}"
        )

    if result.quote_epoch != peer.epoch or result.quote_session_id != peer.session_id:
        raise AttestationContinuityError(
            "epoch/session discontinuity: peer restarted since attestation cached"
        )

    age = now - result.quote_time
    if age > FRESHNESS_WINDOW_S:
        raise AttestationContinuityError(
            f"stale quote: age {age:.3f}s exceeds window {FRESHNESS_WINDOW_S}s at consumption"
        )

    return result.output
