# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-sink-blocking-when-untrusted-retrieved-content-and-trusted-task-instructions-share-a-single-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-sink-blocking-when-untrusted-retrieved-content-and-trusted-task-instructions-share-a-single-context-window.warrant.json
# Markdown SHA-256:   9b6f4d6309cf3f55ebd8f112f6b3a82f9e158fd2fc8b33a3c2b5e1ebe60f7113
# Code AST SHA-256:   db23f17f72dcda42041fa290c3c1f1882e3994a94c2a812ab3c201e56cddb3ef
# Verified Classes:   TaintLaunderingError, Taint, Declassification, ToolOutput
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a high sink is reachable from tainted premises without declassification."""


@dataclass(frozen=True)
class Taint:
    labels: frozenset[str] = frozenset()
    premise_hashes: frozenset[str] = frozenset()

    def union(self, other: "Taint") -> "Taint":
        return Taint(self.labels | other.labels, self.premise_hashes | other.premise_hashes)

    @property
    def is_tainted(self) -> bool:
        return bool(self.labels)


@dataclass(frozen=True)
class Declassification:
    sink: str
    argument_fingerprint: str
    premise_hashes: frozenset[str]
    human_approver: str


@dataclass
class ToolOutput:
    value: Any
    taint: Taint
    decision_producing: bool = False


HIGH_SINKS = frozenset({"wire_transfer", "shell_exec", "http_post_external", "write_credentials"})


def propagate_taint(tool_name: str, inputs: list[ToolOutput], output: Any) -> ToolOutput:
    """Transitive provenance: outputs inherit union of input taint.
    Decision-producing tools (summarizers, classifiers) always propagate,
    even if their output is a fresh literal."""
    merged = Taint()
    for i in inputs:
        merged = merged.union(i.taint)
    decision_producing = tool_name in {"summarize", "classify", "decide", "judge"}
    if not merged.is_tainted and not decision_producing:
        return ToolOutput(value=output, taint=merged)
    return ToolOutput(value=output, taint=merged, decision_producing=decision_producing)


def invoke_high_sink(
    sink: str,
    arguments: dict[str, Any],
    argument_taints: dict[str, Taint],
    branch_predicate_taint: Taint,
    tool_selection_taint: Taint,
    declassification: Declassification | None,
) -> None:
    if sink not in HIGH_SINKS:
        raise TaintLaunderingError(f"sink {sink!r} is not a registered high sink")

    reachable_taint = branch_predicate_taint.union(tool_selection_taint)
    for name, t in argument_taints.items():
        reachable_taint = reachable_taint.union(t)

    if not reachable_taint.is_tainted:
        return

    if declassification is None:
        raise TaintLaunderingError(
            f"high sink {sink!r} reachable from tainted premises "
            f"{sorted(reachable_taint.premise_hashes)} with no declassification"
        )

    fingerprint = repr(sorted(arguments.items()))
    if declassification.sink != sink:
        raise TaintLaunderingError(
            f"declassification bound to {declassification.sink!r}, not {sink!r}"
        )
    if declassification.argument_fingerprint != fingerprint:
        raise TaintLaunderingError(
            "declassification argument fingerprint mismatch: "
            "approval does not bind the actual sink arguments"
        )
    if not reachable_taint.premise_hashes.issubset(declassification.premise_hashes):
        raise TaintLaunderingError(
            "declassification does not cover all tainted premises reachable at sink"
        )
