# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-byzantine-memory-forks-from-surviving-quorum-reconciliation-in-multi-agent-shared-context.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-byzantine-memory-forks-from-surviving-quorum-reconciliation-in-multi-agent-shared-context.warrant.json
# Markdown SHA-256:   cf7c9876823a7dd444d2999dee94203e9f850bf6e22f110e8a6136e9d62ff965
# Code AST SHA-256:   a4543178b21a23028dce8841c64203ee93bb2d8dc5c4b9c00b439f4409650b4b
# Verified Classes:   ProvenanceChainError, MemoryRecord, ReplicatedMemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceChainError(RuntimeError):
    """Raised when a memory record cannot be verified to genesis, or a fork
    is reconciled while a losing-branch read-fence is still open."""


@dataclass
class MemoryRecord:
    slot: int
    content: bytes
    predecessor_hash: Optional[str]
    provenance: list  # ordered (agent_id, prior_hash, tool_digest) tuples
    record_hash: str = field(init=False)

    def __post_init__(self):
        h = hashlib.sha256()
        h.update(str(self.slot).encode())
        h.update(self.content)
        h.update((self.predecessor_hash or "GENESIS").encode())
        for agent_id, prior, digest in self.provenance:
            h.update(f"{agent_id}:{prior}:{digest}".encode())
        self.record_hash = h.hexdigest()


class ReplicatedMemoryStore:
    def __init__(self, genesis_hash: str):
        self.genesis_hash = genesis_hash
        self.committed: dict[int, MemoryRecord] = {}
        self.read_fences: set[str] = set()  # record_hash values read into context

    def verify_provenance(self, record: MemoryRecord) -> None:
        # Every predecessor in the chain must resolve to a committed record
        # or to genesis. Deferral is forbidden; unresolvable => reject.
        seen = set()
        cursor = record
        while cursor.predecessor_hash is not None:
            pred = cursor.predecessor_hash
            if pred == self.genesis_hash:
                return
            if pred in seen:
                raise ProvenanceChainError(f"cycle in provenance at {pred}")
            seen.add(pred)
            parent = next(
                (r for r in self.committed.values() if r.record_hash == pred), None
            )
            if parent is None:
                raise ProvenanceChainError(
                    f"unresolvable predecessor {pred} for record "
                    f"{record.record_hash[:12]}; refusing to defer"
                )
            cursor = parent

    def prepare(self, record: MemoryRecord, acceptor_head: Optional[str]) -> None:
        self.verify_provenance(record)
        if record.predecessor_hash != acceptor_head:
            raise ProvenanceChainError(
                f"predecessor mismatch: proposer cites "
                f"{record.predecessor_hash}, acceptor head is {acceptor_head}"
            )

    def open_read_fence(self, record_hash: str) -> None:
        self.read_fences.add(record_hash)

    def reconcile(self, slot: int, winner: MemoryRecord, loser: MemoryRecord) -> None:
        if loser.record_hash in self.read_fences:
            raise ProvenanceChainError(
                f"cannot reconcile slot {slot}: loser {loser.record_hash[:12]} "
                f"has an open read-fence; derived actions may be externally "
                f"visible. Abort task or drain fence before commit."
            )
        self.committed[slot] = winner
        self.read_fences.discard(loser.record_hash)


def commit_memory(
    store: ReplicatedMemoryStore,
    record: MemoryRecord,
    acceptor_head: Optional[str],
    quorum_hashes: list[str],
) -> None:
    """Admit a record only if provenance closes, predecessor binds, and no
    competing branch at the slot carries an open read-fence."""
    store.prepare(record, acceptor_head)
    for h in quorum_hashes:
        if h in store.read_fences and h != record.record_hash:
            raise ProvenanceChainError(
                f"quorum member {h[:12]} has an open read-fence on a "
                f"competing branch at slot {record.slot}; commit would "
                f"create an unrecoverable execution divergence"
            )
    store.committed[record.slot] = record
