# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-before-it-re-enters-the-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-before-it-re-enters-the-reasoning-loop.warrant.json
# Markdown SHA-256:   451d4150f18daffd1840a1842de526bdb36698573f521e7d20cb8cae927c3548
# Code AST SHA-256:   3d7f3257bc5f718f21c7db44286a9d1c7e14924ce8fd0f12654b8289de64e99c
# Verified Classes:   Taint, TaintLaunderingError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Callable


class Taint(IntEnum):
    INTERNAL = 0
    EXTERNAL_TOOL = 1
    EXTERNAL_WEB = 2
    INJECTED = 3


def join(*labels: Taint) -> Taint:
    return Taint(max(labels)) if labels else Taint.INTERNAL


class TaintLaunderingError(RuntimeError):
    """Raised when a generative transform attempts to lower taint on its output."""


@dataclass(frozen=True)
class Span:
    text: str
    taint: Taint
    producer: str


def generative_transform(
    inputs: list[Span],
    model_fn: Callable[[str], str],
    producer: str,
) -> Span:
    joined = join(*(s.taint for s in inputs))
    out_text = model_fn("".join(s.text for s in inputs))
    # A model call cannot declassify. Output taint is the join of inputs.
    return Span(text=out_text, taint=joined, producer=producer)


def deterministic_extract(
    source: Span,
    extractor: Callable[[str], str],
    producer: str,
) -> Span:
    # Schema-typed extraction is a legitimate declassification channel:
    # the parser, not a model, decided which bytes survive.
    out_text = extractor(source.text)
    return Span(text=out_text, taint=source.taint, producer=producer)


def admit_to_action_context(span: Span, action_is_irreversible: bool) -> None:
    if span.taint >= Taint.EXTERNAL_WEB and action_is_irreversible:
        raise TaintLaunderingError(
            f"span from {span.producer!r} carries taint={span.taint.name}; "
            f"refusing admission to irreversible-action context without "
            f"explicit human declassification"
        )


def check_label_soundness(output: Span, inputs: list[Span]) -> None:
    expected = join(*(s.taint for s in inputs))
    if output.taint < expected:
        raise TaintLaunderingError(
            f"label laundering: output taint={output.taint.name} < "
            f"join(inputs)={expected.name} for producer {output.producer!r}"
        )
