# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-mid-stream-sse-to-streamable-http-migration-when-the-mcp-session-s-last-event-id-watermark-diverges-from-the-server-s-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-mid-stream-sse-to-streamable-http-migration-when-the-mcp-session-s-last-event-id-watermark-diverges-from-the-server-s-repl.warrant.json
# Markdown SHA-256:   7ec99dbe401e625afdf89fea3c083057161f95439f0e1b3705b707c7737251a2
# Code AST SHA-256:   93fce14ba6bff7c1ec34d5122e7f95a546863d867bba35003138e1a6d1608e2a
# Verified Classes:   TransportMigrationContinuityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TransportMigrationContinuityError(RuntimeError):
    """Raised when a resumed MCP stream cannot prove event-namespace continuity."""
    pass


def resume_mcp_stream(
    session_id: str,
    client_watermark: int,
    client_step_counter: int,
    prior_binding: str,          # "sse" | "streamable_http"
    new_binding: str,
    first_event_id: int | None,  # None if server omitted id: on first frame
) -> str:
    """
    Decide whether to trust a resumed stream or degrade to cold-start.
    Returns "trust" or "cold_start". Raises on unrecoverable ambiguity.
    """
    if session_id is None:
        raise TransportMigrationContinuityError(
            "resume attempted without Mcp-Session-Id; cannot scope event namespace"
        )

    if first_event_id is None:
        # Server gave us a live stream but no cursor. Per spec this is legal
        # on a fresh stream; it is NOT evidence of continuity.
        return "cold_start"

    binding_changed = prior_binding != new_binding
    cursor_regressed = first_event_id <= client_watermark

    if binding_changed or cursor_regressed:
        # Either the transport migrated (SSE<->HTTP) or the server's replay
        # cursor is behind our watermark. Both mean the event namespace is
        # not provably the same one we were reading from.
        return "cold_start"

    # Same namespace, monotonic advance: safe to continue, but the agent's
    # own step counter must still be reconciled before trusting tool results.
    if client_step_counter < 0:
        raise TransportMigrationContinuityError(
            f"step counter corrupt for session {session_id}"
        )
    return "trust"


def reconcile_or_abort(
    session_id: str,
    client_step_counter: int,
    server_reported_step: int,
) -> None:
    if server_reported_step != client_step_counter:
        raise TransportMigrationContinuityError(
            f"session {session_id}: client step {client_step_counter} != "
            f"server step {server_reported_step}; refusing to continue loop"
        )
