# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-provenance-label-survives-a-tool-call-but-the-injection-payload-is-re-encoded-across-a-memory-writ.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-provenance-label-survives-a-tool-call-but-the-injection-payload-is-re-encoded-across-a-memory-writ.warrant.json
# Markdown SHA-256:   8fc9c91773599f061d8ed0e3f7c3d29527e833a6650594ed5d86d16f06829a9f
# Code AST SHA-256:   2f673c06ea9e9fe2d0f835304fdaef509f051e0275763807d585f5abd86f2043
# Verified Classes:   Taint, TaintLaunderingError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    NONE = 0
    UNKNOWN = 1
    INSTRUCTION_INJECTION = 2
    CREDENTIAL_EXFIL = 3


def join(a: Taint, b: Taint) -> Taint:
    # Monotone least-upper-bound: taint may only increase.
    return Taint(max(int(a), int(b)))


class TaintLaunderingError(RuntimeError):
    """Raised when a pipeline stage attempts to lower an inherited taint label."""


@dataclass(frozen=True)
class Segment:
    text: str
    taint: Taint
    sources: FrozenSet[str] = field(default_factory=frozenset)


def derive(parents: list[Segment], new_text: str, stage: str) -> Segment:
    """Provenance-preserving transform: output taint is the join of inputs."""
    if not parents:
        raise TaintLaunderingError(f"stage {stage!r} produced output with no provenance parents")
    t = Taint.NONE
    srcs: set[str] = set()
    for p in parents:
        t = join(t, p.taint)
        srcs.update(p.sources)
    return Segment(text=new_text, taint=t, sources=frozenset(srcs))


def assemble_for_resume(
    persisted: Segment,
    rederived_signature_match: bool,
    sink_is_egress: bool,
) -> Segment:
    """Assembler must inherit-and-monotone; may not downgrade on non-match."""
    derived = (
        Taint.INSTRUCTION_INJECTION if rederived_signature_match else Taint.UNKNOWN
    )
    effective = join(persisted.taint, derived)

    # Guardrail: never allow a lower label than what was persisted.
    if int(effective) < int(persisted.taint):
        raise TaintLaunderingError(
            f"assembler would downgrade taint {persisted.taint.name} -> {effective.name} "
            f"for segment sources={sorted(persisted.sources)}"
        )

    if sink_is_egress and effective != Taint.NONE:
        # Fail closed: egress sinks require explicit declassification.
        raise TaintLaunderingError(
            f"tainted segment (taint={effective.name}, sources={sorted(persisted.sources)}) "
            f"routed to egress sink without declassification"
        )
    return Segment(text=persisted.text, taint=effective, sources=persisted.sources)


def write_memory(seg: Segment, normalizer_strips_quotes: bool) -> Segment:
    text = seg.text.replace('"', "") if normalizer_strips_quotes else seg.text
    # Normalization is provenance-preserving: taint and sources ride along.
    return Segment(text=text, taint=seg.taint, sources=seg.sources)
