# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-an-mcp-stream-after-a-mid-flight-last-event-id-replay-and-why-silent-resumption-corrupts-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-an-mcp-stream-after-a-mid-flight-last-event-id-replay-and-why-silent-resumption-corrupts-agent.warrant.json
# Markdown SHA-256:   f25b8bd3e2d14c46794c70b6bba7d69e7cb679ad46729c8620bc4dad6575628a
# Code AST SHA-256:   154adc5f5b7cb6bb2a2914e1be95520cf48d74d9d3e3d1f40b06825899ccecb3
# Verified Classes:   StreamResumeRejected, ResumeDecision, Event, ResumeRequest
# Defensive Guards:   1 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from dataclasses import dataclass
from enum import Enum


class StreamResumeRejected(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be safely stitched."""


class ResumeDecision(Enum):
    RESUME = "resume"
    RECONCILE = "reconcile"
    RESTART = "restart"


@dataclass(frozen=True)
class Event:
    id: int
    kind: str            # "progress" | "partial_result" | "checkpoint" | "side_effect" | "terminal"
    idempotent: bool
    dedup_key: str | None = None


@dataclass(frozen=True)
class ResumeRequest:
    call_id: str
    transport_cursor: int      # Last-Event-ID from the HTTP layer
    application_cursor: int    # last event the agent durably applied
    execution_epoch: str       # server-side epoch of the live tool call
    server_epoch: str          # epoch the server reports for this call_id
    replayable: list[Event]    # server's replay suffix, may be empty


def decide_resume(req: ResumeRequest) -> ResumeDecision:
    # Epoch mismatch: server restarted or call was re-created. The event log
    # the client holds does not describe the execution now running.
    if req.execution_epoch != req.server_epoch:
        return ResumeDecision.RECONCILE

    # Gap between the client's durable cursor and the transport cursor that
    # the client cannot dedup => in-flight window is unrecoverable.
    if req.transport_cursor < req.application_cursor:
        return ResumeDecision.RECONCILE

    if not req.replayable:
        # No suffix available: either execution ended or log truncated.
        return ResumeDecision.RECONCILE

    # Replay must be gap-free from the application cursor.
    expected = req.application_cursor + 1
    for ev in req.replayable:
        if ev.id != expected:
            return ResumeDecision.RECONCILE
        expected += 1

    # Any non-idempotent side effect in the replay window means replaying it
    # would either double-apply or falsely re-assert an irreversible fact.
    for ev in req.replayable:
        if ev.kind == "side_effect" and not ev.idempotent:
            return ResumeDecision.RECONCILE
        if ev.kind == "partial_result" and ev.dedup_key is None:
            return ResumeDecision.RECONCILE

    return ResumeDecision.RESUME


def resume_or_raise(req: ResumeRequest) -> ResumeDecision:
    decision = decide_resume(req)
    if decision is not ResumeDecision.RESUME:
        raise StreamResumeRejected(
            f"call={req.call_id} epoch={req.execution_epoch} "
            f"transport_cursor={req.transport_cursor} "
            f"application_cursor={req.application_cursor} "
            f"decision={decision.value}: refusing silent stitch; "
            f"route to reconciliation via get_tool_call_status({req.call_id!r})"
        )
    return decision
