# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-capability-negotiation-rather-than-a-stream-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resume-as-a-fresh-capability-negotiation-rather-than-a-stream-continuation.warrant.json
# Markdown SHA-256:   0b0c5ab7337a6a3452276522e6a9bc71c25aab4c3ac41d5e2f19074665ad1aa2
# Code AST SHA-256:   9240dd272c174b5b66951a8e3c7180630108cfd5c328e40430222b296f4adc68
# Verified Classes:   StaleSessionResumeError, SessionEpoch, ResumeResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class StaleSessionResumeError(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be proven to continue the same session."""


@dataclass
class SessionEpoch:
    session_id: str
    generation: int
    capability_digest: str

    @classmethod
    def from_initialize(cls, session_id: str, generation: int, capabilities: dict) -> "SessionEpoch":
        digest = hashlib.sha256(
            repr(sorted(capabilities.items())).encode()
        ).hexdigest()
        return cls(session_id=session_id, generation=generation, capability_digest=digest)


@dataclass
class ResumeResponse:
    status: int
    session_id: Optional[str]
    generation: Optional[int]
    replayed_events: list = field(default_factory=list)


def reconcile_resume(
    prior: SessionEpoch,
    resume: ResumeResponse,
    pending_calls: dict,
) -> dict:
    """
    Decide whether a Last-Event-ID resume is a true continuation.
    Returns a dict of calls whose outcome is unknown and must be reconciled
    via idempotency keys, or raises if the session contract cannot be proven.
    """
    if resume.status in (404, 410):
        # Server explicitly disowned the session: fresh negotiation required.
        raise StaleSessionResumeError(
            f"session {prior.session_id} gone (status {resume.status}); "
            f"must re-initialize before dispatch"
        )

    if resume.session_id != prior.session_id:
        raise StaleSessionResumeError(
            f"resume bound to session {resume.session_id!r} but caller held "
            f"{prior.session_id!r}; replay buffer outlived session record"
        )

    if resume.generation is None or resume.generation != prior.generation:
        raise StaleSessionResumeError(
            f"session epoch advanced {prior.generation}->{resume.generation}; "
            f"capability surface may have changed, renegotiate"
        )

    # Session proven continuous. Any pending call whose result frame
    # was not observed in the replay window has an unknown outcome.
    observed = {
        ev.get("request_id")
        for ev in resume.replayed_events
        if ev.get("type") == "message"
    }
    unknown = {
        rid: call for rid, call in pending_calls.items() if rid not in observed
    }
    return unknown


def dispatch_after_resume(prior: SessionEpoch, resume: ResumeResponse, pending_calls: dict) -> None:
    unknown = reconcile_resume(prior, resume, pending_calls)
    for rid, call in unknown.items():
        if not call.get("idempotency_key"):
            raise StaleSessionResumeError(
                f"pending call {rid} ({call.get('tool')}) has unknown outcome "
                f"and no idempotency key; refusing blind retry"
            )
