# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-shared-task-ledger-under-byzantine-quorum-while-its-own-episodic-memory-is-being-compacted-the-equivocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-shared-task-ledger-under-byzantine-quorum-while-its-own-episodic-memory-is-being-compacted-the-equivocation.warrant.json
# Markdown SHA-256:   209121c6bc13fe9082810aec34a0934e6c6c8db482abbd610e44eec98854bf28
# Code AST SHA-256:   525e18161bad2a40ddd6d709af3b5c0d3800246660cbc1459abeeaa70aeb7860
# Verified Classes:   ByzantineCompactionEquivocation, Vote, CommitmentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Tuple


class ByzantineCompactionEquivocation(RuntimeError):
    """Raised when an honest agent emits two inconsistent votes for the same
    (task_id, epoch) because its episodic memory was compacted mid-epoch."""
    pass


@dataclass
class Vote:
    agent_id: str
    task_id: str
    epoch: int
    decision: str          # "commit" | "abort"
    nonce: str
    signature: str


@dataclass
class CommitmentLedger:
    # Durable, append-only. Keyed on (signer, task, epoch) — NOT on nonce.
    _votes: Dict[Tuple[str, str, int], Vote] = field(default_factory=dict)

    def record(self, vote: Vote) -> None:
        key = (vote.agent_id, vote.task_id, vote.epoch)
        prior = self._votes.get(key)
        if prior is not None and prior.decision != vote.decision:
            # Same honest signer, same epoch, conflicting decision.
            # Nonce differs, so a nonce-keyed guard would have missed this.
            raise ByzantineCompactionEquivocation(
                f"agent {vote.agent_id} equivocated on task {vote.task_id} "
                f"epoch {vote.epoch}: {prior.decision} -> {vote.decision} "
                f"(nonces {prior.nonce} vs {vote.nonce}); "
                f"likely compaction-induced memory rewrite"
            )
        self._votes[key] = vote


def cast_vote(
    agent_id: str,
    task_id: str,
    epoch: int,
    episodic_memory: dict,
    ledger: CommitmentLedger,
    compaction_barrier_open: bool,
) -> Vote:
    """Vote path. Must read only from memory frozen for the epoch."""
    if compaction_barrier_open:
        # Guardrail 1: the compactor must be quiesced while an epoch is open.
        raise ByzantineCompactionEquivocation(
            f"refusing to vote on {task_id} epoch {epoch}: "
            f"compaction barrier open, episodic memory mutable mid-epoch"
        )

    decision = "commit" if episodic_memory.get(task_id) == "safe" else "abort"
    nonce = hashlib.sha256(f"{agent_id}{task_id}{epoch}{decision}".encode()).hexdigest()[:8]
    vote = Vote(agent_id, task_id, epoch, decision, nonce, signature=f"sig:{nonce}")

    # Guardrail 2: durable ledger keyed on (signer, task, epoch).
    ledger.record(vote)
    return vote
