# 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-quorum-but-its-own-prior-vote-is-silently-rewritten-by-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-quorum-but-its-own-prior-vote-is-silently-rewritten-by-context-compaction.warrant.json
# Markdown SHA-256:   6283b7d45e433079b1c7496483afd44146fa3b4ef3858789cd3d2e31bbfee844
# Code AST SHA-256:   833976c71020cb95d82b544e4d835f1e109991fca6cad086deaa5de05f6bcc71
# Verified Classes:   CommitmentAttestationError, CommitmentRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Callable, Optional


class CommitmentAttestationError(RuntimeError):
    """Raised when a committer's live attestation cannot be reconciled
    with its durable committed justification under the pinned vote function."""
    pass


@dataclass(frozen=True)
class CommitmentRecord:
    agent_id: str
    task_id: str
    vote: str
    justification: str          # full J, not just hash
    vote_fn_id: str            # pinned vote-function identity
    justification_hash: str    # hash(J) for fast equality checks


VOTE_FUNCTIONS: dict[str, Callable[[str], str]] = {
    # Deterministic function of J only. No ambient context.
    "v1": lambda j: "COMMIT" if ("validated" in j and "unvalidated" not in j) else "ABSTAIN",
}


def _hash(j: str) -> str:
    return hashlib.sha256(j.encode("utf-8")).hexdigest()


def make_record(agent_id: str, task_id: str, justification: str,
                vote_fn_id: str) -> CommitmentRecord:
    vote = VOTE_FUNCTIONS[vote_fn_id](justification)
    return CommitmentRecord(
        agent_id=agent_id,
        task_id=task_id,
        vote=vote,
        justification=justification,
        vote_fn_id=vote_fn_id,
        justification_hash=_hash(justification),
    )


def adjudicate_attestation(
    record: CommitmentRecord,
    live_attestation: str,
    live_justification: Optional[str],
) -> str:
    """
    Reconcile a live attestation against the durable commitment.
    Returns 'CONFIRMED' if consistent, 'COMPACTION_FIDELITY_EVENT' if the
    live attestation is a lossy artifact of the durable record.
    Raises CommitmentAttestationError only when the mismatch is
    unadjudicable (vote function missing or justification unrecoverable).
    """
    if record.vote_fn_id not in VOTE_FUNCTIONS:
        raise CommitmentAttestationError(
            f"pinned vote function {record.vote_fn_id!r} unavailable; "
            f"cannot re-derive vote for task {record.task_id}"
        )

    vote_fn = VOTE_FUNCTIONS[record.vote_fn_id]
    rederived = vote_fn(record.justification)

    if rederived != record.vote:
        raise CommitmentAttestationError(
            f"durable record for {record.agent_id}/{record.task_id} is "
            f"internally inconsistent: stored vote={record.vote!r} but "
            f"re-derivation yields {rederived!r}"
        )

    if live_attestation == record.vote:
        return "CONFIRMED"

    # Mismatch: the live attestation disagrees with the durable commit.
    # Do NOT trust the live attestation. Adjudicate against the record.
    if live_justification is not None and _hash(live_justification) == record.justification_hash:
        # Justification matches but attestation differs -> attestation bug.
        raise CommitmentAttestationError(
            f"attestation {live_attestation!r} contradicts matching "
            f"justification for {record.agent_id}/{record.task_id}"
        )

    # Live justification diverged -> compaction rewrote the agent's memory.
    # This is a fidelity event, not equivocation.
    return "COMPACTION_FIDELITY_EVENT"


if __name__ == "__main__":
    original_j = "target schema v3 confirmed present; rollback path validated against snapshot 4471"
    rec = make_record("agent-B", "task-migrate-17", original_j, "v1")
    assert rec.vote == "COMMIT"

    # After compaction, the agent's memory reads "unvalidated".
    compacted_j = "schema v3 present; rollback path unvalidated"
    live_attestation = VOTE_FUNCTIONS["v1"](compacted_j)  # -> ABSTAIN

    verdict = adjudicate_attestation(rec, live_attestation, compacted_j)
    print(verdict)  # COMPACTION_FIDELITY_EVENT
    assert verdict == "COMPACTION_FIDELITY_EVENT"
