# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-memory-write-audit-trail-before-trusting-a-retrieval.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-memory-write-audit-trail-before-trusting-a-retrieval.warrant.json
# Markdown SHA-256:   08aa8cadebfaea1e0f8e666284f1fdcf18d2520b6515e2fb8e91e6216784a826
# Code AST SHA-256:   682e0f5702eb95b3ec990bd44e2ac48b3b7a2400d15c7dd4cd8ce80c40dbf284
# Verified Classes:   ProvenanceAuthorityError, ProvenanceClass, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from enum import IntEnum


class ProvenanceAuthorityError(RuntimeError):
    """Raised when a memory's provenance claim exceeds its writer channel's authority."""


class ProvenanceClass(IntEnum):
    TOOL_DERIVED = 1
    PEER_AGENT = 2
    OPERATOR_DIRECTIVE = 3


CHANNEL_CEILING = {
    "ingest": ProvenanceClass.TOOL_DERIVED,
    "peer_handoff": ProvenanceClass.PEER_AGENT,
    "operator": ProvenanceClass.OPERATOR_DIRECTIVE,
}


@dataclass(frozen=True)
class MemoryRecord:
    content: str
    provenance_class: ProvenanceClass
    writer_channel: str
    writer_id: str
    write_epoch: int


def tuple_hash(rec: MemoryRecord) -> str:
    canonical = json.dumps(
        {
            "content": rec.content,
            "provenance_class": int(rec.provenance_class),
            "writer_channel": rec.writer_channel,
            "writer_id": rec.writer_id,
            "write_epoch": rec.write_epoch,
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode()).hexdigest()


def assert_provenance_authorized(rec: MemoryRecord, stored_hash: str) -> None:
    if tuple_hash(rec) != stored_hash:
        raise ProvenanceAuthorityError(
            f"tuple hash mismatch for {rec.writer_id}: provenance may have been mutated post-write"
        )
    ceiling = CHANNEL_CEILING.get(rec.writer_channel)
    if ceiling is None:
        raise ProvenanceAuthorityError(
            f"unknown writer channel {rec.writer_channel!r}; cannot establish authority ceiling"
        )
    if rec.provenance_class > ceiling:
        raise ProvenanceAuthorityError(
            f"provenance {rec.provenance_class.name} exceeds ceiling "
            f"{ceiling.name} for channel {rec.writer_channel!r} "
            f"(writer={rec.writer_id}); memory is suspect and must be downgraded"
        )


def retrieve_for_action(rec: MemoryRecord, stored_hash: str) -> MemoryRecord:
    assert_provenance_authorized(rec, stored_hash)
    return rec
