# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-commitment-quorum-admit-a-forged-task-commit-certificate-when-the-faulty-fraction-stays-below-f-n-1.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-commitment-quorum-admit-a-forged-task-commit-certificate-when-the-faulty-fraction-stays-below-f-n-1.warrant.json
# Markdown SHA-256:   4532d2a4a29f99977dbff6f46be3c3585918e67cb217e0a8cedcf75453505fbd
# Code AST SHA-256:   40e7a90fc7c30352952a5ed09eb5ebaeb2c8ffb165a9cefe6f2bbee29193d1c0
# Verified Classes:   StaleEpochSignatureError, CommitmentSigner
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleEpochSignatureError(RuntimeError):
    """Raised when a commitment signature is produced from a reconstructed
    (rather than re-anchored) epoch counter, enabling certificate forgery
    below the classical f < n/3 bound."""
    pass


class CommitmentSigner:
    def __init__(self, agent_id: str, durable_store):
        self.agent_id = agent_id
        self.durable_store = durable_store
        self._resume_barrier_passed = False
        self._last_signed_epoch = None

    def on_resume_from_checkpoint(self, checkpoint_epoch: int) -> None:
        # Resume barrier: the counter MUST come from durable state, not from
        # episodic memory / reconstructed context.
        durable_epoch = self.durable_store.read_last_signed_epoch(self.agent_id)
        if durable_epoch is None:
            raise StaleEpochSignatureError(
                f"agent {self.agent_id} resumed at checkpoint epoch "
                f"{checkpoint_epoch} but durable counter is absent; "
                f"refusing to sign until re-anchored"
            )
        if durable_epoch < checkpoint_epoch:
            raise StaleEpochSignatureError(
                f"durable epoch {durable_epoch} < checkpoint epoch "
                f"{checkpoint_epoch}; context drift suspected"
            )
        self._last_signed_epoch = durable_epoch
        self._resume_barrier_passed = True

    def sign_commitment(self, task_id: str, cap_hash: str, epoch: int) -> bytes:
        if not self._resume_barrier_passed:
            raise StaleEpochSignatureError(
                f"agent {self.agent_id} attempted to sign {task_id} at "
                f"epoch {epoch} without passing the resume barrier"
            )
        if self._last_signed_epoch is not None and epoch <= self._last_signed_epoch:
            raise StaleEpochSignatureError(
                f"agent {self.agent_id} attempted to sign epoch {epoch} "
                f"<= last_signed_epoch {self._last_signed_epoch}; "
                f"stale-epoch replay would enable certificate forgery"
            )
        # Epoch and agent_id MUST be inside the signed payload, not the envelope.
        payload = f"{task_id}|{self.agent_id}|{cap_hash}|{epoch}".encode()
        self.durable_store.write_last_signed_epoch(self.agent_id, epoch)
        self._last_signed_epoch = epoch
        return self._sign(payload)

    def _sign(self, payload: bytes) -> bytes:
        # Placeholder for the agent's signing primitive.
        return b"sig:" + payload
