# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-result-as-taint-laundering-rather-than-a-clean-label-reset.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-result-as-taint-laundering-rather-than-a-clean-label-reset.warrant.json
# Markdown SHA-256:   54955326731b36f5aa41b2857d0aea8949f8d2574e79490fcb164290099b1f6e
# Code AST SHA-256:   ad62e1a2518d69f8cfa399dda2c652bc0b034ddb8a71a6199acf9eaa8312a438
# Verified Classes:   Trust, TaintLaunderingError, Segment, ToolResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    # Lower = less trusted. join() takes the minimum (taint meet).
    UNTRUSTED_EXTERNAL = 0
    UNTRUSTED_INTERNAL = 1
    TRUSTED_INTERNAL = 2
    TRUSTED_SYSTEM = 3


class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary assigns an output label more trusted than
    the join of its inputs and the content the tool ingested."""


@dataclass
class Segment:
    name: str
    label: Trust
    origin: str


@dataclass
class ToolResult:
    segment: Segment
    ingested: list[Segment] = field(default_factory=list)


def join(labels: Iterable[Trust]) -> Trust:
    labels = list(labels)
    if not labels:
        # No inputs and nothing ingested: only then may output be clean.
        return Trust.TRUSTED_INTERNAL
    return min(labels)


def propagate(
    tool_name: str,
    args: list[Segment],
    result: ToolResult,
    *,
    content_preserving: bool = True,
    schema_validated: bool = False,
) -> Segment:
    """Assign the output label at a tool boundary under the laundering invariant.

    A clean relabel is permitted ONLY when the tool output is provably
    input-independent (content_preserving=False) or every output field was
    validated against a closed schema (schema_validated=True). Otherwise the
    output inherits the join of input taint and ingested content.
    """
    if not content_preserving or schema_validated:
        # Exempt path: output cannot carry the payload. Log justification.
        return Segment(result.segment.name, Trust.TRUSTED_INTERNAL,
                       origin=f"{tool_name}:exempt(content_preserving={content_preserving},"
                              f"schema_validated={schema_validated})")

    input_labels = [a.label for a in args]
    ingested_labels = [s.label for s in result.ingested]
    required = join(input_labels + ingested_labels)

    if result.segment.label > required:
        raise TaintLaunderingError(
            f"tool '{tool_name}' relabeled output '{result.segment.name}' to "
            f"{result.segment.label.name} but join of inputs/ingested is "
            f"{required.name}; laundering of payload from "
            f"{[s.origin for s in args + result.ingested if s.label <= required]}"
        )

    return Segment(result.segment.name, required, origin=f"{tool_name}:propagated")


def handle_summarize(ticket: Segment) -> Segment:
    # Summarizer faithfully reproduces the injected refund instruction.
    summary = Segment("summary", Trust.TRUSTED_INTERNAL, origin="summarize")
    return propagate(
        "summarize",
        args=[ticket],
        result=ToolResult(segment=summary),
        content_preserving=True,
        schema_validated=False,
    )


if __name__ == "__main__":
    ticket = Segment("ticket_body", Trust.UNTRUSTED_EXTERNAL, origin="ticket-4471")
    out = handle_summarize(ticket)
    assert out.label == Trust.UNTRUSTED_EXTERNAL, out
    print("propagated:", out)

    # A handler that resets clean violates the invariant and must raise.
    bad = ToolResult(segment=Segment("summary", Trust.TRUSTED_INTERNAL, "summarize"))
    try:
        propagate("summarize", args=[ticket], result=bad)
    except TaintLaunderingError as e:
        print("blocked:", e)
