# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-memory-write-is-re-indexed-across-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-memory-write-is-re-indexed-across-sessions.warrant.json
# Markdown SHA-256:   e818766738f099b4597cc02c5b7aa5903c3d468f455107140ecdcdbc35370716
# Code AST SHA-256:   48bdf78cfc9244fd17352004482f678473450a1180c7b1b37f85d66fe6084870
# Verified Classes:   TaintLaunderingError, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = "TRUSTED"
UNTRUSTED = "UNTRUSTED"


class TaintLaunderingError(RuntimeError):
    """Raised when a memory transform would drop or weaken taint provenance."""


@dataclass(frozen=True)
class MemoryRecord:
    content: str
    taint: FrozenSet[str] = field(default_factory=lambda: frozenset({UNTRUSTED}))


def join_taints(inputs: list[MemoryRecord]) -> FrozenSet[str]:
    if not inputs:
        raise TaintLaunderingError("cannot join taint over empty input set")
    joined: set[str] = set()
    for rec in inputs:
        if rec.taint is None:
            # Fail-closed: a record with no taint is treated as untrusted.
            raise TaintLaunderingError(
                f"record missing taint provenance: {rec.content[:40]!r}"
            )
        joined |= rec.taint
    return frozenset(joined)


def distill(episodic: list[MemoryRecord], summary_text: str) -> MemoryRecord:
    """Distillation must carry the mechanical taint join, never model-authored taint."""
    joined = join_taints(episodic)
    if UNTRUSTED in joined or any(t.startswith("UNTRUSTED:") for t in joined):
        # Do not silently promote; surface for quarantine review.
        return MemoryRecord(content=summary_text, taint=joined)
    return MemoryRecord(content=summary_text, taint=joined)


def promote_to_trusted_tier(record: MemoryRecord) -> MemoryRecord:
    """Write to the trusted semantic tier. Refuses any record carrying untrusted taint."""
    if record.taint is None:
        raise TaintLaunderingError("null taint on promotion attempt; fail-closed required")
    if any(t == UNTRUSTED or t.startswith("UNTRUSTED:") for t in record.taint):
        raise TaintLaunderingError(
            f"refusing to promote tainted record to trusted tier: taint={sorted(record.taint)}"
        )
    return record


def merge_dedup(a: MemoryRecord, b: MemoryRecord) -> MemoryRecord:
    """Dedup must join taints; never inherit the 'cleaner' side."""
    if a.taint is None or b.taint is None:
        raise TaintLaunderingError("merge encountered record with null taint")
    return MemoryRecord(content=a.content, taint=a.taint | b.taint)
