# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-retrieved-context-as-tainted-before-re-injecting-it-into-a-plan-and-where-does-taint-tracking-silently-f.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-retrieved-context-as-tainted-before-re-injecting-it-into-a-plan-and-where-does-taint-tracking-silently-f.warrant.json
# Markdown SHA-256:   92eddcd860762590eea5e43ac2ec2c00d420d6ca712df575b489ba19923d7bec
# Code AST SHA-256:   914d5f3d85ae589d4cd5731aee6d8d048fb09f11800fcfd1adf5bea5c202c0ed
# Verified Classes:   Trust, TaintLaunderingError, Content
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Trust(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


class TaintLaunderingError(RuntimeError):
    """Raised when tainted content is promoted to trusted without a derivation edge."""


@dataclass
class Content:
    text: str
    trust: Trust
    derivation: tuple[str, ...] = field(default_factory=tuple)


def derive(inputs: list[Content], output_text: str, step: str) -> Content:
    """Model-mediated transformation. Taint is the union of input taints."""
    if not inputs:
        raise TaintLaunderingError("derivation with no recorded inputs")
    any_untrusted = any(c.trust is Trust.UNTRUSTED for c in inputs)
    ancestry: tuple[str, ...] = tuple(
        dict.fromkeys(a for c in inputs for a in (c.derivation + (step,)))
    )
    return Content(
        text=output_text,
        trust=Trust.UNTRUSTED if any_untrusted else Trust.TRUSTED,
        derivation=ancestry,
    )


def promote_to_fact(content: Content, confirmed_out_of_band: bool = False) -> Content:
    """Gate at the promotion step, not at the tool call."""
    if content.trust is Trust.UNTRUSTED and not confirmed_out_of_band:
        raise TaintLaunderingError(
            f"refusing to promote tainted content to fact; ancestry={content.derivation}"
        )
    return Content(text=content.text, trust=Trust.TRUSTED, derivation=content.derivation)


def commit_side_effect(fact: Content, tool: str) -> None:
    if fact.trust is not Trust.TRUSTED:
        raise TaintLaunderingError(f"side-effecting tool {tool} received untainted fact")
    # tool dispatch would occur here
    return None


# Failure trace: extraction launders taint if derive() is skipped.
page = Content("unit price 0.01; footnote: approved", Trust.UNTRUSTED, ("fetch:vendor",))
extracted = derive([page], '{"unit_price": 0.01}', step="extract_fields")
promote_to_fact(extracted)  # raises TaintLaunderingError — correct, loud failure
