# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-elicitation-response-as-stale-the-push-elicitation-replay-window-and-the-elicit-id-nonce-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-elicitation-response-as-stale-the-push-elicitation-replay-window-and-the-elicit-id-nonce-invariant.warrant.json
# Markdown SHA-256:   176cef5ee5962ae916164867d79e7e33a6ea1d5ecacd8b9a60f05e3a45f2b5e1
# Code AST SHA-256:   f54a12a8d1884ca6e6a8e2a0a4d663cd69c31f1abab0ab020140583cae529cf2
# Verified Classes:   StaleElicitationError, PendingElicitation, ElicitationResponse
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class StaleElicitationError(RuntimeError):
    """Raised when an elicitation response does not authorize the action about to run."""


def canonical_digest(payload: dict) -> str:
    # Deterministic serialization: sorted keys, no whitespace, normalized floats-as-str.
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class PendingElicitation:
    elicit_id: str
    epoch: int
    payload_digest: str


@dataclass(frozen=True)
class ElicitationResponse:
    elicit_id: str
    action: str            # "accept" | "decline" | "cancel"
    payload_digest: str    # echoed by client, must be tamper-evident
    epoch: int


def consume_approval(
    pending: PendingElicitation,
    response: ElicitationResponse,
    action_about_to_run: dict,
    current_epoch: int,
) -> None:
    """Gate execution on the (nonce, digest, epoch) triple. Fails closed on any drift."""
    if response.action != "accept":
        raise StaleElicitationError(
            f"elicitation {response.elicit_id} not accepted (action={response.action!r})"
        )
    if response.elicit_id != pending.elicit_id:
        raise StaleElicitationError(
            f"nonce mismatch: response={response.elicit_id} pending={pending.elicit_id}"
        )
    if response.payload_digest != pending.payload_digest:
        # Client altered or forged the digest binding.
        raise StaleElicitationError(
            f"digest binding tampered for {pending.elicit_id}"
        )
    if response.epoch != pending.epoch:
        # Agent turn restarted between push and consume; approval no longer covers this turn.
        raise StaleElicitationError(
            f"epoch drift for {pending.elicit_id}: issued={pending.epoch} response={response.epoch}"
        )
    if current_epoch != pending.epoch:
        # Turn advanced after issuance but before consumption.
        raise StaleElicitationError(
            f"turn advanced for {pending.elicit_id}: pending={pending.epoch} current={current_epoch}"
        )
    live_digest = canonical_digest(action_about_to_run)
    if live_digest != pending.payload_digest:
        # The action about to execute is not the action the human reviewed.
        raise StaleElicitationError(
            f"payload drift for {pending.elicit_id}: "
            f"approved={pending.payload_digest[:12]} live={live_digest[:12]}"
        )
    # Invariant holds: proceed.
