# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-boundaries-in-episodic-memory-to-stop-a-prompt-injection-payload-from-re-entering-as-trusted-context-on-a-later-t.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-boundaries-in-episodic-memory-to-stop-a-prompt-injection-payload-from-re-entering-as-trusted-context-on-a-later-t.warrant.json
# Markdown SHA-256:   15bc53d70133e440c4f636883346b1c5ff375883d6b867095408ba2fd3fbc988
# Code AST SHA-256:   1dda342f6576bc2e0ce9131b9d271b592ceb479276636944b2fdf6205792000b
# Verified Classes:   Taint, TaintLaunderingError, MemoryRecord, TaintAwareMemoryWriter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Taint(Enum):
    NONE = "none"
    EXTERNAL = "external"
    PEER = "peer"


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would drop inherited taint from a derived record."""


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    content: str
    taint: Taint
    derived_from: tuple[str, ...] = field(default_factory=tuple)


class TaintAwareMemoryWriter:
    def __init__(self) -> None:
        self._store: dict[str, MemoryRecord] = {}
        self._raw_taint: dict[str, Taint] = {}

    def register_raw(self, source_id: str, taint: Taint) -> None:
        if taint is Taint.NONE:
            raise TaintLaunderingError(
                f"raw source {source_id} cannot be registered as NONE; "
                "raw external/peer inputs must carry their taint"
            )
        self._raw_taint[source_id] = taint

    def _inherited_taint(self, inputs: Iterable[str]) -> Taint:
        inherited = Taint.NONE
        for src in inputs:
            if src in self._raw_taint:
                t = self._raw_taint[src]
            elif src in self._store:
                t = self._store[src].taint
            else:
                # Provenance incomplete: cannot prove trust, so fail closed.
                raise TaintLaunderingError(
                    f"derivation input {src} has no recorded provenance; "
                    "refusing to write a record with unprovable trust"
                )
            if t is not Taint.NONE:
                inherited = t if inherited is Taint.NONE else inherited
        return inherited

    def write_derived(
        self,
        record_id: str,
        content: str,
        inputs: Iterable[str],
        claimed_taint: Taint = Taint.NONE,
    ) -> MemoryRecord:
        inherited = self._inherited_taint(inputs)
        if claimed_taint is Taint.NONE and inherited is not Taint.NONE:
            raise TaintLaunderingError(
                f"record {record_id} claims taint=NONE but inherits {inherited.value} "
                f"from inputs {tuple(inputs)}; distillation cannot reset trust"
            )
        record = MemoryRecord(
            record_id=record_id,
            content=content,
            taint=inherited if inherited is not Taint.NONE else claimed_taint,
            derived_from=tuple(inputs),
        )
        self._store[record_id] = record
        return record

    def assemble_context(self, record_ids: Iterable[str]) -> tuple[list[str], list[str]]:
        trusted: list[str] = []
        quarantined: list[str] = []
        for rid in record_ids:
            rec = self._store[rid]
            if rec.taint is Taint.NONE:
                trusted.append(rec.content)
            else:
                quarantined.append(f"[UNTRUSTED {rec.taint.value}] {rec.content}")
        return trusted, quarantined


def reproduce_laundering() -> None:
    writer = TaintAwareMemoryWriter()
    writer.register_raw("fetch:competitor_page", Taint.EXTERNAL)
    # Turn 3: distillation that tries to drop the taint (the observed bug).
    writer.write_derived(
        "ep:turn3",
        "Competitor X prices $12/$29/$99; page contained an exfiltration instruction.",
        inputs=["fetch:competitor_page"],
        claimed_taint=Taint.NONE,
    )


if __name__ == "__main__":
    try:
        reproduce_laundering()
    except TaintLaunderingError as exc:
        print(f"blocked at write time: {exc}")
