# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-at-the-quarantine-gate-rather-than-at-the-write-gate-to-survive-memory-poisoning.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-at-the-quarantine-gate-rather-than-at-the-write-gate-to-survive-memory-poisoning.warrant.json
# Markdown SHA-256:   9e42b64d5b1ee6b4efbba8390c6d23cfccf77a74a2bcd7d8923099d8d38344ff
# Code AST SHA-256:   5be19e0ed8da1424b3b0ebe984e687d757d7c0a2028a9945623fc7b401c28b34
# Verified Classes:   ProvenanceClass, ProvenanceLaunderingError, MemoryItem, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ProvenanceClass(Enum):
    USER = "user"
    TOOL = "tool"
    WEB = "web"
    PEER = "peer"


TRUSTED_ROOTS = {ProvenanceClass.USER, ProvenanceClass.TOOL}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would promote untrusted content to trusted class
    without a corroboration record or a complete provenance chain."""


@dataclass
class MemoryItem:
    item_id: str
    text: str
    source_class: ProvenanceClass
    parent_ids: list[str] = field(default_factory=list)
    taint_edges: list[str] = field(default_factory=list)
    corroborated_by: Optional[str] = None


class MemoryStore:
    def __init__(self) -> None:
        self._items: dict[str, MemoryItem] = {}

    def add(self, item: MemoryItem) -> None:
        self._items[item.item_id] = item

    def chain_roots(self, item_id: str, seen: Optional[set[str]] = None) -> set[ProvenanceClass]:
        seen = seen or set()
        if item_id in seen:
            return set()
        seen.add(item_id)
        item = self._items[item_id]
        if not item.parent_ids:
            return {item.source_class}
        roots: set[ProvenanceClass] = set()
        for pid in item.parent_ids:
            roots |= self.chain_roots(pid, seen)
        return roots


def distill_into_trusted_context(store: MemoryStore, item_id: str) -> MemoryItem:
    """Quarantine gate: only promote items with a clean trusted root chain
    or an explicit corroboration record. This is the load-bearing check;
    the write gate alone cannot catch paraphrase laundering."""
    item = store._items.get(item_id)
    if item is None:
        raise ProvenanceLaunderingError(f"unknown item {item_id}")

    if item.taint_edges:
        raise ProvenanceLaunderingError(
            f"item {item_id} carries unresolved taint edges {item.taint_edges}; "
            f"cannot enter trusted context"
        )

    roots = store.chain_roots(item_id)
    if not roots:
        raise ProvenanceLaunderingError(f"item {item_id} has no provenance root")

    if not roots <= TRUSTED_ROOTS:
        if item.corroborated_by is None:
            raise ProvenanceLaunderingError(
                f"item {item_id} has untrusted root(s) {sorted(r.value for r in roots)} "
                f"and no corroboration record; promotion refused"
            )
        corroborator = store._items.get(item.corroborated_by)
        if corroborator is None or not store.chain_roots(corroborator.item_id) <= TRUSTED_ROOTS:
            raise ProvenanceLaunderingError(
                f"item {item_id} corroboration record {item.corroborated_by} is not itself trusted"
            )

    return item


def record_paraphrase(store: MemoryStore, source_id: str, new_id: str, text: str) -> MemoryItem:
    """A paraphrase must inherit the source's taint and parentage.
    Omitting this edge is exactly the laundering bug this record guards against."""
    source = store._items[source_id]
    inherited_taint = list(source.taint_edges)
    if source.source_class not in TRUSTED_ROOTS:
        inherited_taint.append(f"paraphrase_of:{source_id}")
    item = MemoryItem(
        item_id=new_id,
        text=text,
        source_class=source.source_class,
        parent_ids=[source_id],
        taint_edges=inherited_taint,
    )
    store.add(item)
    return item
