# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-re-serializes-injected-content-through-a-schema-validated-return-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-re-serializes-injected-content-through-a-schema-validated-return-channel.warrant.json
# Markdown SHA-256:   0cad3025bcaeda2c157cca73e52073a00ca661136c9224d1486361fc0d3ff567
# Code AST SHA-256:   1dfb987cfc705ceabc6e24edd95c4201a7ffc7ed4d8f51bc2765b65c858dc4dd
# Verified Classes:   TaintLaunderingError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Taint = Literal["TRUSTED", "UNKNOWN", "TAINTED"]


class TaintLaunderingError(RuntimeError):
    """Raised when a model-visible segment lacks a valid derivation record."""


@dataclass
class Segment:
    content: str
    taint: Taint
    derivation: tuple[str, ...] = field(default_factory=tuple)  # input segment ids


def union_taint(inputs: list[Segment]) -> Taint:
    order = {"TRUSTED": 0, "UNKNOWN": 1, "TAINTED": 2}
    worst = max(inputs, key=lambda s: order[s.taint]).taint
    return worst


def construct_from_tool_return(
    raw_segment: Segment,
    parsed_fields: dict[str, str],
    content_bearing_fields: set[str],
    wrapper_namespace_trusted: bool,
) -> Segment:
    """Instrumented constructor: the ONLY legal path to a model-visible segment."""
    if not raw_segment.derivation and raw_segment.taint == "TRUSTED":
        raise TaintLaunderingError(
            "raw input claims TRUSTED with no derivation; refuse to build on it"
        )

    # Detect the laundering condition: free-text field carrying external content
    # while the wrapper would otherwise classify its output as trusted.
    leaked = content_bearing_fields & set(parsed_fields)
    if leaked and wrapper_namespace_trusted and raw_segment.taint != "TRUSTED":
        raise TaintLaunderingError(
            f"content-bearing fields {sorted(leaked)} would inherit wrapper "
            f"TRUSTED namespace over input taint={raw_segment.taint}; "
            f"re-serialization would launder taint"
        )

    inherited = union_taint([raw_segment])
    return Segment(
        content=str(parsed_fields),
        taint=inherited,
        derivation=(id(raw_segment),),
    )


def insert_into_context(seg: Segment) -> Segment:
    """Context-insertion chokepoint: default-deny on missing lineage."""
    if seg.taint != "TRUSTED" and not seg.derivation:
        raise TaintLaunderingError(
            "unlabeled non-trusted segment reached context insertion; "
            "no derivation record to union over"
        )
    return seg
