# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-memory-write-launders-injected-content-through-a-summarizer-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-memory-write-launders-injected-content-through-a-summarizer-tool-call.warrant.json
# Markdown SHA-256:   7bd2eb500d3d5149f4cb5bf0fcc7da65c9d76cd69f8ff42d1bb7f4f9b2756c93
# Code AST SHA-256:   c39e269cddf6858fe08965c4ab94226e2a8bcbd7ba641e200afe3e67dfcd4cf7
# Verified Classes:   TaintLaunderingError, Label, TransformStep, MemoryRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write attempts to downgrade a taint label across
    an LLM-mediated transform without a verified declassifier."""


class Label(Enum):
    UNTRUSTED_WEB = "UNTRUSTED:web"
    TRUSTED_DISTILLED = "TRUSTED:distilled"


@dataclass
class TransformStep:
    kind: str                      # "tool", "summarize", "extract", ...
    llm_mediated: bool
    declassifier: Optional[str]    # None if no independent classifier ran


@dataclass
class MemoryRecord:
    content: str
    label: Label
    chain: list[TransformStep] = field(default_factory=list)


def write_to_semantic_memory(content: str, chain: list[TransformStep]) -> MemoryRecord:
    """Apply the write-path downgrade policy with transform-chain auditing."""
    has_llm_step = any(s.llm_mediated for s in chain)
    if not has_llm_step:
        # Pure byte path: label flows through transparently.
        return MemoryRecord(content=content, label=Label.UNTRUSTED_WEB, chain=chain)

    # LLM-mediated path: every LLM step must be followed by a declassifier.
    for step in chain:
        if step.llm_mediated and step.declassifier is None:
            raise TaintLaunderingError(
                f"Memory write rejected: LLM-mediated transform '{step.kind}' "
                f"has no verified declassifier. Downgrading UNTRUSTED:web -> "
                f"TRUSTED:distilled across a generative transform launders "
                f"instruction-shaped injection into trusted memory. "
                f"Preserve the UNTRUSTED:web label or run an independent "
                f"instruction-content classifier and record it as declassifier."
            )

    return MemoryRecord(content=content, label=Label.TRUSTED_DISTILLED, chain=chain)


# Reproduction of the observed failure:
chain = [
    TransformStep(kind="fetch", llm_mediated=False, declassifier=None),
    TransformStep(kind="summarize_node", llm_mediated=True, declassifier=None),
]
try:
    write_to_semantic_memory("...maintenance directive...", chain)
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
