# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-just-committed-the-write-verify-echo-gap-in-long-horizon-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-just-committed-the-write-verify-echo-gap-in-long-horizon-agents.warrant.json
# Markdown SHA-256:   a77e7c6243fa3141bc7fa196ed597a1685b7edc31cfa6cb7ad520915ffc394dd
# Code AST SHA-256:   c642d585d03bdd271554fd10af6aef28598cf205ad8bc27150b3dbd01450314e
# Verified Classes:   MemoryIntegrityError, FailureClass, WriteWitness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class MemoryIntegrityError(RuntimeError):
    """Raised when a memory write cannot be certified by an independent witness."""


class FailureClass(Enum):
    WRITE_PATH_MUTATION = "write_path_mutation"      # pre != ack, ack == read
    READ_PATH_TRANSFORM = "read_path_transform"      # pre == ack, ack != read
    PATH_ASYMMETRY = "path_asymmetry"                # pre == ack != read, read != ack
    SYMMETRIC_POISON = "symmetric_poison"            # pre != ack == read (echo passes, record poisoned)
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class WriteWitness:
    pre_write_hash: str      # hash of payload BEFORE store.write, captured out-of-band
    write_ack_hash: str      # hash of the write path's acknowledgment payload
    read_back_hash: str      # hash of an independent read after commit


def _h(payload: str) -> str:
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def certify_write(payload: str, store, witness_sink) -> WriteWitness:
    """Write payload, then certify via three-way hash comparison.

    The pre_write_hash MUST be captured before store.write and MUST be
    persisted to witness_sink (a path independent of the store), so that
    context eviction cannot erase the anchor.
    """
    pre = _h(payload)
    witness_sink.record(pre)                      # anchor outside write path

    ack = store.write(payload)                    # may be mutated by wrapper
    ack_hash = _h(ack)

    read_back = store.read(ack.key)               # may be transformed by indexer
    read_hash = _h(read_back)

    witness = WriteWitness(pre, ack_hash, read_hash)
    return witness


def classify(w: WriteWitness) -> FailureClass:
    if w.pre_write_hash == w.write_ack_hash == w.read_back_hash:
        return None  # certified
    if w.pre_write_hash != w.write_ack_hash and w.write_ack_hash == w.read_back_hash:
        return FailureClass.SYMMETRIC_POISON
    if w.pre_write_hash == w.write_ack_hash and w.write_ack_hash != w.read_back_hash:
        return FailureClass.READ_PATH_TRANSFORM
    if w.pre_write_hash != w.write_ack_hash and w.write_ack_hash != w.read_back_hash:
        return FailureClass.PATH_ASYMMETRY
    return FailureClass.UNKNOWN


def commit_memory(payload: str, store, witness_sink, escalation_channel):
    witness = certify_write(payload, store, witness_sink)
    failure = classify(witness)

    if failure is None:
        return witness

    # Echo-equality alone would have passed on SYMMETRIC_POISON; we must not retry.
    if failure in (FailureClass.SYMMETRIC_POISON, FailureClass.UNKNOWN):
        escalation_channel.quarantine(payload, witness, reason=failure.value)
        raise MemoryIntegrityError(
            f"memory write not certifiable: {failure.value}; "
            f"pre={witness.pre_write_hash[:12]} ack={witness.write_ack_hash[:12]} "
            f"read={witness.read_back_hash[:12]}"
        )

    if failure is FailureClass.READ_PATH_TRANSFORM:
        # Retry is harmful (non-deterministic re-summarization diverges);
        # persist a transform-normalized form and re-certify.
        normalized = payload.strip()
        if _h(normalized) == witness.read_back_hash:
            return certify_write(normalized, store, witness_sink)
        raise MemoryIntegrityError(
            "read-path transform not reproducible by normalization; "
            "refusing retry to avoid divergence"
        )

    # PATH_ASYMMETRY: localize before acting; do not blindly retry.
    raise MemoryIntegrityError(
        f"path asymmetry requires manual localization: {failure.value}"
    )
