# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-a-token-scope-downgrade-and-replays-tool-calls-under-stale-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-a-token-scope-downgrade-and-replays-tool-calls-under-stale-authorization.warrant.json
# Markdown SHA-256:   7c284e472fe4079f1d6eee969bb7c365c796a0cfa00fe9baf5f7f8659bf09504
# Code AST SHA-256:   1c28ae916b9e06d266b1b920b71d1111beee678c9e065922ed31cc2752b0b074
# Verified Classes:   StaleAuthorizationReplayError, Scope, BufferedEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, List


class StaleAuthorizationReplayError(RuntimeError):
    """Raised when a resumed session would consume replayed events
    produced under scopes the current token no longer holds."""


@dataclass(frozen=True)
class Scope:
    name: str


@dataclass
class BufferedEvent:
    event_id: int
    tool: str
    producing_scopes: FrozenSet[str]
    payload_gated_by: FrozenSet[str] = field(default_factory=frozenset)
    result: dict = field(default_factory=dict)


def resume_session(
    current_scopes: FrozenSet[str],
    replay_backlog: List[BufferedEvent],
    allow_redaction: bool = True,
) -> List[BufferedEvent]:
    """Validate a resumable SSE resume against the live token's scopes.

    Returns the events the client may treat as *actionable* history.
    Raises if a replayed result would advance the plan under a scope
    the current token lacks and the server did not redact it.
    """
    actionable: List[BufferedEvent] = []
    stale = [
        e for e in replay_backlog
        if not current_scopes.issuperset(e.producing_scopes)
    ]

    if stale:
        # A replayed result produced under a broader grant is inert history.
        # The client MUST NOT fold it into plan state.
        for e in stale:
            if e.payload_gated_by and not current_scopes.issuperset(e.payload_gated_by):
                if not allow_redaction:
                    raise StaleAuthorizationReplayError(
                        f"event {e.event_id} ({e.tool}) payload gated by "
                        f"{sorted(e.payload_gated_by)} exceeds current scopes "
                        f"{sorted(current_scopes)}; server did not redact — "
                        f"replay would launder a read across the auth boundary"
                    )
                # Redacted: record as observed, do not act.
                continue
            raise StaleAuthorizationReplayError(
                f"event {e.event_id} ({e.tool}) produced under "
                f"{sorted(e.producing_scopes)} but current scopes are "
                f"{sorted(current_scopes)}; plan must be re-derived from the "
                f"last event whose producing scopes are still held, not resumed"
            )

    for e in replay_backlog:
        if current_scopes.issuperset(e.producing_scopes):
            actionable.append(e)
    return actionable


def advance_plan(plan_step: str, actionable: List[BufferedEvent]) -> str:
    if plan_step == "close_issue" and not any(
        e.tool == "attach_artifact" for e in actionable
    ):
        raise StaleAuthorizationReplayError(
            "cannot advance to close_issue: prerequisite attach_artifact "
            "result was produced under a revoked scope and is inert history; "
            "re-plan required, do not retry"
        )
    return plan_step
