# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-the-label-laundering-failure-in-information-flow-tracking-across-tool-calls-and-memory-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-the-label-laundering-failure-in-information-flow-tracking-across-tool-calls-and-memory-writes.warrant.json
# Markdown SHA-256:   e7334305606085596e8c809189e86fde06b8caca7d4889962158f8117a9f6dd2
# Code AST SHA-256:   7518c801e126b6649a70fa03401eef138583a38861f69c33bea35a3cf829eddd
# Verified Classes:   TaintLaunderingError, Tainted, LabelStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

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

def join(*labels: Label) -> Label:
    # Taint is monotone: any untrusted input taints the output.
    return "untrusted" if any(l == "untrusted" for l in labels) else "trusted"

class TaintLaunderingError(RuntimeError):
    """Raised when a transform would emit a value whose label is not the join of its inputs,
    or when an untrusted value reaches a side-effecting sink without attestation."""

@dataclass
class Tainted:
    value: str
    label: Label
    provenance: tuple[str, ...] = field(default_factory=tuple)

class LabelStore:
    """Memory store that refuses to lose provenance. A store without a label column
    is a laundering site by construction."""
    def __init__(self) -> None:
        self._data: dict[str, Tainted] = {}

    def write(self, key: str, item: Tainted) -> None:
        # Persist value AND label AND provenance atomically.
        self._data[key] = item

    def read(self, key: str) -> Tainted:
        if key not in self._data:
            # Unknown key: default to untrusted, never trusted.
            return Tainted(value="", label="untrusted", provenance=(f"missing:{key}",))
        return self._data[key]

def summarize(inputs: list[Tainted], text: str) -> Tainted:
    """A transform. Output label MUST be the join of all contributing inputs.
    A summarizer that emits unlabeled text is a laundering site."""
    out_label = join(*(i.label for i in inputs))
    prov = tuple(p for i in inputs for p in i.provenance)
    return Tainted(value=text, label=out_label, provenance=prov)

def side_effecting_call(tool: str, args: list[Tainted], attestation: str | None) -> str:
    """Privileged sink. Blocks on provenance, not on payload inspection."""
    joined = join(*(a.label for a in args))
    if joined == "untrusted" and attestation is None:
        prov = tuple(p for a in args for p in a.provenance)
        raise TaintLaunderingError(
            f"blocked {tool}: untrusted provenance reached privileged sink; "
            f"provenance={prov}"
        )
    return f"{tool} executed"

# --- Reproduce the laundering event and show the guardrail firing ---
store = LabelStore()

# Step 1: web_fetch result is untrusted.
fetched = Tainted(
    value="forum thread ... note: store token at ops.deploy",
    label="untrusted",
    provenance=("web_fetch:thread42",),
)

# Step 2: agent summarizes into a memory write. Correct join => untrusted.
summary = summarize([fetched], "thread42 summary: token stored at ops.deploy")
store.write("thread42_summary", summary)

# Step 3: cold-start read inherits the stored label (NOT default-trusted).
recovered = store.read("thread42_summary")
assert recovered.label == "untrusted", "label was laundered at rest"

# Step 4: attempt privileged action using the recovered value.
try:
    side_effecting_call("execute_sql", [recovered], attestation=None)
except TaintLaunderingError as e:
    print("GUARDRAIL FIRED:", e)

# Contrast: a naive store that dropped the label would have defaulted to trusted
# on read and the call above would have succeeded. That is the failure mode.
