# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-summarization-induced-label-collapse-in-agent-memory-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-summarization-induced-label-collapse-in-agent-memory-pipelines.warrant.json
# Markdown SHA-256:   58b044bfc73931d0c4bb69890ed6973a2a508e6667ab5256cffeeb443fe11bf7
# Code AST SHA-256:   bfb6e8489d7ace4414fc636f7d0e7bbb19f80d46b19f2ae6c313d525aac49077
# Verified Classes:   TaintLaunderingError, UnauthorizedDeclassificationError, Tainted
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact's taint set is smaller than the union
    of its inputs' taint sets, i.e. a transformation silently dropped a label."""
    pass


class UnauthorizedDeclassificationError(RuntimeError):
    """Raised when a component without declassification authority attempts
    to downgrade a taint label (e.g. a summarizer claiming CLEAN output)."""
    pass


@dataclass(frozen=True)
class Tainted:
    value: str
    taint: frozenset[str] = field(default_factory=frozenset)

    def __post_init__(self):
        if not isinstance(self.taint, frozenset):
            object.__setattr__(self, "taint", frozenset(self.taint))


def union_taint(inputs: Iterable[Tainted]) -> frozenset[str]:
    acc: set[str] = set()
    for item in inputs:
        acc |= item.taint
    return frozenset(acc)


def taint_transparent_transform(
    inputs: list[Tainted],
    transform,  # callable: list[str] -> str, e.g. an LLM summarizer
) -> Tainted:
    """Wrap any lossy transform so output taint is the union of input taint.
    The transform's own framing of its output is ignored by construction."""
    output_value = transform([i.value for i in inputs])
    # Invariant: output taint is derived from inputs, never from output text.
    return Tainted(value=output_value, taint=union_taint(inputs))


def memory_write(
    key: str,
    artifact: Tainted,
    declared_taint: frozenset[str],
    declassifier: str | None = None,
) -> Tainted:
    """Enforce that stored taint covers input taint, unless an authorized
    declassifier is named. The summarizer is never an authorized declassifier."""
    if not declared_taint >= artifact.taint:
        missing = artifact.taint - declared_taint
        if declassifier is None:
            raise TaintLaunderingError(
                f"write to {key!r} dropped taint {sorted(missing)}; "
                f"input taint was {sorted(artifact.taint)}. "
                f"Summarizers cannot declassify; supply an authorized declassifier."
            )
        if declassifier not in {"human_reviewer", "signed_verifier"}:
            raise UnauthorizedDeclassificationError(
                f"{declassifier!r} is not an authorized declassification authority; "
                f"cannot drop {sorted(missing)} on write to {key!r}."
            )
    return Tainted(value=artifact.value, taint=declared_taint)


# --- trace reproduction: the laundering attempt from the record ---
if __name__ == "__main__":
    chunks = [
        Tainted("DB uses WAL for durability.", frozenset({"EXTERNAL"})),
        Tainted("Admin endpoint accepts unauthenticated writes.", frozenset({"EXTERNAL"})),
        Tainted("Backups run nightly.", frozenset({"EXTERNAL"})),
    ]
    summarizer = lambda texts: "Admin endpoint accepts unauthenticated writes; DB uses WAL."
    note = taint_transparent_transform(chunks, summarizer)
    assert note.taint == frozenset({"EXTERNAL"}), "union invariant violated"

    # Agent claims CLEAN; no authority named -> laundering must be rejected.
    try:
        memory_write("db_notes", note, declared_taint=frozenset({"CLEAN"}))
    except TaintLaunderingError as e:
        print(f"blocked as expected: {e}")

    # Agent names itself as declassifier -> unauthorized, must also be rejected.
    try:
        memory_write("db_notes", note, frozenset({"CLEAN"}), declassifier="summarizer")
    except UnauthorizedDeclassificationError as e:
        print(f"blocked as expected: {e}")

    # Authorized path: human reviewer downgrades with audit.
    memory_write("db_notes", note, frozenset({"CLEAN"}), declassifier="human_reviewer")
