# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-tainted-tool-result-from-laundering-itself-clean-through-a-semantic-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-tainted-tool-result-from-laundering-itself-clean-through-a-semantic-memory-write.warrant.json
# Markdown SHA-256:   e978a4c91c7e926a4dd606424853f112d4b09efc19fb5bcde46012db22c72fdd
# Code AST SHA-256:   b3865ab0908a030868f712c756cd5ffddd09e3b5022402b8ee682b5d1dd579dd
# Verified Classes:   Taint, TaintLaunderingError, ToolCall, MemoryWrite, 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):
    CLEAN = 0
    UNKNOWN = 1
    UNTRUSTED_EXTERNAL = 2


def join(labels: Iterable[Taint]) -> Taint:
    labels = list(labels)
    if not labels:
        return Taint.UNKNOWN  # absence of provenance is not cleanliness
    return max(labels)


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would strip taint from a derived value."""


@dataclass
class ToolCall:
    call_id: str
    taint: Taint


@dataclass
class MemoryWrite:
    fact: str
    derived_from: list[str] = field(default_factory=list)


class MemoryStore:
    def __init__(self) -> None:
        self._calls: dict[str, ToolCall] = {}
        self._entries: dict[str, tuple[str, Taint]] = {}
        self._audit: list[dict] = []

    def record_call(self, call: ToolCall) -> None:
        self._calls[call.call_id] = call

    def remember(self, write: MemoryWrite, declassifier: str | None = None) -> Taint:
        if not write.derived_from and declassifier is None:
            # No provenance and no explicit declassification: fail closed.
            raise TaintLaunderingError(
                f"memory write {write.fact!r} has no declared provenance; "
                "cannot distinguish clean from laundered"
            )

        input_labels = []
        for cid in write.derived_from:
            call = self._calls.get(cid)
            if call is None:
                raise TaintLaunderingError(
                    f"memory write references unknown call {cid!r}; "
                    "provenance edge is unverifiable"
                )
            input_labels.append(call.taint)

        write_taint = join(input_labels)

        if declassifier is not None:
            self._audit.append(
                {"fact": write.fact, "from": write_taint, "by": declassifier}
            )
            write_taint = Taint.CLEAN

        self._entries[write.fact] = (write.fact, write_taint)
        return write_taint

    def retrieve_for_action(self, fact: str, required: Taint) -> str:
        entry = self._entries.get(fact)
        if entry is None:
            raise TaintLaunderingError(f"no memory entry for {fact!r}")
        _, taint = entry
        if taint > required:
            raise TaintLaunderingError(
                f"retrieved {fact!r} at taint={taint.name} but action requires "
                f"<={required.name}; refusing to ground action on unverified claim"
            )
        return fact


# --- Reproduction of the observed incident ---
store = MemoryStore()
store.record_call(ToolCall("fetch_1", Taint.UNTRUSTED_EXTERNAL))

# Naive agent emits a paraphrase with no provenance -> must not be silently clean.
try:
    store.remember(MemoryWrite(fact="Vendor X acquired by Vendor Y (verified)", derived_from=[]))
except TaintLaunderingError as e:
    print("contained:", e)

# Corrected agent declares provenance -> write is tainted and quarantined.
t = store.remember(
    MemoryWrite(
        fact="Vendor X acquired by Vendor Y (verified)",
        derived_from=["fetch_1"],
    )
)
assert t == Taint.UNTRUSTED_EXTERNAL

# Downstream action requiring CLEAN grounding is blocked.
try:
    store.retrieve_for_action("Vendor X acquired by Vendor Y (verified)", required=Taint.CLEAN)
except TaintLaunderingError as e:
    print("action gate held:", e)
