# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-editing-working-memory-as-a-transactional-commit-rather-than-an-in-place-mutation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-editing-working-memory-as-a-transactional-commit-rather-than-an-in-place-mutation.warrant.json
# Markdown SHA-256:   62cd11cf934515e9fa5b1f3ae97eb9d0aa443fb288857f0db59fef7480832cdc
# Code AST SHA-256:   07658c5f15c12ea2824288c9ca2136ebc8ad3ef8115eec0bf8ae53a812a69268
# Verified Classes:   CheckpointAliasedError, CircularValidationError, Checkpoint, TransactionalWorkingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CheckpointAliasedError(RuntimeError):
    """Raised when a rollback target's storage was mutated in place."""
    pass


class CircularValidationError(RuntimeError):
    """Raised when a self-edit is validated against the buffer it wrote."""
    pass


@dataclass
class Checkpoint:
    digest: str
    payload: bytes


@dataclass
class TransactionalWorkingMemory:
    committed: bytes = b""
    checkpoints: dict[str, Checkpoint] = field(default_factory=dict)

    def _digest(self, data: bytes) -> str:
        return hashlib.sha256(data).hexdigest()

    def checkpoint(self, label: str) -> str:
        cp = Checkpoint(digest=self._digest(self.committed), payload=self.committed)
        self.checkpoints[label] = cp
        return label

    def stage_edit(self, new_state: bytes) -> bytes:
        # Copy-on-write: the candidate lives off the committed buffer.
        return new_state

    def validate_staged(self, staged: bytes, predicate) -> bool:
        # Predicate must run on staged bytes, never on self.committed.
        return bool(predicate(staged))

    def commit(self, staged: bytes) -> None:
        # Atomic swap: committed pointer moves; old bytes remain reachable
        # via checkpoints, so no checkpoint is aliased.
        self.committed = staged

    def rollback(self, label: str) -> bytes:
        cp = self.checkpoints.get(label)
        if cp is None:
            raise CheckpointAliasedError(f"no checkpoint {label!r}")
        # Fail closed: if the stored payload no longer matches its digest,
        # the storage was mutated in place and the restore is a chimera.
        if self._digest(cp.payload) != cp.digest:
            raise CheckpointAliasedError(
                f"checkpoint {label!r} aliased: digest mismatch, refusing chimera restore"
            )
        self.committed = cp.payload
        return self.committed


def self_edit(
    wm: TransactionalWorkingMemory,
    new_state: bytes,
    predicate,
    checkpoint_label: str,
) -> None:
    # Guard: validation must not read the committed buffer post-write.
    if predicate.__code__.co_freevars and "committed" in predicate.__code__.co_freevars:
        raise CircularValidationError(
            "predicate closes over working set; validate staged bytes instead"
        )
    staged = wm.stage_edit(new_state)
    if not wm.validate_staged(staged, predicate):
        # Reject before touching committed state; rollback remains reachable.
        raise CheckpointAliasedError("staged edit failed validation; committed state intact")
    wm.commit(staged)
    wm.checkpoint(checkpoint_label)
