# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-negotiation-replay-hazard-when-resumable-sse-is-silently-upgraded-to-streamable-http.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-negotiation-replay-hazard-when-resumable-sse-is-silently-upgraded-to-streamable-http.warrant.json
# Markdown SHA-256:   68a56c9220fbaf693a3e80e3f85c841a8050b0b6ddb4fa56b834d23bf7716186
# Code AST SHA-256:   7b29d77f5e6edc8e9d9ce033e006c9d733ebe933e314d5d3bc22591b818e22df
# Verified Classes:   ScopeLaunderingError, NegotiatedScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ScopeLaunderingError(RuntimeError):
    """Raised when a resumed event is delivered under a scope the client never negotiated."""
    pass


@dataclass(frozen=True)
class NegotiatedScope:
    session_id: str
    tool_grants: dict[str, frozenset[str]]


def resume_after_redirect(
    carried_session_id: str,
    carried_cursor: int,
    recorded_scope: NegotiatedScope,
    renegotiation_response: dict,
) -> NegotiatedScope:
    """
    Enforce the invariant: a carried cursor is advisory; scope continuity must be
    re-confirmed by the redirect target before any replayed event is accepted.
    """
    echoed_session = renegotiation_response.get("mcp_session_id")
    echoed_scope = renegotiation_response.get("tool_scope")

    # Signal 1: the target silently minted a new session instead of honoring ours.
    if echoed_session != carried_session_id:
        raise ScopeLaunderingError(
            f"session discontinuity on resume: carried {carried_session_id!r}, "
            f"target echoed {echoed_session!r}; cursor {carried_cursor} must be discarded"
        )

    # Signal 2: the target omitted the per-tool scope map entirely.
    if echoed_scope is None:
        raise ScopeLaunderingError(
            f"renegotiation omitted tool scope for session {carried_session_id!r}; "
            "replayed events cannot be authorized"
        )

    # Signal 3: the target's scope differs from what the client negotiated.
    rederived = NegotiatedScope(
        session_id=echoed_session,
        tool_grants={k: frozenset(v) for k, v in echoed_scope.items()},
    )
    if rederived.tool_grants != recorded_scope.tool_grants:
        raise ScopeLaunderingError(
            f"scope drift on resume: recorded {recorded_scope.tool_grants!r}, "
            f"target applied {rederived.tool_grants!r}"
        )

    return rederived
