# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-byzantine-task-commitment-from-surviving-a-stale-quorum-epoch-transition-in-multi-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-byzantine-task-commitment-from-surviving-a-stale-quorum-epoch-transition-in-multi-agent-consensus.warrant.json
# Markdown SHA-256:   35fd605fcfecb1a8dfe236d4ce2e596e39082ce7a544e10830ebf691da38e28f
# Code AST SHA-256:   7739d9a6e64d196c420286e432aad55e09317ec933250f7eb5cb055dc6f7bae1
# Verified Classes:   StaleEpochVoteError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleEpochVoteError(RuntimeError):
    """Raised when a rejoining agent attempts to rebroadcast a vote
    whose epoch is not provably current under the live quorum."""
    pass


def resume_pending_votes(
    pending: list[dict],
    current_epoch: int,
    has_new_view_cert: bool,
) -> list[dict]:
    """
    Filter an agent's pending-vote set at resume time.

    A vote is rebroadcastable only if:
      - its epoch == current_epoch, OR
      - its epoch == current_epoch - 1 AND a valid new-view certificate
        covers the transition (so the current leader can still use it).

    Any vote older than current_epoch - 1, or from current_epoch - 1
    without a certificate, is a fossil and MUST NOT be re-emitted.
    Rebroadcasting it is the quorum-intersection violation.
    """
    rebroadcastable: list[dict] = []
    for vote in pending:
        epoch = vote["epoch"]
        if epoch == current_epoch:
            rebroadcastable.append(vote)
        elif epoch == current_epoch - 1 and has_new_view_cert:
            # Still usable, but only via the new leader's new-view path.
            rebroadcastable.append(vote)
        elif epoch < current_epoch - 1 or (
            epoch == current_epoch - 1 and not has_new_view_cert
        ):
            raise StaleEpochVoteError(
                f"agent {vote['agent_id']} holds pending vote "
                f"(epoch={epoch}, digest={vote['digest']!r}) but current "
                f"epoch={current_epoch} and new_view_cert={has_new_view_cert}. "
                f"Rebroadcast would violate quorum intersection; discard and "
                f"escalate to operator."
            )
    return rebroadcastable
