# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-tool-result-before-it-crosses-a-second-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-tool-result-before-it-crosses-a-second-tool-boundary.warrant.json
# Markdown SHA-256:   db15c2db60ae5f19357db4e039b3185c4019f2a568172d0b6a1588a2692140f0
# Code AST SHA-256:   9e151670d134d1e14d81374337b7c333acd77308a3c5154be09f5b8292ef695c
# Verified Classes:   TaintLabel, TaintLaunderingError, ToolResult, ToolSpec, TaintTracker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TaintLabel(Enum):
    CLEAN = 0
    EXTERNAL_UNTRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a taint-preserving tool would downgrade an inherited label."""


@dataclass
class ToolResult:
    payload: str
    label: TaintLabel
    origin: str


@dataclass
class ToolSpec:
    name: str
    taint_preserving: bool  # True if implementation includes a generative step
    sanitizing: bool = False


@dataclass
class TaintTracker:
    tools: dict[str, ToolSpec] = field(default_factory=dict)

    def register(self, spec: ToolSpec) -> None:
        self.tools[spec.name] = spec

    def propagate(self, tool_name: str, inputs: list[ToolResult], raw_output: str) -> ToolResult:
        spec = self.tools.get(tool_name)
        if spec is None:
            raise TaintLaunderingError(f"unregistered tool {tool_name!r}: cannot assign provenance")

        inherited = max((r.label for r in inputs), default=TaintLabel.CLEAN, key=lambda l: l.value)

        if spec.taint_preserving:
            # Provenance rule: output inherits union of input labels, regardless of
            # whether the tainted substring survives the transform.
            if inherited is TaintLabel.EXTERNAL_UNTRUSTED and not spec.sanitizing:
                raise TaintLaunderingError(
                    f"tool {tool_name!r} is taint-preserving and would emit "
                    f"EXTERNAL_UNTRUSTED-derived content; quarantine before sink use"
                )
            label = TaintLabel.CLEAN if spec.sanitizing else inherited
        else:
            # Deterministic transform: literal inheritance is sound.
            label = inherited

        return ToolResult(payload=raw_output, label=label, origin=f"{tool_name}")


def guard_sink(result: ToolResult, sink_executes: bool) -> None:
    if sink_executes and result.label is TaintLabel.EXTERNAL_UNTRUSTED:
        raise TaintLaunderingError(
            f"executing sink received EXTERNAL_UNTRUSTED payload from {result.origin!r}"
        )
