# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-result-re-serialization-in-agent-dataflow-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-result-re-serialization-in-agent-dataflow-graphs.warrant.json
# Markdown SHA-256:   8e1be74dc5b17f6f6782109ad70aa8c3d5c86550bc2d1d06295be032531ac003
# Code AST SHA-256:   f3275cff707b275f7443df5274be2cfda9131ac7edc47f6002ce85d9c5e18fe7
# Verified Classes:   TaintLaunderingError, Value
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a value's provenance DAG is empty or reaches an
    untrusted root without an audited declassify node."""


@dataclass(frozen=True)
class Value:
    payload: str
    parents: FrozenSet[str] = field(default_factory=frozenset)
    declassified: bool = False


# Registry of transformation taint policies. Anything not here is ambiguous.
TRANSFORM_POLICY = {
    "strip_html": "preserving",
    "json_loads": "preserving",
    "json_dumps": "preserving",
    "format": "preserving",
    "closed_enum": "clearing",  # requires proof obligation elsewhere
}

UNTRUSTED_ROOTS = {"fetch_url"}


def transform(name: str, src: Value) -> Value:
    policy = TRANSFORM_POLICY.get(name)
    if policy is None:
        raise TaintLaunderingError(
            f"unregistered transformation {name!r}: taint-ambiguous, fail closed"
        )
    if policy == "clearing":
        # Caller must supply proof; here we refuse to clear silently.
        raise TaintLaunderingError(
            f"clearing transform {name!r} requires audited proof, not implicit trust"
        )
    if not src.parents and not src.declassified:
        raise TaintLaunderingError(
            f"transform {name!r} on value with empty provenance DAG: "
            f"uninstrumented construction is indistinguishable from laundering"
        )
    return Value(payload=src.payload, parents=src.parents | {name})


def egress_guard(arg: Value, sink: str) -> None:
    if arg.declassified:
        return  # audited declassify node recorded upstream
    if not arg.parents:
        raise TaintLaunderingError(
            f"{sink}: argument has empty provenance DAG; refusing to send"
        )
    reachable = arg.parents & UNTRUSTED_ROOTS
    if reachable:
        raise TaintLaunderingError(
            f"{sink}: argument provenance reaches untrusted root(s) {sorted(reachable)}"
        )


def run_planner(fetched: Value) -> None:
    # The bug: extracting text in-process without a registered transform.
    # text = fetched.payload.replace("<html>", "")  # <-- uninstrumented, empty parents
    text = transform("strip_html", fetched)
    egress_guard(text, sink="send_email")
