# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumed-sse-stream-has-silently-crossed-a-capability-boundary-after-mcp-session-re-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumed-sse-stream-has-silently-crossed-a-capability-boundary-after-mcp-session-re-negotiation.warrant.json
# Markdown SHA-256:   0f0e30a710f0a665920d009347efb73cfc5edb8ff58e4d753dcc11cd4b4d67a1
# Code AST SHA-256:   a7383a6f2d73e481bb48580dde291f3e8c5498b43a5915949fb50ccd95246ef5
# Verified Classes:   CapabilityScopeMismatch, NonResumableSession, SessionState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityScopeMismatch(RuntimeError):
    """Raised when a resumed SSE stream's capability scope no longer matches
    the scope under which the client negotiated the session."""
    pass


class NonResumableSession(RuntimeError):
    """Raised when the server cannot assert capability scope on resume."""
    pass


def digest_capabilities(caps: dict) -> str:
    # Stable digest over the negotiated capability set.
    canonical = json.dumps(caps, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class SessionState:
    session_id: str
    capabilities: dict
    last_event_id: int
    capability_digest: str = field(init=False)

    def __post_init__(self) -> None:
        self.capability_digest = digest_capabilities(self.capabilities)


def resume_stream(
    state: SessionState,
    server_echoed_digest: Optional[str],
    server_supports_scope_assertion: bool,
) -> str:
    """
    Decide whether it is safe to consume replayed events after an SSE drop.

    Returns the resume token to send (the Last-Event-ID) only if the server
    confirms the capability scope still matches. Otherwise raises, forcing
    the caller to re-initialize the session.
    """
    if not server_supports_scope_assertion:
        # Server cannot prove scope continuity. Reusing session IDs across
        # capability rotations is indistinguishable from a clean resume,
        # so we must fail closed.
        raise NonResumableSession(
            f"server cannot assert capability scope for session {state.session_id}; "
            f"refusing to resume at Last-Event-ID={state.last_event_id}"
        )

    if server_echoed_digest is None:
        raise CapabilityScopeMismatch(
            f"server returned no capability digest on resume for session "
            f"{state.session_id}; cannot verify replayed events are in-scope"
        )

    if server_echoed_digest != state.capability_digest:
        raise CapabilityScopeMismatch(
            f"capability scope rotated across resume for session {state.session_id}: "
            f"client holds {state.capability_digest[:12]}, server asserts "
            f"{server_echoed_digest[:12]}; replayed events at Last-Event-ID="
            f"{state.last_event_id} may carry out-of-scope semantics"
        )

    return str(state.last_event_id)


def safe_resume_or_reinit(state: SessionState, server_echoed_digest, supports_assertion) -> str:
    try:
        return resume_stream(state, server_echoed_digest, supports_assertion)
    except (CapabilityScopeMismatch, NonResumableSession):
        # Cold-start path: discard cursor, re-run initialize, rebuild state.
        return "REINITIALIZE"
