# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-elicitation-request-has-been-orphaned-by-a-reconnecting-client-the-lost-elicitation-id-invariant-in-human-in-t.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-elicitation-request-has-been-orphaned-by-a-reconnecting-client-the-lost-elicitation-id-invariant-in-human-in-t.warrant.json
# Markdown SHA-256:   9b9121fb1be24725bdc36bd1fdd44c1df453bc94f3dd322f69acf3a7b965508d
# Code AST SHA-256:   0f6b9eafecc0aeba0d7da227a5c5980f0b50f2060e5122046f517f519a73e8a2
# Verified Classes:   ElicitationOrphaned, ElicitationState, PendingElicitation, ElicitationRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict


class ElicitationOrphaned(RuntimeError):
    """Raised when a pending elicitation's transport generation is dead.

    This is deliberately NOT a denial and NOT a timeout. It signals that the
    correlation between the elicitation ID, the blocked tool call, and the
    live transport session has been severed, so the authorization is void and
    the tool MUST NOT execute. The agent should treat this as "retry with a
    fresh elicitation," never as "human said no."
    """


class ElicitationState(Enum):
    PENDING = "pending"
    RESOLVED = "resolved"
    ORPHANED = "orphaned"


@dataclass
class PendingElicitation:
    elicitation_id: str
    transport_generation: int
    tool_name: str
    state: ElicitationState = ElicitationState.PENDING


@dataclass
class ElicitationRegistry:
    live_generation: int
    pending: Dict[str, PendingElicitation] = field(default_factory=dict)

    def register(self, elicitation_id: str, tool_name: str) -> PendingElicitation:
        rec = PendingElicitation(
            elicitation_id=elicitation_id,
            transport_generation=self.live_generation,
            tool_name=tool_name,
        )
        self.pending[elicitation_id] = rec
        return rec

    def on_transport_rotate(self, new_generation: int) -> list[str]:
        """Drain orphans on reconnect. Returns IDs voided by this rotation."""
        self.live_generation = new_generation
        orphaned: list[str] = []
        for eid, rec in list(self.pending.items()):
            if rec.state is ElicitationState.PENDING and rec.transport_generation != new_generation:
                rec.state = ElicitationState.ORPHANED
                orphaned.append(eid)
        return orphaned

    def resolve(self, elicitation_id: str, approved: bool) -> bool:
        """Correlate a response strictly by ID and live generation.

        Content-based matching (tool name, arg hash) is forbidden: it silently
        collapses a retried elicitation onto an orphaned one and reintroduces
        duplicate authorization.
        """
        rec = self.pending.get(elicitation_id)
        if rec is None:
            raise ElicitationOrphaned(
                f"response for unknown elicitation {elicitation_id!r}; "
                "no live correlation exists"
            )
        if rec.state is ElicitationState.ORPHANED:
            raise ElicitationOrphaned(
                f"elicitation {elicitation_id!r} was orphaned at generation "
                f"{rec.transport_generation}; live generation is "
                f"{self.live_generation}"
            )
        if rec.transport_generation != self.live_generation:
            rec.state = ElicitationState.ORPHANED
            raise ElicitationOrphaned(
                f"elicitation {elicitation_id!r} bound to generation "
                f"{rec.transport_generation}, response arrived on "
                f"{self.live_generation}; authorization void"
            )
        rec.state = ElicitationState.RESOLVED
        return approved


def authorize_tool_call(
    registry: ElicitationRegistry,
    elicitation_id: str,
    approved: bool,
) -> str:
    """Gate a tool call on a human decision, enforcing the ID+generation invariant."""
    try:
        granted = registry.resolve(elicitation_id, approved)
    except ElicitationOrphaned as exc:
        # Fail closed: the tool does not run. Surface a distinguishable error
        # so the agent retries with a fresh elicitation rather than treating
        # this as a denial or a success.
        raise ElicitationOrphaned(str(exc)) from exc
    if not granted:
        return "denied"
    return "executed"
