# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-void-when-its-signer-set-is-internally-consistent-but-the-commitment-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-void-when-its-signer-set-is-internally-consistent-but-the-commitment-it.warrant.json
# Markdown SHA-256:   e0f9172efb6539fffd0d473a472fa59a01aa3ed6c080cb87dba4ed9a7f23040d
# Code AST SHA-256:   33f6c130582ff5fd4daf63e1eb30288ea151f20ab3fcf6a9618429a9b2594d99
# Verified Classes:   ProvenanceGapError, QuorumCertificate, AgentState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceGapError(RuntimeError):
    """Raised when an instance attempts to propose a transition from a
    certified root whose commitment history it has not replayed."""
    pass


class QuorumCertificate:
    def __init__(self, root_digest: str, commitment_index: int,
                 signers: frozenset, epoch: int):
        self.root_digest = root_digest
        self.commitment_index = commitment_index
        self.signers = signers
        self.epoch = epoch


class AgentState:
    def __init__(self, last_replayed_index: int, local_root: str):
        self.last_replayed_index = last_replayed_index
        self.local_root = local_root
        # mode is one of: PROPOSAL_ELIGIBLE, SYNCED_READONLY
        self.mode = "PROPOSAL_ELIGIBLE"


def accept_certificate(state: AgentState, qc: QuorumCertificate,
                       threshold: int, current_epoch: int) -> AgentState:
    # Cryptographic soundness: necessary, not sufficient.
    if len(qc.signers) < threshold:
        raise ProvenanceGapError(
            f"QC undersigned: {len(qc.signers)} < {threshold}")
    if qc.epoch != current_epoch:
        raise ProvenanceGapError(
            f"QC epoch {qc.epoch} != membership epoch {current_epoch}")

    # Adopt the certified root as current.
    state.local_root = qc.root_digest

    # Provenance gate: can we replay the gap?
    gap = qc.commitment_index - state.last_replayed_index
    if gap == 0:
        state.mode = "PROPOSAL_ELIGIBLE"
    elif gap == 1:
        # Single-round gap: replay is trivial and safe.
        state.last_replayed_index = qc.commitment_index
        state.mode = "PROPOSAL_ELIGIBLE"
    else:
        # Multi-round gap: root is current, history is not held.
        # Downgrade to read-only until re-sync completes.
        state.mode = "SYNCED_READONLY"
    return state


def propose_transition(state: AgentState, delta_fn) -> dict:
    if state.mode != "PROPOSAL_ELIGIBLE":
        raise ProvenanceGapError(
            "instance holds a certified root but has not replayed the "
            "commitment gap; proposing now would encode a stale pre-state "
            f"(last_replayed_index={state.last_replayed_index}, "
            f"root={state.local_root})")
    return delta_fn(state.local_root)


def complete_resync(state: AgentState, replayed_to_index: int,
                    verified_chain: bool) -> AgentState:
    if not verified_chain:
        raise ProvenanceGapError(
            "resync chain failed per-transition verification")
    state.last_replayed_index = replayed_to_index
    state.mode = "PROPOSAL_ELIGIBLE"
    return state
