# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tainted-value-provenance-tag-as-non-transferable-across-tool-call-boundaries-and-why-does-naive-tag-inherit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tainted-value-provenance-tag-as-non-transferable-across-tool-call-boundaries-and-why-does-naive-tag-inherit.warrant.json
# Markdown SHA-256:   cde70ee2123b5258ce14adf37671f35ec1eb460a88fe50c673b544a9c9786208
# Code AST SHA-256:   bbf6445a88329aa8d719f88bf80f38b4146031275beea334d2090d5b897e0852
# Verified Classes:   TaintLossError, Tainted, ToolSpec, Runtime
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLossError(RuntimeError):
    """Raised when a value reaches an egress sink with no provenance record,
    indicating the taint tag was dropped somewhere along the flow."""


@dataclass
class Tainted:
    value: Any
    tainted: bool
    origin: str | None = None


@dataclass
class ToolSpec:
    name: str
    egress: bool
    transfer: str  # "identity" | "conservative" | "sanitizing"
    warrant: str | None = None  # e.g. "recipient_allowlist"


@dataclass
class Runtime:
    tools: dict[str, ToolSpec] = field(default_factory=dict)

    def invoke(self, name: str, args: dict[str, Tainted]) -> Tainted:
        spec = self.tools.get(name)
        if spec is None:
            # Unannotated tool: treat as conservative, never clean.
            spec = ToolSpec(name=name, egress=True, transfer="conservative")

        any_tainted = any(a.tainted for a in args.values())

        if spec.egress and any_tainted and spec.warrant is None:
            raise TaintLossError(
                f"egress tool {name!r} received tainted leaf "
                f"{[k for k, a in args.items() if a.tainted]}; no warrant"
            )

        if spec.transfer == "sanitizing":
            return Tainted(value="<sanitized>", tainted=False, origin=None)
        if spec.transfer in ("identity", "conservative") and any_tainted:
            # Conservative closure: output stays tainted.
            return Tainted(value="<result>", tainted=True, origin="derived")
        return Tainted(value="<result>", tainted=False, origin="agent_authored")

    def check_clean_leaf(self, leaf: Tainted) -> None:
        if not leaf.tainted and leaf.origin is None:
            raise TaintLossError(
                "clean leaf with no provenance: tag was dropped, "
                "treat as tainted and deny egress"
            )


def demo() -> None:
    rt = Runtime(tools={
        "retrieve": ToolSpec("retrieve", egress=False, transfer="conservative"),
        "summarize": ToolSpec("summarize", egress=False, transfer="conservative"),
        "send_email": ToolSpec("send_email", egress=True, transfer="identity"),
    })
    chunk = Tainted(value="customer rows", tainted=True, origin="doc_8812")
    summary = rt.invoke("summarize", {"text": chunk})  # stays tainted
    rt.invoke("send_email", {"body": summary})  # raises TaintLossError
