# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-resume-an-mcp-sse-stream-the-last-event-id-cursor-can-outlive-the-oauth-2-1-resource-indicator-scope-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-resume-an-mcp-sse-stream-the-last-event-id-cursor-can-outlive-the-oauth-2-1-resource-indicator-scope-that-authorized-it.warrant.json
# Markdown SHA-256:   c3e9dc79fe73c2d1075546c179b3de0da0dc33956db6b1ff48af916043d20a6d
# Code AST SHA-256:   0eba81e1bb0ff844a9fa50168d235e3b01621a9c446b7e8d900be16f1153e41f
# Verified Classes:   ScopeBoundCursorError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeBoundCursorError(RuntimeError):
    """Raised when an SSE Last-Event-ID resumption would cross a resource-indicator scope boundary."""
    pass


def resume_stream(session, token_resource, last_event_id, event_log):
    """
    session: object with .resource (resource indicator the session was created under)
             and .session_id
    token_resource: the `resource`/`aud` claim of the token presented on this reconnect
    last_event_id: the cursor the client sent (int or None)
    event_log: list of events, each with .id and .resource (scope that produced it)
    Returns the list of events safe to replay.
    """
    if last_event_id is None:
        return []

    # Invariant 1: the session's own scope must match the consuming warrant.
    if session.resource != token_resource:
        raise ScopeBoundCursorError(
            f"session {session.session_id} scoped to {session.resource!r} "
            f"but reconnect presents token scoped to {token_resource!r}; "
            f"cursor {last_event_id} cannot be honored across scopes"
        )

    replay = [e for e in event_log if e.id > last_event_id]

    # Invariant 2: every replayed event must have been produced under the
    # same resource indicator that authorizes this connection.
    for e in replay:
        if e.resource != token_resource:
            raise ScopeBoundCursorError(
                f"event {e.id} produced under {e.resource!r} but replay "
                f"authorized only for {token_resource!r}; refusing cross-scope replay"
            )

    return replay
