# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-token-binding-across-a-re-attestation-boundary-during-mid-tool-call-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-token-binding-across-a-re-attestation-boundary-during-mid-tool-call-handoff.warrant.json
# Markdown SHA-256:   660b413b2947cb38b5ade11e3684233e4d4f3470817b1999db29fa3b3274c0c8
# Code AST SHA-256:   447137414d3e95e7005b54b2ddf165e665cd45fbe66182bcd24df579e199989d
# Verified Classes:   BindingLapseError, Attestation, Peer, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class BindingLapseError(RuntimeError):
    """Raised when a token's attestation epoch no longer matches the peer's
    live measurement epoch at invocation time, and the call was not yet
    dispatched under the authorizing epoch's manifest snapshot."""
    pass


@dataclass
class Attestation:
    epoch: int
    measurement: str
    manifest_snapshot: dict


@dataclass
class Peer:
    live: Attestation
    manifest_by_epoch: dict = field(default_factory=dict)


@dataclass
class CapabilityToken:
    tool: str
    attestation_epoch: int
    ttl_s: float
    minted_at: float = field(default_factory=time.monotonic)

    def expired(self) -> bool:
        return (time.monotonic() - self.minted_at) > self.ttl_s


def invoke_tool(peer: Peer, token: CapabilityToken, dispatched: bool) -> dict:
    if token.expired():
        raise BindingLapseError(f"token for {token.tool} expired before dispatch")

    if token.attestation_epoch == peer.live.epoch:
        # Bound to the live measurement: execute against the live manifest.
        return {"manifest": peer.live.manifest_snapshot, "epoch": token.attestation_epoch}

    if dispatched:
        # In-flight call: must complete against the epoch it was authorized
        # against, using the snapshot -- never the live (mutated) manifest.
        snapshot = peer.manifest_by_epoch.get(token.attestation_epoch)
        if snapshot is None:
            raise BindingLapseError(
                f"no manifest snapshot for epoch {token.attestation_epoch}; "
                f"live epoch is {peer.live.epoch} -- cannot safely complete in-flight call"
            )
        return {"manifest": snapshot, "epoch": token.attestation_epoch}

    # Not yet dispatched and epoch is stale: hard abort, require re-handshake.
    raise BindingLapseError(
        f"token authorized under epoch {token.attestation_epoch} but peer is at "
        f"epoch {peer.live.epoch}; refusing to dispatch against live manifest"
    )
