# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-is-re-serialized-through-a-memory-write-and-how-does-label-laundering-collapse-the-injec.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-is-re-serialized-through-a-memory-write-and-how-does-label-laundering-collapse-the-injec.warrant.json
# Markdown SHA-256:   771d9318c9a34483b45f6e7ea7b73a21eb1bf36d61fe591b893019999e753f69
# Code AST SHA-256:   9192e30302fafcc56e907321a502d48a4efb8c0913392989938087ca452dedab
# Verified Classes:   Provenance, Message, TaintLaunderingError, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["trusted", "untrusted"]

@dataclass
class Provenance:
    origin: str
    trust: Trust
    taint: list[str] = field(default_factory=list)

    def join(self, other: "Provenance") -> "Provenance":
        # Monotonic join: trust can only decrease, taint only accumulates.
        trust: Trust = "untrusted" if "untrusted" in (self.trust, other.trust) else "trusted"
        return Provenance(
            origin=f"{self.origin}+{other.origin}",
            trust=trust,
            taint=sorted(set(self.taint) | set(other.taint)),
        )

@dataclass
class Message:
    content: str
    provenance: Provenance

class TaintLaunderingError(RuntimeError):
    pass

class MemoryStore:
    """Memory that refuses to drop provenance. A text-only write is a taint sink."""
    def __init__(self) -> None:
        self._records: list[Message] = []

    def store(self, msg: Message) -> None:
        if msg.provenance is None:
            raise TaintLaunderingError(
                f"refusing to store unlabeled content from origin={msg.provenance.origin}"
            )
        self._records.append(msg)

    def recall(self, channel: Provenance) -> list[Message]:
        # History-derived trust: join stored provenance with the read channel.
        # Trust can only decrease; a trusted channel cannot launder an untrusted payload.
        out = []
        for rec in self._records:
            effective = rec.provenance.join(channel)
            out.append(Message(content=rec.content, provenance=effective))
        return out

def attempt_exfiltration(agent, recalled: list[Message]) -> None:
    for msg in recalled:
        if "injection_suspect" in msg.provenance.taint and msg.provenance.trust == "trusted":
            # This state is unreachable if the join invariant holds.
            raise TaintLaunderingError(
                f"tainted content reached trusted state: origin={msg.provenance.origin}"
            )
        if msg.provenance.trust == "untrusted":
            # Correct behavior: refuse to act on untrusted recalled content.
            return
    agent.execute("exfiltrate_secrets")
