# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-durability-when-sse-backpressure-outruns-its-resumable-session-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-durability-when-sse-backpressure-outruns-its-resumable-session-cursor.warrant.json
# Markdown SHA-256:   49b3bffce20f4cfed47049133260a7dc77194662e9895a7c083c5b56df9822ec
# Code AST SHA-256:   488ef40f72641684cb53bb33cf424911b98bf02859a5e824da6f5b1c0ebb7b68
# Verified Classes:   ResumeDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumeDivergenceError(RuntimeError):
    """Raised when the delivery cursor and commit cursor disagree on resume."""


def reconcile_resume(delivery_cursor: int, commit_log: list[dict]) -> list[dict]:
    """
    Given the client's Last-Event-ID (delivery cursor) and the durable
    commit log, decide what to replay. A frame with seq <= delivery_cursor
    was already seen by the client. A commit with seq <= delivery_cursor
    but whose frame was NOT delivered is a divergence: the effect exists
    but the client never learned of it.
    """
    replay = []
    for entry in commit_log:
        seq = entry["seq"]
        if seq <= delivery_cursor:
            if not entry.get("delivered", False):
                # Effect committed ahead of delivery: do NOT re-execute.
                # Emit a reconciliation frame instead of a tool_call.
                replay.append({"type": "replayed_commit", "seq": seq,
                               "effect": entry["effect"]})
            continue
        # seq > delivery_cursor: not yet seen. Re-issue only if uncommitted.
        if entry.get("committed", False):
            raise ResumeDivergenceError(
                f"seq {seq} committed but beyond delivery cursor "
                f"{delivery_cursor}; commit ran ahead of transport flush. "
                f"Refusing to replay a side effect that already occurred."
            )
        replay.append({"type": "tool_call", "seq": seq, "call": entry["call"]})
    return replay


def flush_gated_commit(frame_seq: int, write_result: bool, commit_fn) -> None:
    """
    The commit gate: a tool call may only be committed after its
    announcing frame has been flushed to the transport.
    """
    if not write_result:
        raise ResumeDivergenceError(
            f"frame {frame_seq} not flushed; refusing to commit. "
            f"Executor would run ahead of the delivery cursor."
        )
    commit_fn()
