# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-resumable-a2a-stream-artifact-rather-than-checkpoint-it.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-resumable-a2a-stream-artifact-rather-than-checkpoint-it.warrant.json
# Markdown SHA-256:   38ec9218869116ef3de654855d6527a2559fafa6569cbd1534d93fb2cc604dd1
# Code AST SHA-256:   674bc1f9bc64b6c6a228bbcf3b704632d6371da332b14bae47228132c7562cb7
# Verified Classes:   UnrecoverableStreamGap
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnrecoverableStreamGap(RuntimeError):
    """Raised when a paused A2A artifact stream cannot be safely resumed."""
    pass


def resume_cursor(outbound_cursor: int,
                  last_committed: int | None,
                  replay_window: int,
                  peer_signaled_eviction: bool) -> int:
    """
    Decide the chunk index to resume an A2A artifact stream from.

    Returns the resume index. Raises UnrecoverableStreamGap when the gap
    between the sender's outbound cursor and the peer's committed cursor
    exceeds the replay window under eviction, meaning a rewound resume would
    both duplicate committed regions and still miss evicted ones.
    """
    if last_committed is None:
        # No committed cursor advertised: assume nothing in-flight is durable.
        last_committed = 0

    gap = outbound_cursor - last_committed
    if gap <= 1:
        # Contiguous: sender cursor is a safe anchor.
        return outbound_cursor

    if gap > replay_window and peer_signaled_eviction:
        raise UnrecoverableStreamGap(
            f"gap={gap} exceeds replay_window={replay_window} with peer eviction; "
            f"restart artifact from chunk 0 with a new artifact_id"
        )

    # Rewind to first unconfirmed chunk rather than trusting outbound cursor.
    return last_committed + 1
