# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-fault-tolerant-quorum-rules-while-its-own-memory-of-the-commitment-is-lossy.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-fault-tolerant-quorum-rules-while-its-own-memory-of-the-commitment-is-lossy.warrant.json
# Markdown SHA-256:   c509441a52919b01497d0fca973efff86e6e95b9714f2a5272698a0b3dd06013
# Code AST SHA-256:   0c571c23ee28d0cc9e706692901221d1437653767c237d3b0c2234bfab567427
# Verified Classes:   CommitmentLedgerMismatch, CommitmentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CommitmentLedgerMismatch(RuntimeError):
    """Raised when an agent's reconstructed memory of a commitment
    disagrees with the signed ledger entry for the same task slot.
    This is the boundary condition: the agent is about to vote on
    the basis of a summary, not a literal, and the two disagree."""
    pass


class CommitmentLedger:
    def __init__(self, replica_id: str):
        self.replica_id = replica_id
        self._entries: dict[str, dict] = {}  # task_slot -> literal commitment

    def record_prepare(self, task_slot: str, value: dict) -> None:
        # Store literals only; references like "self" are resolved here.
        literal = dict(value)
        if literal.get("assignee") in ("self", "me", None):
            literal["assignee"] = self.replica_id
        self._entries[task_slot] = literal

    def read(self, task_slot: str) -> dict:
        if task_slot not in self._entries:
            raise CommitmentLedgerMismatch(
                f"no signed commitment for slot {task_slot!r}; "
                f"agent must abstain, not reconstruct from memory"
            )
        return self._entries[task_slot]


def vote_on_proposal(
    ledger: CommitmentLedger,
    task_slot: str,
    proposal: dict,
    memory_summary: dict,
) -> str:
    """Decide PREPARE/REJECT for a proposal, using the ledger as the
    authority and the memory summary only as a cross-check."""
    try:
        prior = ledger.read(task_slot)
    except CommitmentLedgerMismatch:
        # Cannot verify against signed history -> abstain, never guess.
        return "ABSTAIN"

    # Cross-check: if memory disagrees with ledger, memory is stale.
    # The ledger wins, but the disagreement is a reportable event.
    mem_assignee = memory_summary.get("assignee")
    if mem_assignee is not None and mem_assignee != prior.get("assignee"):
        # Memory drift detected. Do not vote on memory; vote on ledger.
        # But surface the drift so operators can audit compaction.
        _report_drift(task_slot, prior, memory_summary)

    if proposal == prior:
        return "PREPARE"
    # Genuine conflict with signed history: legitimate REJECT.
    return "REJECT"


def _report_drift(task_slot: str, ledger_value: dict, memory_value: dict) -> None:
    # In production this emits to the audit channel; here it is a no-op
    # that exists to make the drift observable rather than silent.
    if ledger_value.get("assignee") != memory_value.get("assignee"):
        # If the ledger and memory disagree on a literal that affects
        # vote correctness, escalate rather than proceed silently.
        raise CommitmentLedgerMismatch(
            f"slot {task_slot!r}: ledger assignee="
            f"{ledger_value.get('assignee')!r} vs memory assignee="
            f"{memory_value.get('assignee')!r}; compaction is lossy "
            f"on a consensus-critical field"
        )
