# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-a-plan-when-a-byzantine-peer-s-vote-is-internally-consistent-but-contradicts-its-own-prior-signed-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-a-plan-when-a-byzantine-peer-s-vote-is-internally-consistent-but-contradicts-its-own-prior-signed-state.warrant.json
# Markdown SHA-256:   f55c221c0757668306736e542a46f34d5e4ff7715612d250f74bfa1c10e175ea
# Code AST SHA-256:   2151fdca606d51aa9abf9302683f5ec500e584d336f977f1ad45ee4fcb55b639
# Verified Classes:   DuplicateSlotVoteError, SignedVote, DurableVoteLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class DuplicateSlotVoteError(RuntimeError):
    """Raised when an agent attempts to sign a second, conflicting vote
    for an already-occupied (plan_id, epoch, slot) slot.

    This is the single-assignment guard that keeps a probabilistic agent
    from becoming the equivocator via context amnesia or retry drift.
    """


@dataclass
class SignedVote:
    plan_id: str
    epoch: int
    slot: int
    seq: int
    fragment_hash: str
    signature: str


@dataclass
class DurableVoteLog:
    # key: (plan_id, epoch, slot) -> the one authoritative vote for that slot
    _slots: dict = field(default_factory=dict)

    def get(self, plan_id: str, epoch: int, slot: int) -> SignedVote | None:
        return self._slots.get((plan_id, epoch, slot))

    def put(self, vote: SignedVote) -> None:
        self._slots[(vote.plan_id, vote.epoch, vote.slot)] = vote


def _sign(payload: dict) -> str:
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


def sign_vote(
    log: DurableVoteLog,
    plan_id: str,
    epoch: int,
    slot: int,
    seq: int,
    fragment: str,
) -> SignedVote:
    """The signing edge. The LLM proposes a fragment; this function decides
    whether a signature may be produced. It reads DURABLE state, never the
    model's context, before signing.
    """
    fragment_hash = hashlib.sha256(fragment.encode()).hexdigest()
    prior = log.get(plan_id, epoch, slot)

    if prior is not None:
        if prior.fragment_hash == fragment_hash:
            # Idempotent replay: same fragment, safe to re-emit the prior vote.
            return prior
        # Conflicting vote for an occupied slot -> equivocation attempt.
        raise DuplicateSlotVoteError(
            f"slot ({plan_id},{epoch},{slot}) already signed as seq={prior.seq} "
            f"over fragment {prior.fragment_hash[:12]}; refusing to sign "
            f"conflicting fragment {fragment_hash[:12]} (seq={seq}). "
            f"Emit a reconsider() advisory instead of a second vote."
        )

    vote = SignedVote(
        plan_id=plan_id,
        epoch=epoch,
        slot=slot,
        seq=seq,
        fragment_hash=fragment_hash,
        signature=_sign(
            {"plan_id": plan_id, "epoch": epoch, "slot": slot,
             "seq": seq, "fragment_hash": fragment_hash}
        ),
    )
    log.put(vote)
    return vote


def reconsider(plan_id: str, epoch: int, slot: int, preferred_fragment: str) -> dict:
    """Advisory message type. Does NOT occupy the slot; lets the model change
    its mind without forking the quorum."""
    return {
        "type": "reconsider",
        "plan_id": plan_id,
        "epoch": epoch,
        "slot": slot,
        "preferred_fragment_hash": hashlib.sha256(preferred_fragment.encode()).hexdigest(),
    }


if __name__ == "__main__":
    log = DurableVoteLog()
    # Epoch 17, slot 3: first vote over fragment P_a.
    sign_vote(log, "plan-remediate-7", 17, 3, seq=41, fragment="P_a")

    # Context eviction + retry re-derives a different fragment P_b.
    try:
        sign_vote(log, "plan-remediate-7", 17, 3, seq=58, fragment="P_b")
    except DuplicateSlotVoteError as e:
        print("guard fired:", e)
        # Correct recovery: advisory, not a second vote.
        print(reconsider("plan-remediate-7", 17, 3, "P_b"))
