# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-byzantine-plan-commitments-before-it-can-safely-act-on-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-byzantine-plan-commitments-before-it-can-safely-act-on-shared-state.warrant.json
# Markdown SHA-256:   8488ed137f9f866e5da467905a6b3fcd71a99d842ead3d5fbf30e9b1fb793d64
# Code AST SHA-256:   80c917dc6ee217467cb9593bb6d0d6290c850cba70e9ea5be4c9684da45c461f
# Verified Classes:   StateCommitmentDivergence, Commitment, StateView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StateCommitmentDivergence(RuntimeError):
    """Raised when reconciled state is not causally bound to the plan commitment."""
    pass


@dataclass(frozen=True)
class Commitment:
    epoch: int
    plan_id: str
    state_root_digest: str
    signers: frozenset[str]


@dataclass(frozen=True)
class StateView:
    epoch: int
    root: bytes
    attesters: frozenset[str]


def digest(root: bytes) -> str:
    return hashlib.sha256(root).hexdigest()


def gate_execution(commitment: Commitment, state: StateView, quorum: int) -> None:
    """Enforce the state-commitment binding before any side-effecting action.

    Raises StateCommitmentDivergence when the state an agent is about to act on
    is not the state the commitment authorized, or is not quorum-attested.
    """
    if state.epoch != commitment.epoch:
        raise StateCommitmentDivergence(
            f"epoch mismatch: commitment at {commitment.epoch}, "
            f"state at {state.epoch}"
        )

    if digest(state.root) != commitment.state_root_digest:
        raise StateCommitmentDivergence(
            "state root digest does not match commitment binding; "
            "refusing to execute against unbound state"
        )

    valid_attesters = state.attesters & commitment.signers
    if len(valid_attesters) < quorum:
        raise StateCommitmentDivergence(
            f"state root attested by {len(valid_attesters)} commitment signers, "
            f"need {quorum}; single-source state is not authoritative"
        )


def execute_step(commitment: Commitment, state: StateView, quorum: int,
                 step_fn) -> None:
    # Gate is re-checked at every side-effecting boundary, not just plan start,
    # because reconciliation can occur mid-execution.
    gate_execution(commitment, state, quorum)
    step_fn(state)
