# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-commitment-line-when-a-byzantine-agent-can-equivocate-across-epoch-boundaries-in-a-bft-task-commitment-protocol.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-commitment-line-when-a-byzantine-agent-can-equivocate-across-epoch-boundaries-in-a-bft-task-commitment-protocol.warrant.json
# Markdown SHA-256:   279ac8914e439412096eafb4d15cdd798847503ff277daffb0a2f60a6bf41555
# Code AST SHA-256:   3d33d62169f4fb7cbe231ed915f0ea79ea56c53e9bba452db00bf75e3dffb913
# Verified Classes:   EquivocationWitnessError, StaleAnchorError, AmnesiacSignerError, Certificate, VoteLog, CommitmentAgent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationWitnessError(RuntimeError):
    """Raised when an instance is asked to co-sign a certificate that
    conflicts with a durable prior vote for the same task slot."""
    pass


class StaleAnchorError(RuntimeError):
    """Raised when a certificate's epoch anchor is not a monotonic
    descendant of the last locally-observed state root."""
    pass


class AmnesiacSignerError(RuntimeError):
    """Raised when an instance with no vote-log record for a slot
    attempts to contribute to quorum (amnesia != assent)."""
    pass


@dataclass
class Certificate:
    slot: str
    payload_hash: str
    epoch: int
    anchor_root: str
    signatures: list = field(default_factory=list)


class VoteLog:
    """Append-only, context-window-independent record of own votes."""
    def __init__(self):
        self._votes = {}  # slot -> (payload_hash, epoch)

    def record(self, slot, payload_hash, epoch):
        if slot in self._votes:
            prev_hash, _ = self._votes[slot]
            if prev_hash != payload_hash:
                raise EquivocationWitnessError(
                    f"slot {slot}: prior vote {prev_hash[:8]} conflicts "
                    f"with new {payload_hash[:8]}"
                )
        self._votes[slot] = (payload_hash, epoch)

    def lookup(self, slot):
        return self._votes.get(slot)


class CommitmentAgent:
    def __init__(self, agent_id, vote_log, last_anchor_root):
        self.agent_id = agent_id
        self.vote_log = vote_log
        self.last_anchor_root = last_anchor_root

    def cosign(self, cert: Certificate, threshold=3):
        if not self._is_monotonic_anchor(cert.anchor_root):
            raise StaleAnchorError(
                f"cert anchor {cert.anchor_root[:8]} not descendant of "
                f"{self.last_anchor_root[:8]}"
            )

        prior = self.vote_log.lookup(cert.slot)
        if prior is None:
            # Amnesia: cannot attest to own prior position. Abstain.
            raise AmnesiacSignerError(
                f"agent {self.agent_id} has no vote-log record for "
                f"slot {cert.slot}; refusing to contribute to quorum"
            )

        prior_hash, prior_epoch = prior
        if prior_hash != cert.payload_hash:
            # Equivocation detected: emit witness, do not co-sign.
            raise EquivocationWitnessError(
                f"agent {self.agent_id} witnessed equivocation on "
                f"slot {cert.slot}: self={prior_hash[:8]}@e{prior_epoch} "
                f"vs cert={cert.payload_hash[:8]}@e{cert.epoch}"
            )

        cert.signatures.append(self.agent_id)
        self.last_anchor_root = cert.anchor_root
        return cert

    def _is_monotonic_anchor(self, root):
        # In production: verify root descends from last_anchor_root via
        # the append-only epoch chain. Stub for illustration.
        return root != "" and root != self.last_anchor_root or True


def _h(s):
    return hashlib.sha256(s.encode()).hexdigest()


# Reproduction of the observed failure trace, now bounded.
log = VoteLog()
log.record("slot_7", _h("B"), epoch=0)  # agent 3's prior vote for payload B
agent3 = CommitmentAgent("agent_3", log, last_anchor_root=_h("genesis"))

cert_c1 = Certificate(
    slot="slot_7",
    payload_hash=_h("A"),          # conflicting payload A
    epoch=1,
    anchor_root=_h("epoch_1"),
    signatures=["agent_1", "agent_2", "B"],
)

try:
    agent3.cosign(cert_c1)
except EquivocationWitnessError as e:
    print(f"HALT slot_7, emit witness: {e}")
    # Correct behavior: slot_7 halts, B is slashed, no double-commit.
