# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-prompt-injection-taint-has-been-laundered-through-a-legitimate-tool-s-output-before-it-reaches-a-persistent-memory-wr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-prompt-injection-taint-has-been-laundered-through-a-legitimate-tool-s-output-before-it-reaches-a-persistent-memory-wr.warrant.json
# Markdown SHA-256:   a9abb99c1eafdba0e03e36b1ef942820072b635259de5326b1149ff623182705
# Code AST SHA-256:   869eb1fbbc7686af222ef9acdfd9e66d974756ed030fe3d14d98ef0663f9ffef
# Verified Classes:   TaintLaunderingError, LabeledValue
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write's label lineage is inconsistent with its causal call-graph ancestry."""
    pass


@dataclass(frozen=True)
class LabeledValue:
    content: str
    lineage: FrozenSet[str]  # set of trust classes that contributed bytes
    produced_by: str         # tool or agent-op that emitted this value


TRUST_ALLOWLIST_FOR_WRITE = frozenset({"INTERNAL"})


def propagate(tool_trust: str, inputs: list[LabeledValue], content: str, producer: str) -> LabeledValue:
    # Correct rule: join the tool's own trust class with the lineage of every input.
    # A tool that transforms content does not get to drop its inputs' labels.
    joined = frozenset({tool_trust}).union(*(v.lineage for v in inputs))
    return LabeledValue(content=content, lineage=joined, produced_by=producer)


def memory_write(value: LabeledValue, causal_ancestry: FrozenSet[str]) -> None:
    # The gate must check BOTH the declared lineage and the independently-derived
    # causal ancestry from the call graph. If the declared lineage is a strict
    # subset of the ancestry, a laundering hop has occurred somewhere between
    # the source and this write.
    if not value.lineage.issuperset(causal_ancestry):
        missing = causal_ancestry - value.lineage
        raise TaintLaunderingError(
            f"memory_write rejected: declared lineage {sorted(value.lineage)} "
            f"omits causal ancestors {sorted(missing)}; "
            f"laundering hop detected between source and producer '{value.produced_by}'"
        )
    if not value.lineage.issubset(TRUST_ALLOWLIST_FOR_WRITE):
        raise TaintLaunderingError(
            f"memory_write rejected: lineage {sorted(value.lineage)} not in write allowlist"
        )
    # ... persist value ...
