# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-the-next-reasoning-hop-and-why-post-hoc-sanitization-cannot-recover-a-poisoned-context.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-the-next-reasoning-hop-and-why-post-hoc-sanitization-cannot-recover-a-poisoned-context.warrant.json
# Markdown SHA-256:   e2cf927aa44ea224cecf091f52269a6a53911f25ef04978defff328e02ea37ff
# Code AST SHA-256:   2e8a49c5e576db00ec21f6dc457ccc57d2b761595266ccb6682d23b78ee3c4e7
# Verified Classes:   TaintError, Label, LabeledValue
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from enum import IntEnum
from typing import Optional


class TaintError(RuntimeError):
    """Raised when a tainted value reaches a sink without declassification."""


class Label(IntEnum):
    UNTRUSTED = 0
    INTERNAL = 1
    SECRET = 2


def join(labels):
    """Lattice join: the least upper bound of a set of labels."""
    if not labels:
        raise TaintError("cannot join an empty label set")
    return max(labels)


class LabeledValue:
    __slots__ = ("text", "label")

    def __init__(self, text: str, label: Optional[Label]):
        if label is None:
            raise TaintError("value entered pipeline without provenance label")
        self.text = text
        self.label = label


def sanitize(value: LabeledValue) -> LabeledValue:
    """Strip patterns but PRESERVE the label. Never declassify by transformation."""
    cleaned = value.text.replace("ignore previous instructions", "")
    return LabeledValue(cleaned, value.label)  # label carried, not dropped


def check_sink(context: list[LabeledValue], sink_clearance: Label) -> None:
    """A sink is permitted only if the hop's input label is dominated by clearance."""
    if not context:
        raise TaintError("sink invoked with empty context")
    hop_label = join([v.label for v in context])
    if hop_label > sink_clearance:
        raise TaintError(
            f"tainted decision: hop label {hop_label.name} exceeds "
            f"sink clearance {sink_clearance.name}; quarantine required"
        )


def invoke_send_email(context, to, body):
    # context includes the fetch_url result (UNTRUSTED) and read_crm (INTERNAL)
    check_sink(context, Label.INTERNAL)
    return {"sent": True, "to": to}
