# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-before-its-quorum-certificate-is-durably-anchored-the-pre-commit-divergence-boundary-in-bft-agent-cons.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-before-its-quorum-certificate-is-durably-anchored-the-pre-commit-divergence-boundary-in-bft-agent-cons.warrant.json
# Markdown SHA-256:   10883d327899cfaa045c08986180d7c424de65b58154e8b585e8a81019abffb6
# Code AST SHA-256:   67b35a9dbb77ccc976ce8bb8d446d551bc70ad2cc9bed238e0a24b9d7153c757
# Verified Classes:   PreCommitDivergenceError, SignedCommit, DurableCommitLog, SigningGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class PreCommitDivergenceError(RuntimeError):
    """Raised when an agent attempts to sign a commitment that conflicts with a
    durably recorded prior commitment for the same slot, or when the durability
    log cannot be fsynced before the signature is released to transport."""


@dataclass
class SignedCommit:
    slot: str
    epoch: int
    value_hash: str
    signature: str


@dataclass
class DurableCommitLog:
    """Deterministic, fsync-before-ack per-slot nonce log. Lives OUTSIDE the
    LLM reasoning loop. The LLM cannot read or write this directly; it can only
    request a signature through `SigningGate.sign_commit`."""
    _records: dict[str, SignedCommit] = field(default_factory=dict)
    _fsynced: set[str] = field(default_factory=set)

    def highest_epoch(self, slot: str) -> Optional[int]:
        rec = self._records.get(slot)
        return rec.epoch if rec else None

    def append_and_fsync(self, commit: SignedCommit) -> None:
        self._records[commit.slot] = commit
        # Simulated fsync: in production, this is a real os.fsync on the WAL fd.
        # If fsync fails, the record must NOT be considered durable.
        if not self._simulate_fsync():
            raise PreCommitDivergenceError(
                f"fsync failed for slot={commit.slot} epoch={commit.epoch}; "
                f"signature must not be released to transport"
            )
        self._fsynced.add(commit.slot)

    def _simulate_fsync(self) -> bool:
        # Placeholder: real implementations call os.fsync and check errno.
        return True


class SigningGate:
    """The only path from an LLM-proposed commitment to a transmitted signature.
    Enforces the BFT safety invariant: never sign a conflicting value for a slot
    at an epoch <= the highest durably recorded epoch for that slot."""

    def __init__(self, log: DurableCommitLog):
        self.log = log

    def sign_commit(
        self, slot: str, epoch: int, value: str, key: bytes
    ) -> SignedCommit:
        value_hash = hashlib.sha256(value.encode()).hexdigest()
        prior_epoch = self.log.highest_epoch(slot)

        # Invariant check: reject any re-sign at an epoch we have already
        # durably committed, regardless of value. This is the boundary guard.
        if prior_epoch is not None and epoch <= prior_epoch:
            prior = self.log._records[slot]
            if prior.value_hash != value_hash:
                raise PreCommitDivergenceError(
                    f"conflicting commitment for slot={slot}: "
                    f"durable record epoch={prior.epoch} value_hash={prior.value_hash[:12]} "
                    f"vs proposed epoch={epoch} value_hash={value_hash[:12]}. "
                    f"Refusing to sign; this would create a second quorum."
                )
            # Same value, same-or-lower epoch: idempotent, but still must be durable.
            return prior

        # Construct the signature deterministically from the durable record.
        sig = hashlib.sha256(
            f"{slot}:{epoch}:{value_hash}".encode() + key
        ).hexdigest()
        commit = SignedCommit(slot=slot, epoch=epoch, value_hash=value_hash, signature=sig)

        # Durability BEFORE transmission. If this raises, no signature escapes.
        self.log.append_and_fsync(commit)
        return commit


def handle_proposal(
    gate: SigningGate,
    slot: str,
    epoch: int,
    value: str,
    key: bytes,
    *,
    agent_context_saturated: bool,
) -> SignedCommit:
    """Entry point invoked by the agent runtime on receipt of a proposal.
    The LLM may have proposed `value` after reasoning over a context window;
    that reasoning is untrusted. The gate is the trust boundary."""
    if agent_context_saturated:
        # Saturation is a *risk signal*, not a bypass. The gate still runs.
        # Log it so auditors can correlate divergences with eviction events.
        pass
    try:
        return gate.sign_commit(slot=slot, epoch=epoch, value=value, key=key)
    except PreCommitDivergenceError:
        # Re-raise with operational context; never swallow.
        raise PreCommitDivergenceError(
            f"agent refused to sign slot={slot} epoch={epoch} "
            f"(context_saturated={agent_context_saturated}); "
            f"escalating to auditor for replay against transport log"
        )


if __name__ == "__main__":
    log = DurableCommitLog()
    gate = SigningGate(log)
    key = b"replica-A3-key"

    # Epoch 4: A3 signs R, durably recorded before transmission.
    c4 = handle_proposal(gate, "T7", 4, "result_R", key, agent_context_saturated=True)
    print("committed epoch 4:", c4.value_hash[:12])

    # Epoch 5: Byzantine leader equivocates with R'. A3's context was evicted,
    # so its LLM "forgets" the epoch-4 commit — but the gate does not.
    try:
        handle_proposal(gate, "T7", 5, "result_R_prime", key, agent_context_saturated=True)
    except PreCommitDivergenceError as e:
        print("BLOCKED:", e)
