# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-when-a-poisoned-write-is-re-ingested-through-a-trusted-derived-consolidation-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-when-a-poisoned-write-is-re-ingested-through-a-trusted-derived-consolidation-path.warrant.json
# Markdown SHA-256:   c11c6f43a0660fe601a6d78c4e7511b78e61fc890604cd6ac367a96d88cc9d21
# Code AST SHA-256:   c4169553883ace58e4f36a89397940b6ae1528bbb00a1faabc5e464e7a7f7da6
# Verified Classes:   ProvenanceLaunderingError, Trust, MemoryRecord, ProvenanceStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a consolidated record's taint cannot be recomputed from its
    persisted derivation edges, i.e. the store has laundered provenance."""
    pass


class Trust(Enum):
    CLEAN = "clean"
    TAINTED = "tainted"
    UNVERIFIED = "unverified"  # cannot prove clean; must NOT be treated as clean


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    source: str
    confidence: float
    taint_flag: Optional[bool] = None          # write-time flag: UNRELIABLE
    derived_from: tuple[str, ...] = ()          # persisted derivation edges
    derivation_epoch: int = 0


class ProvenanceStore:
    def __init__(self, max_recomputable_depth: int = 8):
        self._records: dict[str, MemoryRecord] = {}
        self._max_depth = max_recomputable_depth

    def write_episodic(self, rec: MemoryRecord) -> None:
        self._records[rec.record_id] = rec

    def consolidate(self, out_id: str, inputs: list[str],
                    content: str, stated_confidence: float) -> None:
        # Guardrail (a): persist derivation edges; do NOT trust stated_confidence.
        for i in inputs:
            if i not in self._records:
                raise ProvenanceLaunderingError(
                    f"consolidation input {i} missing; cannot establish lineage")
        min_conf = min(self._records[i].confidence for i in inputs)
        self._records[out_id] = MemoryRecord(
            record_id=out_id,
            content=content,
            source="consolidation_agent",
            confidence=min(stated_confidence, min_conf),  # meet, not join
            taint_flag=None,                              # never set by writer
            derived_from=tuple(inputs),
            derivation_epoch=max(self._records[i].derivation_epoch
                                 for i in inputs) + 1,
        )

    def _taint_join(self, rec_id: str, depth: int = 0) -> Trust:
        # Guardrail (b): recompute the join over the FULL ancestor set.
        if depth > self._max_depth:
            return Trust.UNVERIFIED
        rec = self._records.get(rec_id)
        if rec is None:
            return Trust.UNVERIFIED          # pruned ancestor -> cannot prove
        if not rec.derived_from:
            # Leaf: trust is determined by its own source, not by a flag.
            return Trust.CLEAN if rec.source not in ("untrusted_web",) else Trust.TAINTED
        results = [self._taint_join(a, depth + 1) for a in rec.derived_from]
        if any(r is Trust.TAINTED for r in results):
            return Trust.TAINTED
        if any(r is Trust.UNVERIFIED for r in results):
            return Trust.UNVERIFIED
        return Trust.CLEAN

    def admit_for_recall(self, rec_id: str) -> bool:
        rec = self._records.get(rec_id)
        if rec is None:
            raise ProvenanceLaunderingError(f"{rec_id} absent at recall")
        trust = self._taint_join(rec_id)
        if trust is Trust.TAINTED:
            return False                      # content failure: reject, continue
        if trust is Trust.UNVERIFIED:
            # Guardrail (c): cannot prove clean -> re-derive, do not admit on faith.
            raise ProvenanceLaunderingError(
                f"{rec_id} lineage incomplete; re-derive from episodic records")
        # Confidence clause: reject inflated summaries even when clean.
        if rec.derived_from:
            min_anc = min(self._records[a].confidence for a in rec.derived_from)
            if rec.confidence > min_anc + 1e-9:
                raise ProvenanceLaunderingError(
                    f"{rec_id} confidence {rec.confidence} exceeds ancestor "
                    f"minimum {min_anc}: laundering amplifier")
        return True


def recall_or_refuse(store: ProvenanceStore, rec_id: str) -> str:
    try:
        if store.admit_for_recall(rec_id):
            return store._records[rec_id].content
    except ProvenanceLaunderingError as e:
        # Distinguish integrity failure from content rejection at the call site.
        raise ProvenanceLaunderingError(
            f"refusing recall of {rec_id}: {e}") from e
    raise ProvenanceLaunderingError(f"{rec_id} rejected: tainted ancestor")
