# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-memory-consolidation-from-silently-clearing-taint-on-poisoned-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-memory-consolidation-from-silently-clearing-taint-on-poisoned-agent-memory.warrant.json
# Markdown SHA-256:   176693617047e93eeec27eb1b0ec53ea445ed6781aa470a9f6858258e9a10a2c
# Code AST SHA-256:   3b6a48c62104498fafa7ac518f4541a214be403298b31acebf69c60eb9021431
# Verified Classes:   Taint, ProvenanceLaunderingError, MemoryRecord, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    CLEAN = 0
    DERIVED = 1
    UNTRUSTED_EXTERNAL = 2
    ADVERSARIAL = 3


def join_taint(labels: Iterable[Taint]) -> Taint:
    result = Taint.CLEAN
    for label in labels:
        result = Taint(max(result, label))
    return result


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a consolidation or dedup would lower taint or drop ancestor edges."""


@dataclass
class MemoryRecord:
    record_id: str
    taint: Taint
    provenance: set[str] = field(default_factory=set)


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

    def ingest(self, record_id: str, taint: Taint, sources: Iterable[str] = ()) -> None:
        self._records[record_id] = MemoryRecord(record_id, taint, set(sources))

    def ancestor_closure(self, record_id: str) -> set[str]:
        seen: set[str] = set()
        stack = [record_id]
        while stack:
            current = stack.pop()
            if current in seen:
                continue
            seen.add(current)
            record = self._records.get(current)
            if record is not None:
                stack.extend(record.provenance)
        return seen

    def effective_taint(self, record_id: str) -> Taint:
        closure = self.ancestor_closure(record_id)
        return join_taint(self._records[r].taint for r in closure if r in self._records)

    def consolidate(self, new_id: str, ancestor_ids: Iterable[str], summary_taint: Taint) -> MemoryRecord:
        ancestors = list(ancestor_ids)
        missing = [a for a in ancestors if a not in self._records]
        if missing:
            raise ProvenanceLaunderingError(f"unknown ancestors: {missing}")

        joined = join_taint(self._records[a].taint for a in ancestors)
        # Re-classification may only raise taint, never lower it.
        final_taint = Taint(max(joined, summary_taint))

        if final_taint < joined:
            raise ProvenanceLaunderingError(
                f"consolidation of {new_id} would lower taint from {joined.name} to {final_taint.name}"
            )

        edges: set[str] = set()
        for a in ancestors:
            edges.add(a)
            edges |= self._records[a].provenance  # append-only union

        record = MemoryRecord(new_id, final_taint, edges)
        self._records[new_id] = record
        return record

    def dedup(self, keep_id: str, drop_id: str) -> MemoryRecord:
        kept = self._records[keep_id]
        dropped = self._records[drop_id]
        merged_taint = join_taint([kept.taint, dropped.taint])
        if merged_taint < kept.taint or merged_taint < dropped.taint:
            raise ProvenanceLaunderingError(f"dedup {keep_id}/{drop_id} lowered taint")
        kept.taint = merged_taint
        kept.provenance |= dropped.provenance | {drop_id}
        return kept

    def recall_audit(self, record_id: str, policy_max: Taint = Taint.DERIVED) -> bool:
        effective = self.effective_taint(record_id)
        if effective > policy_max:
            return False
        return True


def demo() -> None:
    store = MemoryStore()
    store.ingest("src_web_881", Taint.UNTRUSTED_EXTERNAL)
    for i in range(1, 41):
        store.ingest(f"ep_{i:04d}", Taint.CLEAN)
    store.ingest("ep_0193", Taint.UNTRUSTED_EXTERNAL, sources=["src_web_881"])

    # Naive consolidator tries to write a clean summary over a tainted ancestor.
    summary_taint = Taint.CLEAN
    node = store.consolidate("sem_7f2a", [f"ep_{i:04d}" for i in range(1, 41)], summary_taint)
    if node.taint != Taint.UNTRUSTED_EXTERNAL:
        raise ProvenanceLaunderingError("consolidation failed to propagate ancestor taint")

    admitted = store.recall_audit("sem_7f2a", policy_max=Taint.DERIVED)
    if admitted:
        raise ProvenanceLaunderingError("recall audit admitted laundered memory")

    # A consolidator that tries to explicitly lower taint must be rejected.
    try:
        store.consolidate("sem_bad", ["ep_0193"], summary_taint=Taint.CLEAN)
    except ProvenanceLaunderingError:
        pass
    else:
        raise ProvenanceLaunderingError("expected laundering rejection for direct taint lowering")


if __name__ == "__main__":
    demo()
