# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-a-tool-call-boundary-when-the-sandbox-verdict-is-computed-over-a-re-serialized-argument-tree-r.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-a-tool-call-boundary-when-the-sandbox-verdict-is-computed-over-a-re-serialized-argument-tree-r.warrant.json
# Markdown SHA-256:   46262366e5c62a53b914f02eefebac64d2089322a1a29f8b91f88e91b1db9fea
# Code AST SHA-256:   a46aadcb1e6c718bc0179598cd7bf9bb68620837b073c3e89bbee07300ba8bea
# Verified Classes:   TaintLaunderingError, Taint, Emission
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when serialization drops or fragments taint between emission and invocation."""


@dataclass(frozen=True)
class Taint:
    labels: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Taint") -> "Taint":
        return Taint(self.labels | other.labels)

    def is_sensitive(self, sensitive: Iterable[str]) -> bool:
        return bool(self.labels & frozenset(sensitive))


@dataclass
class Emission:
    # Raw argument tree as the model emitted it, with per-node taint witnesses
    # derived from the context manifest at generation time.
    tree: dict[str, Any]
    taint: dict[str, Taint]

    def taint_of(self, path: str) -> Taint:
        return self.taint.get(path, Taint())


def serialize(emission: Emission, schema: dict[str, str]) -> tuple[dict[str, Any], dict[str, Taint]]:
    """Untrusted serializer: strip/normalize/coerce. Must be taint-monotone."""
    out: dict[str, Any] = {}
    out_taint: dict[str, Taint] = {}
    for key, typ in schema.items():
        if key not in emission.tree:
            continue
        raw = emission.tree[key]
        # Normalization that historically laundered taint:
        if typ == "integer":
            value = int(str(raw).strip())
        elif typ == "string":
            value = str(raw).strip().lower()
        else:
            value = raw
        out[key] = value
        # Sticky taint: the serializer carries the emission's witness forward.
        out_taint[key] = emission.taint_of(key)
    return out, out_taint


def enforce_taint_boundary(
    emission: Emission,
    schema: dict[str, str],
    egress_tool: bool,
    sensitive_labels: Iterable[str] = ("SECRET", "PII"),
) -> dict[str, Any]:
    invocation, invocation_taint = serialize(emission, schema)

    if egress_tool:
        for path, taint in invocation_taint.items():
            if taint.is_sensitive(sensitive_labels):
                raise TaintLaunderingError(
                    f"egress blocked: argument {path!r} carries sensitive taint "
                    f"{sorted(taint.labels)} into egress tool"
                )

    # Monotonicity assertion: invocation taint must dominate emission taint.
    for path, emitted in emission.taint.items():
        if path in invocation_taint:
            if not invocation_taint[path].labels >= emitted.labels:
                raise TaintLaunderingError(
                    f"serializer dropped taint on {path!r}: "
                    f"emission={sorted(emitted.labels)} "
                    f"invocation={sorted(invocation_taint[path].labels)}"
                )
    return invocation


# Trace: labeled customer ID "0042" emitted into an integer field.
em = Emission(
    tree={"customer_id": "0042"},
    taint={"customer_id": Taint(frozenset({"SECRET"}))},
)
try:
    enforce_taint_boundary(em, {"customer_id": "integer"}, egress_tool=True)
except TaintLaunderingError as exc:
    # Correct behavior: the coercion to 42 does not launder the taint,
    # because taint rode on the emission witness, not on value identity.
    print("blocked:", exc)
