# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-effect-double-commit-when-byzantine-peers-replay-signed-effect-warrants-across-a-multi-agent-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-effect-double-commit-when-byzantine-peers-replay-signed-effect-warrants-across-a-multi-agent-quorum.warrant.json
# Markdown SHA-256:   bf3a692f6b09654365d5d988caddeff39b2a587c8851f83caae3ad048fe423f9
# Code AST SHA-256:   a6ed185ba3284c3c849db25d0dcfbc60761511169bce263e51ed24d09e2fabd4
# Verified Classes:   StaleWarrantError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a warrant is authentic but fails the freshness invariant."""


@dataclass(frozen=True)
class Warrant:
    signer: str
    proposal_id: int
    epoch: int
    round: int
    payload_hash: str
    signature: str  # verified elsewhere; assumed valid here


def signed_digest(w: Warrant) -> str:
    # The invariant: identity is bound into the digest, not just the payload.
    material = f"{w.proposal_id}|{w.payload_hash}|{w.epoch}|{w.round}".encode()
    return hashlib.sha256(material).hexdigest()


def verify_warrant(
    w: Warrant,
    *,
    current_epoch: int,
    high_water: dict[str, int],
    expected_digest: str,
) -> None:
    if signed_digest(w) != expected_digest:
        raise StaleWarrantError(
            f"digest mismatch for signer={w.signer} id={w.proposal_id}"
        )
    if w.epoch != current_epoch:
        raise StaleWarrantError(
            f"epoch lag: warrant epoch={w.epoch} verifier epoch={current_epoch}"
        )
    prior = high_water.get(w.signer, -1)
    if w.proposal_id <= prior:
        raise StaleWarrantError(
            f"replay: signer={w.signer} proposal_id={w.proposal_id} "
            f"<= high_water={prior}"
        )
    high_water[w.signer] = w.proposal_id


def commit_effect(
    warrants: list[Warrant],
    *,
    quorum: int,
    current_epoch: int,
    high_water: dict[str, int],
    expected_digests: dict[str, str],
) -> str:
    seen_signers: set[str] = set()
    for w in warrants:
        verify_warrant(
            w,
            current_epoch=current_epoch,
            high_water=high_water,
            expected_digest=expected_digests[w.signer],
        )
        seen_signers.add(w.signer)
    if len(seen_signers) < quorum:
        raise StaleWarrantError(
            f"insufficient quorum: {len(seen_signers)} < {quorum}"
        )
    # Effect application happens only after all freshness checks pass.
    return hashlib.sha256(
        "|".join(sorted(signed_digest(w) for w in warrants)).encode()
    ).hexdigest()
