# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-result-re-ingestion-in-an-agent-s-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-result-re-ingestion-in-an-agent-s-working-set.warrant.json
# Markdown SHA-256:   f4fce2d73aa92aec15f56b536fda89af5a6117bfccc9686e5673027037893495
# Code AST SHA-256:   c6d311096785f8fb831f84639ca23c72da55df192aecb46471f81b549ec4e22b
# Verified Classes:   Trust, TaintLaunderingError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # join = max; untrusted dominates


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted-labeled segment has an un-declassified path
    from an untrusted source. Indicates prompt-injection taint laundering."""


@dataclass
class Segment:
    seg_id: str
    label: Trust
    provenance: tuple[str, ...] = ()  # ids of source segments
    declassified_by: Optional[str] = None


def join(*labels: Trust) -> Trust:
    return Trust(max(int(l) for l in labels)) if labels else Trust.TRUSTED


def derive_result(
    tool_name: str,
    tool_declared_class: Trust,
    arg_labels: list[Trust],
    retrieved_labels: list[Trust],
) -> Trust:
    # Derivation closure: result inherits join of ALL inputs, never the
    # tool's declared class. The declared class is only a floor for the
    # tool's own code, not for its output's provenance.
    input_join = join(*(arg_labels + retrieved_labels))
    return join(input_join, tool_declared_class)


def check_no_laundering(seg: Segment, sources: dict[str, Segment]) -> None:
    if seg.label != Trust.TRUSTED:
        return
    if seg.declassified_by is not None:
        return  # audited declassification edge is permitted
    # Walk provenance; any reachable untrusted source without a declass
    # edge on the path is a laundering violation.
    stack = list(seg.provenance)
    seen: set[str] = set()
    while stack:
        sid = stack.pop()
        if sid in seen:
            continue
        seen.add(sid)
        src = sources.get(sid)
        if src is None:
            continue
        if src.label == Trust.UNTRUSTED and src.declassified_by is None:
            raise TaintLaunderingError(
                f"segment {seg.seg_id!r} labeled TRUSTED but has un-declassified "
                f"path to untrusted source {sid!r} (tool={seg.provenance!r})"
            )
        stack.extend(src.provenance)


def ingest_tool_result(
    result_id: str,
    tool_name: str,
    tool_declared_class: Trust,
    arg_segments: list[Segment],
    retrieved_segments: list[Segment],
    sources: dict[str, Segment],
) -> Segment:
    label = derive_result(
        tool_name,
        tool_declared_class,
        [s.label for s in arg_segments],
        [s.label for s in retrieved_segments],
    )
    prov = tuple(s.seg_id for s in arg_segments + retrieved_segments)
    seg = Segment(seg_id=result_id, label=label, provenance=prov)
    check_no_laundering(seg, sources)
    sources[result_id] = seg
    return seg


def gate_irreversible_action(action: str, consumed: list[Segment]) -> None:
    if any(s.label == Trust.UNTRUSTED for s in consumed):
        raise TaintLaunderingError(
            f"irreversible action {action!r} attempted with untrusted input; "
            f"requires explicit declassification"
        )
