# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-label-before-tool-result-re-entry-and-when-does-label-laundering-through-sanitization-brea.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-label-before-tool-result-re-entry-and-when-does-label-laundering-through-sanitization-brea.warrant.json
# Markdown SHA-256:   49feec43e6adc9ffb99f96892f3f76dee93b3d0d0dc049fac07d7f8fefb7d64f
# Code AST SHA-256:   ea89dd9161cbcc2f0cb778c773922526126580dd2ec9442ced87a58c758445b1
# Verified Classes:   TaintViolation, Sink, Label, Artifact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintViolation(RuntimeError):
    """Raised when a tainted artifact reaches a sink its label forbids."""


class Sink(Enum):
    CONTEXT_ONLY = "context_only"
    TOOL_CALL = "tool_call"
    OUTBOUND = "outbound"


@dataclass(frozen=True)
class Label:
    tainted: bool
    allowed_sinks: FrozenSet[Sink]
    lineage: FrozenSet[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        # Monotone join: taint is sticky, sinks only narrow.
        return Label(
            tainted=self.tainted or other.tainted,
            allowed_sinks=self.allowed_sinks & other.allowed_sinks,
            lineage=self.lineage | other.lineage,
        )


@dataclass(frozen=True)
class Artifact:
    artifact_id: str
    label: Label


def derive(source: Artifact, transform_name: str, oracle_certified: bool) -> Artifact:
    """A derived artifact inherits the source label unless an out-of-band
    oracle certifies the transformation as non-instruction-preserving."""
    if oracle_certified:
        new_label = Label(
            tainted=False,
            allowed_sinks=frozenset(Sink),
            lineage=source.label.lineage | {source.artifact_id},
        )
    else:
        # No certification: inherit taint, keep sink restrictions.
        new_label = Label(
            tainted=source.label.tainted,
            allowed_sinks=source.label.allowed_sinks,
            lineage=source.label.lineage | {source.artifact_id},
        )
    return Artifact(artifact_id=f"{source.artifact_id}::{transform_name}", label=new_label)


def tool_call_gate(argument: Artifact, required_sink: Sink) -> None:
    if argument.label.tainted and required_sink not in argument.label.allowed_sinks:
        raise TaintViolation(
            f"artifact {argument.artifact_id} is tainted "
            f"(lineage={sorted(argument.label.lineage)}) and its label forbids "
            f"sink={required_sink.value}; allowed={sorted(s.value for s in argument.label.allowed_sinks)}"
        )


def demo():
    fetch = Artifact(
        artifact_id="web_fetch:1",
        label=Label(tainted=True, allowed_sinks=frozenset({Sink.CONTEXT_ONLY})),
    )
    # LLM summarization without oracle certification: taint survives.
    summary = derive(fetch, "llm_summarize", oracle_certified=False)
    # Gate blocks the laundered summary from being used as a tool argument.
    tool_call_gate(summary, Sink.TOOL_CALL)
    # Deterministic extractor certified by oracle: declassification permitted.
    entities = derive(fetch, "regex_entities", oracle_certified=True)
    tool_call_gate(entities, Sink.TOOL_CALL)


if __name__ == "__main__":
    demo()
