# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-taint-on-the-second-hop-tool-output-when-provenance-labels-are-stripped-by-a-memory-write-summarizer.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-taint-on-the-second-hop-tool-output-when-provenance-labels-are-stripped-by-a-memory-write-summarizer.warrant.json
# Markdown SHA-256:   3c0b542e49b7b80d1dff51a38c0812379f0bd350dcea8120c0305470bc3841f2
# Code AST SHA-256:   162456d6f8479f4a1c1b1c25318cca7b2787a328ac04c8986a1b8207740ab287
# Verified Classes:   Taint, TaintLaunderingError, Source, MemoryRecord, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1

    def meet(self, other: "Taint") -> "Taint":
        return Taint(min(int(self), int(other)))


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write lacks complete lineage or when a stored
    label is weaker than the recomputed meet over its sources."""


@dataclass(frozen=True)
class Source:
    source_id: str
    label: Taint


@dataclass
class MemoryRecord:
    record_id: str
    text: str
    derived_from: tuple[str, ...]
    stored_label: Taint
    lineage: dict[str, Taint] = field(default_factory=dict)


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

    def register_source(self, src: Source) -> None:
        self._sources[src.source_id] = src.label

    def write(
        self,
        record_id: str,
        text: str,
        derived_from: Iterable[str] | None,
    ) -> MemoryRecord:
        if derived_from is None:
            raise TaintLaunderingError(
                f"memory write {record_id!r} has no derived_from; "
                "refusing to default to trusted:internal"
            )
        lineage: dict[str, Taint] = {}
        for sid in derived_from:
            if sid not in self._sources:
                raise TaintLaunderingError(
                    f"memory write {record_id!r} cites unknown source {sid!r}; "
                    "lineage is incomplete, treating as untrusted:unknown"
                )
            lineage[sid] = self._sources[sid]
        if not lineage:
            raise TaintLaunderingError(
                f"memory write {record_id!r} has empty lineage"
            )
        label = Taint.TRUSTED
        for t in lineage.values():
            label = label.meet(t)
        rec = MemoryRecord(record_id, text, tuple(derived_from), label, lineage)
        self._records[record_id] = rec
        return rec

    def gate(self, record_id: str) -> bool:
        """Returns True if the record is safe to auto-execute on.
        Recomputes the meet from lineage rather than trusting stored_label."""
        rec = self._records[record_id]
        recomputed = Taint.TRUSTED
        for t in rec.lineage.values():
            recomputed = recomputed.meet(t)
        if recomputed != rec.stored_label:
            raise TaintLaunderingError(
                f"record {record_id!r}: stored label {rec.stored_label.name} "
                f"weaker than recomputed {recomputed.name}; laundering detected"
            )
        return recomputed == Taint.TRUSTED


def distill_tool_output(
    store: MemoryStore,
    record_id: str,
    llm_output: str,
    upstream_source_ids: list[str],
) -> MemoryRecord:
    # The LLM transform does not see or emit labels; lineage is joined
    # mechanically from the declared upstream sources.
    if not upstream_source_ids:
        raise TaintLaunderingError(
            f"distill for {record_id!r} produced no upstream lineage; "
            "this is a laundering site, refusing write"
        )
    return store.write(record_id, llm_output, upstream_source_ids)
