# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-joins-a-byzantine-consensus-round-with-a-divergent-commitment-log.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-joins-a-byzantine-consensus-round-with-a-divergent-commitment-log.warrant.json
# Markdown SHA-256:   b36dc5434d3101ff23c7c22e59995d7f940b2e96ef57d6bd470e97882e71abc2
# Code AST SHA-256:   60e093f20950c82be525b7e11d813c97df802ce5a22d4070d4b9e264361a3e9d
# Verified Classes:   DivergentCommitmentLogError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DivergentCommitmentLogError(RuntimeError):
    """Raised when a restored agent's log tip is not a certified prefix."""
    pass


def restore_from_checkpoint(checkpoint: dict, quorum_verifier) -> dict:
    log_tip = checkpoint["log_tip_hash"]
    certified = checkpoint["last_certified_hash"]
    cert = checkpoint["last_certificate"]

    # Invariant: a checkpoint may only persist certified state.
    if log_tip != certified:
        raise DivergentCommitmentLogError(
            f"checkpoint log_tip {log_tip[:12]} != certified {certified[:12]}; "
            f"uncommitted proposals leaked into persistence"
        )

    # Invariant: the certificate must still carry 2f+1 valid signatures.
    if not quorum_verifier.verify(cert, expected_parent=certified):
        raise DivergentCommitmentLogError(
            f"certificate for {certified[:12]} failed quorum verification on restore"
        )

    return {"log": checkpoint["log"][: checkpoint["certified_index"] + 1],
            "last_certified_hash": certified}


def checkpoint_agent(agent) -> dict:
    # Truncate to the last certified entry before serializing.
    idx = agent.last_certified_index
    if agent.log[idx].entry_hash != agent.last_certified_hash:
        raise DivergentCommitmentLogError(
            "internal state inconsistency: certified index does not match certified hash"
        )
    return {
        "log": agent.log[: idx + 1],
        "certified_index": idx,
        "log_tip_hash": agent.log[idx].entry_hash,
        "last_certified_hash": agent.last_certified_hash,
        "last_certificate": agent.certificates[idx],
    }
