# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-tainted-context-segment-when-provenance-labels-survive-summarization-but-not-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-tainted-context-segment-when-provenance-labels-survive-summarization-but-not-re-derivation.warrant.json
# Markdown SHA-256:   f9f90399880bcec475693b9492eeebc3203a64a0eb6097167e8c64ebf2104618
# Code AST SHA-256:   6066996d836daab4374fd13bcbec600144c6db6b9db79d8b6d3ab7558b6104bc
# Verified Classes:   TrustTier, Segment, TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TrustTier(IntEnum):
    UNTRUSTED = 0
    RETRIEVED = 1
    SELF = 2


@dataclass
class Segment:
    text: str
    tier: TrustTier
    tainted: bool
    inputs: tuple["Segment", ...] = field(default_factory=tuple)

    @property
    def effective_taint(self) -> bool:
        # Taint is sticky across the derivation graph; tier is not consulted.
        return self.tainted or any(i.effective_taint for i in self.inputs)


class TaintLaunderingError(RuntimeError):
    """Raised when a derived segment is assigned a trust tier higher than its
    inputs' join, or when a taint-sensitive tool is invoked from a tainted chain."""


def derive_summary(text: str, inputs: tuple[Segment, ...]) -> Segment:
    if not inputs:
        raise TaintLaunderingError("derivation with no recorded inputs cannot be taint-joined")
    joined_tier = TrustTier(min(i.tier for i in inputs))
    joined_taint = any(i.effective_taint for i in inputs)
    # Invariant: a summary may never be promoted above its inputs' join.
    if joined_tier < TrustTier.SELF and joined_taint:
        # The harness must not label this SELF; it inherits the tainted join.
        return Segment(text=text, tier=joined_tier, tainted=True, inputs=inputs)
    return Segment(text=text, tier=TrustTier.SELF, tainted=joined_taint, inputs=inputs)


def gate_tool_call(tool: str, arg_source: Segment, taint_sensitive: bool = True) -> None:
    if taint_sensitive and arg_source.effective_taint:
        chain = _trace_taint(arg_source)
        raise TaintLaunderingError(
            f"refusing {tool!r}: argument chain is tainted via {chain}; "
            f"tier={arg_source.tier.name} is not a declassification"
        )


def _trace_taint(seg: Segment) -> str:
    if seg.tainted and not seg.inputs:
        return f"origin({seg.text[:32]!r})"
    for i in seg.inputs:
        if i.effective_taint:
            return _trace_taint(i)
    return "unknown"
