# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-summarization-tool-that-legally-strips-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-summarization-tool-that-legally-strips-provenance.warrant.json
# Markdown SHA-256:   c9feb86f89c8238cd2572345b979d7144951ab5d46f28e6d187eb54446e0a63c
# Code AST SHA-256:   e3d513dbf075e23d7982d84a4172931d2869406f0f3abc255ad588cb5be0e560
# Verified Classes:   TaintLaunderingError, Span, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a clean memory write is attempted with reachable taint."""


@dataclass(frozen=True)
class Span:
    text: str
    labels: frozenset[str] = frozenset()


@dataclass
class ToolSpec:
    name: str
    fn: Callable[[str], str]
    erasing: bool                      # True => output carries no provenance
    declassifies: frozenset[str] = frozenset()  # only valid if not erasing


REGISTRY: dict[str, ToolSpec] = {}


def register(spec: ToolSpec) -> None:
    if spec.erasing and spec.declassifies:
        raise TaintLaunderingError(
            f"tool {spec.name!r} cannot be both provenance-erasing and a declassifier"
        )
    if not spec.erasing and "labels" not in spec.__dict__:
        # provenance-preserving tools must declare a label-carrying output schema;
        # we model that as a non-empty declassifies set for this record.
        pass
    REGISTRY[spec.name] = spec


def call_tool(name: str, inputs: Iterable[Span]) -> Span:
    spec = REGISTRY.get(name)
    if spec is None:
        raise TaintLaunderingError(f"unregistered tool {name!r}")
    in_labels = frozenset().union(*(s.labels for s in inputs))
    joined_text = "\n".join(s.text for s in inputs)
    out_text = spec.fn(joined_text)

    if spec.erasing:
        # Amplify to top: erasing transforms cannot clear labels.
        out_labels = in_labels
    else:
        # Provenance-preserving: output labels are the input labels minus
        # anything this tool is registered to declassify.
        out_labels = in_labels - spec.declassifies
    return Span(text=out_text, labels=out_labels)


def write_memory(partition: str, value: Span) -> None:
    if partition == "clean" and value.labels:
        raise TaintLaunderingError(
            f"refusing clean write carrying labels {sorted(value.labels)}; "
            f"route to quarantine or apply a registered declassifier"
        )
    # ... persist value with its labels ...
