# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-position-when-the-oauth-2-1-resource-binding-rotates-mid-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-position-when-the-oauth-2-1-resource-binding-rotates-mid-resume.warrant.json
# Markdown SHA-256:   3272bb54692f2a4c3598d9e594e68dac41b9685915d20fa1cc02ed28a9df464e
# Code AST SHA-256:   16ab2a0665395a2edfe5834a90765cb6bab324ec31e6d4c815946d2f40097708
# Verified Classes:   CursorProvenanceError, PrincipalBinding
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hmac
import hashlib
from dataclasses import dataclass


class CursorProvenanceError(RuntimeError):
    """Raised when a replayed MCP SSE event cannot be bound to the cursor's
    original principal, or when the server widened the replay partition."""


@dataclass(frozen=True)
class PrincipalBinding:
    resource_uri: str
    stable_id: str          # NOT sub, NOT jti — a linkage-resolved stable id
    stream_id: str


def verify_replay_frame(
    frame: dict,
    cursor: str,
    expected: PrincipalBinding,
    server_key: bytes,
) -> None:
    """Validate a single replayed SSE frame before it enters agent state.

    frame keys: event_id, binding_sig, binding_stable_id, stream_id, payload
    cursor format: "<event_id>.<hex hmac>"
    """
    try:
        event_id_str, sig_hex = cursor.split(".", 1)
        event_id = int(event_id_str)
    except (ValueError, AttributeError) as exc:
        raise CursorProvenanceError(f"malformed cursor: {cursor!r}") from exc

    # 1. Cursor must commit to the principal that originally received it.
    mac = hmac.new(
        server_key,
        f"{expected.stream_id}:{expected.stable_id}:{event_id}".encode(),
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(mac, sig_hex):
        raise CursorProvenanceError(
            f"cursor {cursor!r} not bound to principal {expected.stable_id!r}"
        )

    # 2. Frame must belong to the same stream and stable principal.
    if frame.get("stream_id") != expected.stream_id:
        raise CursorProvenanceError(
            f"frame stream {frame.get('stream_id')!r} != {expected.stream_id!r}"
        )
    if frame.get("binding_stable_id") != expected.stable_id:
        raise CursorProvenanceError(
            "cross-principal replay: frame belongs to "
            f"{frame.get('binding_stable_id')!r}, expected {expected.stable_id!r}"
        )

    # 3. Server must not have silently widened the partition.
    if frame.get("binding_migrated") and not frame.get("linkage_record_id"):
        raise CursorProvenanceError(
            "binding_migrated frame lacks auditable linkage record"
        )

    # 4. Event IDs must be strictly monotonic across the resume boundary.
    if int(frame["event_id"]) <= event_id:
        raise CursorProvenanceError(
            f"non-monotonic replay: {frame['event_id']} <= cursor {event_id}"
        )


def resume_mcp_stream(
    frames: list[dict],
    cursor: str,
    expected: PrincipalBinding,
    server_key: bytes,
) -> list[dict]:
    admitted: list[dict] = []
    for frame in frames:
        try:
            verify_replay_frame(frame, cursor, expected, server_key)
        except CursorProvenanceError:
            # Refuse the entire resume; force cold restart from checkpoint.
            raise
        admitted.append(frame)
    if not admitted:
        raise CursorProvenanceError(
            "empty replay partition; server must emit resume_rejected, "
            "not a widened fallback"
        )
    return admitted
