# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-propagate-taint-across-a-sandbox-re-entry-boundary-the-re-entry-laundering-invariant-in-taint-aware-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-propagate-taint-across-a-sandbox-re-entry-boundary-the-re-entry-laundering-invariant-in-taint-aware-tool.warrant.json
# Markdown SHA-256:   d58de880a5582bfbacbc818ff0310071789f25717fb615a32cdd5d9d910f2878
# Code AST SHA-256:   b10e3f7863384f070cc1d802180b5d2fbe3d7dc0f0d941d75bc2779e5bb8e220
# Verified Classes:   TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a value re-enters the sandbox without a provable clean provenance."""
    pass


class Provenance:
    def __init__(self, sources, certified_clean=False):
        self.sources = frozenset(sources)
        self.certified_clean = certified_clean

    def is_tainted(self):
        return bool(self.sources) or not self.certified_clean


def reenter(value, provenance, tool_declared_pure, inputs_all_trusted):
    """Gate a tool return value back into the agent's argument space.

    Refuses when provenance cannot be certified clean. Unknown provenance
    defaults to tainted: the safe default that prevents re-entry laundering.
    """
    if provenance is None:
        raise TaintLaunderingError(
            f"re-entry of {value!r} has unknown provenance; refusing to launder taint"
        )
    if provenance.is_tainted():
        # Re-tag and let the egress sink checker catch it downstream.
        return value, provenance
    if not (tool_declared_pure and inputs_all_trusted):
        raise TaintLaunderingError(
            f"re-entry of {value!r} claims clean provenance but tool purity="
            f"{tool_declared_pure} inputs_trusted={inputs_all_trusted}; "
            "cannot certify independence from tainted sources"
        )
    return value, Provenance(sources=(), certified_clean=True)
