# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-after-a-prompt-injection-label-was-demoted-by-a-downstream-summarizer.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-after-a-prompt-injection-label-was-demoted-by-a-downstream-summarizer.warrant.json
# Markdown SHA-256:   b3058814335eac760de0061c02698949a75737b6c42ffa1b326003c9c57be591
# Code AST SHA-256:   09cacce18f2ccada2f7ad7259d5ca97e2351f32af9e7aab17ecafe765be370fa
# Verified Classes:   Taint, TaintDemotionError, ToolResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    LOW = 0
    HIGH = 1

    def join(self, other: "Taint") -> "Taint":
        return Taint(max(self.value, other.value))


class TaintDemotionError(RuntimeError):
    """Raised when a tool result's label is lower than the join of its inputs."""


@dataclass
class ToolResult:
    tool: str
    tool_trust: Taint
    inputs: list["ToolResult"] = field(default_factory=list)
    declared_declassifier: bool = False
    observed_inputs_complete: bool = True

    def transitive_join(self) -> Taint:
        acc = self.tool_trust
        for i in self.inputs:
            acc = acc.join(i.transitive_join())
        return acc

    def effective_label(self) -> Taint:
        if not self.observed_inputs_complete:
            raise TaintDemotionError(
                f"tool={self.tool!r}: inputs not fully observed; "
                "label is indeterminate, must halt before privileged sink"
            )
        if self.declared_declassifier:
            # Explicit, audited declassification is the only legal demotion.
            return Taint.LOW
        return self.transitive_join()


def check_sink(result: ToolResult, sink_requires: Taint = Taint.LOW) -> None:
    label = result.effective_label()
    if label > sink_requires:
        raise TaintDemotionError(
            f"tool={result.tool!r}: label={label.name} exceeds sink "
            f"requirement {sink_requires.name}; refusing privileged action"
        )


# Replay of the observed failure: trusted summarizer over tainted fetch.
fetched = ToolResult(tool="fetch_url", tool_trust=Taint.HIGH)
summary = ToolResult(tool="summarize", tool_trust=Taint.LOW, inputs=[fetched])

# Correct join-semantics: summary inherits HIGH from fetched, sink blocks.
try:
    check_sink(summary, sink_requires=Taint.LOW)
except TaintDemotionError as e:
    print("BLOCKED:", e)
else:
    raise TaintDemotionError("join semantics violated: tainted summary reached sink")

# Indeterminate case: retrieval-augmented summarizer with unobserved inputs.
rag_summary = ToolResult(
    tool="summarize", tool_trust=Taint.LOW,
    inputs=[fetched], observed_inputs_complete=False,
)
try:
    check_sink(rag_summary)
except TaintDemotionError as e:
    print("HALTED:", e)
else:
    raise TaintDemotionError("indeterminate label treated as clean")
