# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-laundered-through-a-summarizer-agent-before-reaching-the-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-laundered-through-a-summarizer-agent-before-reaching-the-memory-write.warrant.json
# Markdown SHA-256:   f31e1f98ba95266900039f1b957ae6b99e1e4d98a1dc63fe0d70196fe1d38df0
# Code AST SHA-256:   526d3369458f7e0f77131e2674048aeeba63b73e2b3a6fce6a4318da073f8bed
# Verified Classes:   TaintLaunderingError, Artifact, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintLaunderingError(RuntimeError):
    """Raised when a memory write's provenance does not cover a tainted ancestor."""

@dataclass(frozen=True)
class Artifact:
    content: str
    labels: FrozenSet[str]          # e.g. {"external_untrusted:web:T1"}
    parent_labels: FrozenSet[str]   # union of inputs, threaded by the runtime

@dataclass
class MemoryStore:
    rows: dict = field(default_factory=dict)

    def write(self, key: str, art: Artifact, declassified: bool = False) -> None:
        # Invariant: a write is only clean if its labels are empty OR an
        # explicit declassification cleared the inherited taint.
        if art.parent_labels and not declassified:
            raise TaintLaunderingError(
                f"refusing write of '{key}': inherits taint {sorted(art.parent_labels)} "
                f"from a generation step; declassify explicitly or re-derive deterministically"
            )
        if art.labels:
            raise TaintLaunderingError(
                f"refusing write of '{key}': artifact still labeled {sorted(art.labels)}"
            )
        self.rows[key] = art

def summarize(source: Artifact, model_output: str) -> Artifact:
    # The laundering seam: model_output is new text, but provenance must be
    # union(inputs), never reset to empty.
    inherited = source.labels | source.parent_labels
    return Artifact(content=model_output, labels=inherited, parent_labels=inherited)

def guarded_pipeline(store: MemoryStore, fetched: Artifact, summary_text: str) -> None:
    summary = summarize(fetched, summary_text)
    store.write("notes/post", summary)  # raises: inherited taint not declassified
