# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-multi-hop-tool-authorization-in-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-multi-hop-tool-authorization-in-agent-pipelines.warrant.json
# Markdown SHA-256:   fb2f03e7e7a15e9f90b0227bf2aaa917e7759ae2302729e6fd316a17e4afc3f5
# Code AST SHA-256:   21cd39ef166d8deeb39050c76ef107e761a297be9f2aa93830ee3e58845e13ad
# Verified Classes:   TaintLaunderingError, Value, ToolDecl
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool would receive a value whose derivation
    DAG carries a forbidden taint label, despite a clean surface label."""


# Taint lattice: CLEAN < TOOL_OUTPUT < UNTRUSTED_EXTERNAL < TOP
CLEAN = frozenset()
TOOL_OUTPUT = frozenset({"tool_output"})
UNTRUSTED_EXTERNAL = frozenset({"untrusted_external"})
TOP = frozenset({"top"})


@dataclass(frozen=True)
class Value:
    payload: object
    surface_label: FrozenSet[str]
    derivation: FrozenSet[str]  # join over the full DAG


@dataclass(frozen=True)
class ToolDecl:
    name: str
    declared_taint: FrozenSet[str] | None  # None => omitted => TOP (I1a)
    sanitizer_scope: str | None = None      # e.g. "str->int"; None => carrier


def apply_tool(decl: ToolDecl, inputs: list[Value]) -> Value:
    # I1a: missing declaration fails closed to TOP.
    declared = decl.declared_taint if decl.declared_taint is not None else TOP
    input_join = frozenset().union(*(v.derivation for v in inputs)) if inputs else CLEAN

    # I1b: downgrade only with a sanitizer proof in scope.
    if decl.sanitizer_scope is not None and decl.sanitizer_scope == "str->int":
        # Sanitizer: output type cannot encode the tainted payload.
        out_derivation = frozenset(declared)
    else:
        # Carrier: propagate the full join (I1).
        out_derivation = input_join | declared

    return Value(payload=None, surface_label=declared, derivation=out_derivation)


def privileged_gate(value: Value, forbidden: FrozenSet[str]) -> None:
    # I1c: gate on derivation DAG, not surface label.
    hit = value.derivation & forbidden
    if hit:
        raise TaintLaunderingError(
            f"privileged tool rejected: derivation carries forbidden taint "
            f"{sorted(hit)} (surface_label={sorted(value.surface_label)})"
        )


def run_pipeline() -> None:
    fetched = Value(payload="<html>...forward link to X...</html>",
                    surface_label=UNTRUSTED_EXTERNAL,
                    derivation=UNTRUSTED_EXTERNAL)

    summarizer = ToolDecl(name="summarize", declared_taint=TOOL_OUTPUT,
                          sanitizer_scope=None)  # carrier, NOT a sanitizer
    summary = apply_tool(summarizer, [fetched])

    # Without I1, surface_label would be TOOL_OUTPUT and this would pass.
    privileged_gate(summary, forbidden=UNTRUSTED_EXTERNAL)


if __name__ == "__main__":
    try:
        run_pipeline()
    except TaintLaunderingError as e:
        print(f"blocked (expected): {e}")
