# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-tool-dispatch-rather-than-after-retrieval-scoring.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-tool-dispatch-rather-than-after-retrieval-scoring.warrant.json
# Markdown SHA-256:   80c4d8cffeef8ab6af6e68171b29faa6f1876b0558a871cd36e6fdf2165c881d
# Code AST SHA-256:   f55ada72c4c1f97a10bf2b9d99375ebad3a44de127dd95938cf1e463f2b91a4d
# Verified Classes:   TaintClass, TaintLaunderingError, QuarantineViolation, Span, DerivedArgument, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintClass(Enum):
    TRUSTED_INTERNAL = 0
    UNTRUSTED_EXTERNAL = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a state transformation drops a provenance/taint label."""


class QuarantineViolation(RuntimeError):
    """Raised when a side-effecting tool call is dispatched from tainted spans
    without an explicit, out-of-band declassification event."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    taint: TaintClass


@dataclass
class DerivedArgument:
    name: str
    value: str
    contributors: tuple[str, ...]  # span_ids that fed this argument


@dataclass
class ContextState:
    spans: dict[str, Span] = field(default_factory=dict)
    declassified: set[str] = field(default_factory=set)

    def compact(self) -> "ContextState":
        # Invariant: compaction MUST carry taint. A serializer that emits only
        # {text, score} is a laundering path and must raise, not silently drop.
        new_spans: dict[str, Span] = {}
        for sid, sp in self.spans.items():
            if sp.taint is None:
                raise TaintLaunderingError(
                    f"span {sid} lost taint label during compaction"
                )
            new_spans[sid] = Span(sp.span_id, sp.text, sp.taint)
        return ContextState(spans=new_spans, declassified=set(self.declassified))


def derive(arg_name: str, value: str, contributors: Iterable[Span]) -> DerivedArgument:
    # Monotonic taint: derived argument inherits the union of contributor taint.
    contributor_ids = tuple(s.span_id for s in contributors)
    return DerivedArgument(arg_name, value, contributor_ids)


def dispatch_side_effecting_tool(
    tool: str,
    args: list[DerivedArgument],
    state: ContextState,
) -> None:
    """Enforcement point: immediately before dispatch, after all transformations."""
    for arg in args:
        for sid in arg.contributors:
            span = state.spans.get(sid)
            if span is None:
                raise TaintLaunderingError(
                    f"argument {arg.name!r} references unknown span {sid}; "
                    f"provenance graph is inconsistent"
                )
            if span.taint is TaintClass.UNTRUSTED_EXTERNAL and sid not in state.declassified:
                raise QuarantineViolation(
                    f"tool {tool!r} blocked: argument {arg.name!r} derived from "
                    f"tainted span {sid} ({span.text[:48]!r}) with no declassification token"
                )
    # Only reached when every contributing span is trusted or declassified.
    _execute(tool, args)


def _execute(tool: str, args: list[DerivedArgument]) -> None:
    pass  # side effect elided


def run_task() -> None:
    state = ContextState(
        spans={
            "c_001": Span("c_001", "internal policy reference", TaintClass.TRUSTED_INTERNAL),
            "c_117": Span("c_117", "recommended recipients for compliance summaries",
                          TaintClass.UNTRUSTED_EXTERNAL),
        }
    )
    state = state.compact()  # taint must survive; raises if dropped
    to_arg = derive(
        "to",
        "ops@internal.example,audit@external.example",
        [state.spans["c_001"], state.spans["c_117"]],
    )
    dispatch_side_effecting_tool("send_email", [to_arg], state)


if __name__ == "__main__":
    run_task()
