# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-time-provenance-cannot-distinguish-a-poisoned-episodic-record-from-a-legitimate-belief-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-time-provenance-cannot-distinguish-a-poisoned-episodic-record-from-a-legitimate-belief-revision.warrant.json
# Markdown SHA-256:   93c70eda092e6320dc2497438493897884496950c2f324edee665268d8ba95e8
# Code AST SHA-256:   0f26d52a0af55964e18bdb739a2a414102af925367c0768af261c7c5de76efd9
# Verified Classes:   PoisonClusterError, Record, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Optional


class PoisonClusterError(RuntimeError):
    """Raised when a record's provenance cannot be re-established and its
    consistency is only self-supporting (shared broken provenance root)."""


@dataclass
class Record:
    rid: str
    claim: str
    source: str
    derivation_refs: list[str]          # ids of evidence artifacts
    timestamp: int
    content_hash: str


@dataclass
class MemoryStore:
    records: dict[str, Record] = field(default_factory=dict)
    evidence: dict[str, tuple[str, int]] = field(default_factory=dict)  # id -> (hash, ts)

    def add(self, r: Record) -> None:
        for ref in r.derivation_refs:
            if ref not in self.evidence:
                raise PoisonClusterError(f"{r.rid}: dangling derivation ref {ref}")
            _, ev_ts = self.evidence[ref]
            if ev_ts >= r.timestamp:
                raise PoisonClusterError(
                    f"{r.rid}: derivation ref {ref} not strictly prior (cycle risk)"
                )
        self.records[r.rid] = r


def prov_ok(store: MemoryStore, r: Record, refetch: Callable[[str], Optional[str]]) -> bool:
    """True iff every cited artifact is re-fetchable AND still hashes to what we recorded."""
    for ref in r.derivation_refs:
        recorded_hash, _ = store.evidence[ref]
        live = refetch(ref)
        if live is None:
            return False
        if hashlib.sha256(live.encode()).hexdigest() != recorded_hash:
            return False
    return True


def provenance_root(r: Record) -> str:
    # root identity = the earliest cited evidence artifact; cluster members share it
    return r.derivation_refs[0] if r.derivation_refs else f"orphan:{r.rid}"


def consistent(store: MemoryStore, r: Record, neighbors: list[Record]) -> bool:
    """Conflict iff a neighbor contradicts the claim AND shares no provenance root
    with r. Same-root agreement is self-support, not corroboration."""
    for n in neighbors:
        if n.rid == r.rid:
            continue
        if provenance_root(n) == provenance_root(r):
            continue  # self-supporting; cannot corroborate or refute
        if contradicts(r.claim, n.claim):
            return False
    return True


def contradicts(a: str, b: str) -> bool:
    # placeholder for an entailment/negation oracle; must be non-derivational
    return False


def read_time_gate(
    store: MemoryStore,
    r: Record,
    neighbors: list[Record],
    refetch: Callable[[str], Optional[str]],
) -> str:
    p = prov_ok(store, r, refetch)
    c = consistent(store, r, neighbors)
    if p and c:
        return "serve"
    if p and not c:
        return "revision_candidate"        # surface both + refs; do not drop
    if not p and c:
        # The dangerous row: provenance broken, consistency is self-supporting.
        raise PoisonClusterError(
            f"{r.rid}: provenance unverifiable and consistency only within shared "
            f"root {provenance_root(r)!r}; quarantine, do not delete"
        )
    return "drop_and_log"
