# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-stream-resumption-as-a-fresh-capability-negotiation-rather-than-a-byte-offset-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-stream-resumption-as-a-fresh-capability-negotiation-rather-than-a-byte-offset-replay.warrant.json
# Markdown SHA-256:   592ab6aa69c6298c85a9c9833cf0f46f581df816300877de51c1b5bd571ad887
# Code AST SHA-256:   ba4c31eca7bde313540d7b463db1b4d371881ca85315b149f5fdd160310e6933
# Verified Classes:   SessionEpochMismatchError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionEpochMismatchError(RuntimeError):
    """Raised when a resumed MCP stream cannot prove session-identity continuity."""


def resume_stream(
    prior_epoch: str | None,
    resumed_first_event: dict,
    required_capabilities: set[str],
) -> dict:
    """
    Decide whether a resumed SSE stream is a true continuation or a fresh session.

    prior_epoch: session epoch captured before the break (None if never seen).
    resumed_first_event: the first event after reconnect; must carry 'session_epoch'
                         and, if re-established, a 'capabilities' manifest.
    required_capabilities: capabilities the in-flight tool call depends on.
    """
    resumed_epoch = resumed_first_event.get("session_epoch")

    # Absence of an epoch is "unknown" -> fail closed to re-negotiation.
    if resumed_epoch is None or prior_epoch is None:
        raise SessionEpochMismatchError(
            "session epoch missing on resumption; cannot prove continuity. "
            "Treating as fresh negotiation and re-running initialize."
        )

    if resumed_epoch != prior_epoch:
        raise SessionEpochMismatchError(
            f"session epoch changed across break ({prior_epoch} -> {resumed_epoch}). "
            "Event-ID replay is cosmetic; session is new. Re-negotiate capabilities "
            "and re-validate the in-flight tool call before consuming post-break output."
        )

    # Same epoch: still verify the capability set the call depends on.
    manifest = resumed_first_event.get("capabilities", {})
    missing = required_capabilities - set(manifest)
    if missing:
        raise SessionEpochMismatchError(
            f"same epoch but required capabilities absent after resume: {sorted(missing)}. "
            "In-flight call is no longer semantically valid; abort and re-issue."
        )

    return {"continuation": True, "epoch": resumed_epoch}
