# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-handoff-envelope-whose-warrant-has-already-expired-at-the-receiving-clock.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-handoff-envelope-whose-warrant-has-already-expired-at-the-receiving-clock.warrant.json
# Markdown SHA-256:   e94ced4cab093a180f38ff0e9466e6753a013ad33ffcbf3fd37d7bb73f7fe391
# Code AST SHA-256:   2d33177b047a55218c940f53341a1b1f2a9cd7e0cf7602dab7f85f094690ba25
# Verified Classes:   WarrantExpiredAtUse, ClockSkewExceeded, Envelope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantExpiredAtUse(RuntimeError):
    """Raised when a signed envelope verified at receipt is expired at action time."""
    pass


class ClockSkewExceeded(RuntimeError):
    """Raised when receiver clock and envelope issue time diverge beyond declared skew."""
    pass


@dataclass(frozen=True)
class Envelope:
    scope: str
    iat: float          # issuer time
    nbf: float          # not-before (issuer frame)
    exp: float          # expiry (issuer frame)
    max_skew: float     # declared tolerable skew, seconds
    signature_ok: bool  # result of crypto verify, done once


def verify_at_receipt(env: Envelope, receiver_now: float) -> bool:
    # Cheap receipt-time check. NOT sufficient to authorize an action.
    if not env.signature_ok:
        return False
    if receiver_now < env.nbf - env.max_skew:
        return False
    if receiver_now >= env.exp + env.max_skew:
        return False
    return True


def gate_privileged_action(
    env: Envelope,
    action_scope: str,
    receiver_now: float,
    loop_deadline: float,
) -> None:
    """
    Re-verify at the instant of use. This is the only check that authorizes.

    Raises WarrantExpiredAtUse if the envelope is dead at action time, even
    if it was live at receipt. Raises ClockSkewExceeded if the receiver clock
    disagrees with the issuer beyond the declared skew budget.
    """
    if not env.signature_ok:
        raise WarrantExpiredAtUse(f"signature invalid for scope={action_scope}")

    if action_scope != env.scope:
        raise WarrantExpiredAtUse(
            f"scope mismatch: envelope={env.scope} action={action_scope}"
        )

    skew = abs(receiver_now - env.iat)
    if skew > env.max_skew:
        raise ClockSkewExceeded(
            f"skew {skew:.3f}s exceeds max_skew {env.max_skew:.3f}s; "
            f"TTL budget is unreliable"
        )

    # The decisive check: expiry evaluated at action time, in receiver frame.
    if receiver_now >= env.exp:
        raise WarrantExpiredAtUse(
            f"envelope expired at use: exp={env.exp:.3f} "
            f"action_time={receiver_now:.3f} "
            f"overshoot={receiver_now - env.exp:.3f}s"
        )

    if receiver_now > loop_deadline:
        raise WarrantExpiredAtUse(
            f"loop deadline {loop_deadline:.3f} passed before action"
        )


def run_worker_turn(env: Envelope, loop_seconds: float) -> None:
    """
    Simulates a worker that verifies at receipt, then acts after a reasoning
    loop. The gate is called at use, with the receiver clock read fresh.
    """
    receipt = time.monotonic()
    if not verify_at_receipt(env, receipt):
        raise WarrantExpiredAtUse("rejected at receipt")

    # Reasoning loop: retrieval + model round-trips + retries.
    time.sleep(loop_seconds)

    action_time = time.monotonic()
    loop_deadline = min(env.exp, receipt + loop_seconds + 1.0)

    # Gate is called synchronously with the privileged action. No cached boolean.
    gate_privileged_action(env, env.scope, action_time, loop_deadline)
    # ... privileged tool call executes here ...
