# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-and-the-write-ahead-audit-log-diverges-from-the-committed-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-and-the-write-ahead-audit-log-diverges-from-the-committed-context.warrant.json
# Markdown SHA-256:   ef6b7b80493f72908e1c9b0caab2caa59026964e55e6e9dbd96cbfc46d95bfef
# Code AST SHA-256:   44b7f5367420dba24e9898a774bd42a0aaef4477ad5451a0db1185dddcfa5c4d
# Verified Classes:   ReplayDivergenceError, CommitBarrierViolation, EditRecord, SelfEditingBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ReplayDivergenceError(RuntimeError):
    """Raised when replayed buffer state does not match the logged post-edit hash."""
    pass


class CommitBarrierViolation(RuntimeError):
    """Raised when an edit is applied without a durable post-edit audit record."""
    pass


@dataclass
class EditRecord:
    edit_id: str
    pre_hash: str
    post_hash: str
    post_buffer: str


@dataclass
class SelfEditingBuffer:
    content: str
    version: int = 0
    log: list = field(default_factory=list)

    def _hash(self, s: str) -> str:
        return hashlib.sha256(s.encode()).hexdigest()

    def apply_edit(self, edit_id: str, new_content: str, audit_durable: bool) -> None:
        # Commit barrier: refuse to mutate unless the audit record for the
        # post-edit state is already durable. Approval != commit.
        if not audit_durable:
            raise CommitBarrierViolation(
                f"edit {edit_id} applied before post-edit audit record was durable"
            )
        pre_hash = self._hash(self.content)
        post_hash = self._hash(new_content)
        self.content = new_content
        self.version += 1
        self.log.append(EditRecord(edit_id, pre_hash, post_hash, new_content))

    def replay(self) -> "SelfEditingBuffer":
        # Reconstruct from log, asserting log-to-state equivalence at every edit.
        rebuilt = SelfEditingBuffer(content="")
        for rec in self.log:
            if rebuilt.content and self._hash(rebuilt.content) != rec.pre_hash:
                raise ReplayDivergenceError(
                    f"pre-hash mismatch at {rec.edit_id}: log and state diverged"
                )
            rebuilt.content = rec.post_buffer
            if self._hash(rebuilt.content) != rec.post_hash:
                raise ReplayDivergenceError(
                    f"post-hash mismatch at {rec.edit_id}: logged snapshot is stale"
                )
            rebuilt.version += 1
        return rebuilt


def resume_from_checkpoint(log: list) -> SelfEditingBuffer:
    buf = SelfEditingBuffer(content="")
    buf.log = log
    replayed = buf.replay()
    # Final equivalence assertion: replay must reproduce the live buffer exactly.
    if replayed.version != len(log):
        raise ReplayDivergenceError("replayed version does not match log length")
    return replayed
