# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-schema-validating-tool-provenance-labels-that-survive-the-model-but-not-the-json-round.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-schema-validating-tool-provenance-labels-that-survive-the-model-but-not-the-json-round.warrant.json
# Markdown SHA-256:   a9fdfe8f21cc118f7d734edbae4a925d98855247f87d9e253c4ef6d12cb8d920
# Code AST SHA-256:   58864cc5712055be28c215f989b72ac9eeb1cbf243aaf97dca26ab79b91d6d15
# Verified Classes:   TaintLaunderingError, Segment, DerivedArg, Registry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

TrustLabel = Literal["trusted:operator", "untrusted:web", "untrusted:tool_output"]
Transform = Literal["identity", "paraphrase", "summarize", "translate", "encode"]
EgressTools = {"send_email", "create_calendar_event", "http_post", "file_write"}


class TaintLaunderingError(RuntimeError):
    """Raised when an egress tool argument carries untrusted provenance
    that was not mechanically cleared by the IFC join."""


@dataclass
class Segment:
    seg_id: str
    label: TrustLabel
    text: str


@dataclass
class DerivedArg:
    value: str
    source_ids: list[str]
    transform: Transform
    sanitization_claim: bool = False


@dataclass
class Registry:
    segments: dict[str, Segment] = field(default_factory=dict)

    def label_union(self, source_ids: list[str]) -> set[TrustLabel]:
        labels: set[TrustLabel] = set()
        for sid in source_ids:
            if sid not in self.segments:
                # Unknown source id: treat as maximally untrusted.
                labels.add("untrusted:tool_output")
            else:
                labels.add(self.segments[sid].label)
        return labels


def _sanitization_verified(value: str) -> bool:
    # Constrained classifier stand-in: flag actionable content.
    import re
    actionable = [
        r"[\w.+-]+@[\w-]+\.[\w.]+",       # email
        r"https?://\S+",                   # URL
        r"\b(forward|send|delete|transfer|wire|pay)\b",  # imperative verbs
    ]
    return not any(re.search(p, value, re.IGNORECASE) for p in actionable)


def ifc_join(tool: str, args: dict[str, DerivedArg], reg: Registry) -> None:
    """Enforce: no egress argument reaches the tool with untrusted taint
    that was not cleared by verified sanitization. Default-deny on
    missing provenance."""
    if tool not in EgressTools:
        return
    for name, arg in args.items():
        if not arg.source_ids:
            raise TaintLaunderingError(
                f"egress arg '{name}' has no declared source_ids; "
                f"default-deny (treated as untrusted)"
            )
        labels = reg.label_union(arg.source_ids)
        untrusted = {l for l in labels if l.startswith("untrusted:")}
        if not untrusted:
            continue
        if arg.transform in ("identity", "encode"):
            raise TaintLaunderingError(
                f"egress arg '{name}' derived via {arg.transform} from "
                f"{sorted(untrusted)}; rejected"
            )
        # paraphrase/summarize/translate: claim must be verified.
        if not arg.sanitization_claim:
            raise TaintLaunderingError(
                f"egress arg '{name}' from {sorted(untrusted)} via "
                f"{arg.transform} without sanitization claim; rejected"
            )
        if not _sanitization_verified(arg.value):
            raise TaintLaunderingError(
                f"egress arg '{name}' sanitization claim failed verification "
                f"(actionable content present); taint preserved"
            )
    # All args cleared.
