# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-it-cannot-provenance-the-unauthenticated-append-hole-in-read-write-forget-memory-tool-contracts.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-it-cannot-provenance-the-unauthenticated-append-hole-in-read-write-forget-memory-tool-contracts.warrant.json
# Markdown SHA-256:   9e8a726ce636139722e37d96f63c2b027a22a733986c1e7fc9d06cd10af5a748
# Code AST SHA-256:   89863a004a1777801bfab4b4dae9770d457e34dbf5b52e8fa974673802ae1c86
# Verified Classes:   UnwitnessedMemoryWrite, WitnessResolutionError, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnwitnessedMemoryWrite(RuntimeError):
    """Raised when a memory write's provenance cannot be bound to a durable artifact."""
    pass


class WitnessResolutionError(RuntimeError):
    """Raised when a read's witness cannot be resolved against the durable log."""
    pass


@dataclass(frozen=True)
class MemoryRecord:
    key: str
    value: str
    witness_kind: str          # "tool_call" | "user_turn" | "chunk_hash"
    witness_id: str            # must resolve in the durable log
    witness_digest: str        # hash of the artifact at write time


def write_memory(
    key: str,
    value: str,
    witness_kind: str,
    witness_id: str,
    durable_log: dict,         # witness_id -> artifact bytes; survives compaction
    compaction_horizon: int,   # turn index beyond which witnesses are evicted
    current_turn: int,
) -> MemoryRecord:
    if witness_kind not in ("tool_call", "user_turn", "chunk_hash"):
        raise UnwitnessedMemoryWrite(
            f"asserted provenance rejected: kind={witness_kind!r} is not a bound artifact type"
        )
    if witness_id not in durable_log:
        raise UnwitnessedMemoryWrite(
            f"witness {witness_id!r} does not resolve in durable log; "
            f"write would be unauthenticated at read time"
        )
    if current_turn > compaction_horizon and witness_kind == "user_turn":
        raise UnwitnessedMemoryWrite(
            f"user_turn witness {witness_id!r} will be evicted at horizon "
            f"{compaction_horizon}; embed a durable pointer or re-derive at read"
        )
    artifact = durable_log[witness_id]
    if isinstance(artifact, str):
        artifact = artifact.encode()
    digest = hashlib.sha256(artifact).hexdigest()
    return MemoryRecord(key, value, witness_kind, witness_id, digest)


def read_memory(
    record: MemoryRecord,
    durable_log: dict,
    require_witness: bool = True,
) -> str:
    if not require_witness:
        return record.value
    if record.witness_id not in durable_log:
        raise WitnessResolutionError(
            f"record {record.key!r} witness {record.witness_id!r} no longer resolvable; "
            f"quarantine record, do not act on value"
        )
    artifact = durable_log[record.witness_id]
    if isinstance(artifact, str):
        artifact = artifact.encode()
    if hashlib.sha256(artifact).hexdigest() != record.witness_digest:
        raise WitnessResolutionError(
            f"record {record.key!r} witness digest mismatch; artifact mutated since write"
        )
    return record.value
