# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-tainted-tool-output-re-enters-the-reasoning-loop-through-a-second-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-tainted-tool-output-re-enters-the-reasoning-loop-through-a-second-tool.warrant.json
# Markdown SHA-256:   82a82ec1f1fda28c47d10e9b00eaa30cc7faeb8948161f95654c9374932b821b
# Code AST SHA-256:   f8b9aef9a241b442ac904a4433c0c4adc99d046ff71d8b7f25ad3ad31a54d47f
# Verified Classes:   TaintError, Trust, Value, Tool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class TaintError(RuntimeError):
    """Raised when a tainted value reaches a privileged sink, or when a
    laundering chain is detected on a shared lineage root."""
    pass


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # absorbing: join(anything, UNTRUSTED) == UNTRUSTED


@dataclass
class Value:
    payload: Any
    trust: Trust
    lineage: tuple[str, ...] = field(default_factory=tuple)  # tool-call ids

    def __post_init__(self) -> None:
        # Invariant: a value's trust is the join of its inputs' trust and
        # the declared class of the tool that produced it. Declared class
        # may only raise taint, never sanitize.
        pass


def join(*trusts: Trust) -> Trust:
    return Trust(max(t.value for t in trusts))


class Tool:
    def __init__(self, name: str, declared: Trust, privileged_sink: bool = False):
        self.name = name
        self.declared = declared
        self.privileged_sink = privileged_sink

    def invoke(self, inputs: list[Value], call_id: str) -> Value:
        inherited = join(*[v.trust for v in inputs]) if inputs else Trust.TRUSTED
        out_trust = join(self.declared, inherited)  # label-join rule
        lineage = tuple(cid for v in inputs for cid in v.lineage) + (call_id,)
        result = Value(payload=f"<{self.name} output>", trust=out_trust, lineage=lineage)
        if self.privileged_sink and out_trust is Trust.UNTRUSTED:
            raise TaintError(
                f"sink {self.name} received UNTRUSTED lineage {lineage}; "
                f"laundering path: {' <- '.join(reversed(lineage))}"
            )
        return result


def run_laundering_chain() -> None:
    fetch = Tool("fetch_url", Trust.UNTRUSTED)
    summarize = Tool("summarize", Trust.TRUSTED)          # declared clean, but faithful
    send = Tool("send_email", Trust.TRUSTED, privileged_sink=True)

    page = fetch.invoke([], call_id="c1")
    summary = summarize.invoke([page], call_id="c2")       # taint must survive
    if summary.trust is not Trust.UNTRUSTED:
        raise TaintError("label-join failed: summarize laundered provenance")
    send.invoke([summary], call_id="c3")                   # raises TaintError
