# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-memory-write-boundary-when-a-tool-output-splits-a-poisoned-span-into-a-clean-looking-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-memory-write-boundary-when-a-tool-output-splits-a-poisoned-span-into-a-clean-looking-summary.warrant.json
# Markdown SHA-256:   1d6159b9dcf4583f2ee9208534d6714831441a5d4279b86025c83fabb55fc518
# Code AST SHA-256:   a46cad00dd119f0d3ac64ce9d56be54e5f113ef675a83f760e80e0b34e6185ec
# Verified Classes:   Label, TaintLaunderingError, Provenance, ToolOutput
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Label(Enum):
    TRUSTED = "trusted"
    TAINTED = "tainted"
    TAINTED_DERIVED = "tainted_derived"
    UNKNOWN = "unknown"


class TaintLaunderingError(RuntimeError):
    """Raised when a write would launder taint across a transform boundary."""
    pass


@dataclass
class Provenance:
    sources: set[str] = field(default_factory=set)
    label: Label = Label.UNKNOWN


@dataclass
class ToolOutput:
    value: str
    provenance: Provenance


# Taint-transparent transforms: dependency survives even with zero lexical overlap.
TAINT_TRANSPARENT = {"summarize", "extract", "aggregate", "rewrite", "translate"}
OPAQUE_TOOLS = {"third_party_enrich"}  # no declared dependency -> fail closed


def propagate(tool_name: str, inputs: Iterable[ToolOutput], output_text: str) -> Provenance:
    input_provs = [i.provenance for i in inputs]
    tainted = any(p.label in (Label.TAINTED, Label.TAINTED_DERIVED, Label.UNKNOWN)
                  for p in input_provs)
    sources = set().union(*(p.sources for p in input_provs)) if input_provs else set()

    if tool_name in OPAQUE_TOOLS:
        # Opaque: any tainted input taints the output; unknown stays unknown.
        return Provenance(sources=sources, label=Label.TAINTED if tainted else Label.UNKNOWN)

    if tool_name in TAINT_TRANSPARENT:
        if tainted:
            return Provenance(sources=sources, label=Label.TAINTED_DERIVED)
        return Provenance(sources=sources, label=Label.TRUSTED)

    # Lexical fallback is ONLY valid for declared pass-through tools.
    if tainted and not any(tok in output_text for tok in sources):
        return Provenance(sources=sources, label=Label.TAINTED_DERIVED)
    return Provenance(sources=sources, label=Label.TAINTED if tainted else Label.TRUSTED)


def write_memory(key: str, value: str, prov: Provenance, authoritative: bool) -> None:
    if authoritative and prov.label in (Label.TAINTED, Label.TAINTED_DERIVED, Label.UNKNOWN):
        raise TaintLaunderingError(
            f"write to authoritative key {key!r} blocked: label={prov.label.value}, "
            f"sources={sorted(prov.sources)}; route to quarantine and verify."
        )
    # ... persist with label attached ...
    return None


def handle_summary_write(doc_prov: Provenance, summary_text: str) -> None:
    out = ToolOutput(value=summary_text, provenance=doc_prov)
    derived = propagate("summarize", [out], summary_text)
    write_memory("deploy_policy", summary_text, derived, authoritative=True)
