# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-taint-its-own-output-the-provenance-laundering-boundary-in-taint-aware-tool-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-taint-its-own-output-the-provenance-laundering-boundary-in-taint-aware-tool-sandboxes.warrant.json
# Markdown SHA-256:   5a42f4500e5e9d3e9c78125b192b4dd11b3f559454eb7a6b09de8348ab9f8648
# Code AST SHA-256:   e58f0f77b721ca6eaca575df258e35f980ee38a3a5de7ab1adc27a967b6a0b50
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a declassifier would promote taint on a free-text field."""
    pass


CLOSED_DOMAIN_TYPES = {"int", "float", "bool", "date", "enum", "bounded_id"}


def promote_taint(tool_name: str, schema: dict, values: dict, t_in: str) -> dict:
    """
    Compute per-field output taint for a declassifier's result.
    schema: {field: {"type": str, "pattern": str | None}}
    values: {field: actual_value}
    Returns {field: taint}.
    """
    if not tool_name:
        raise TaintLaunderingError("declassifier invoked without tool identity")

    out = {}
    for field, spec in schema.items():
        ftype = spec.get("type", "str")
        val = values.get(field)

        if ftype not in CLOSED_DOMAIN_TYPES:
            # free-text or unknown type: cannot declassify
            out[field] = t_in
            continue

        pattern = spec.get("pattern")
        if pattern is not None:
            import re
            if val is None or not re.fullmatch(pattern, str(val)):
                # validation failure: do not promote
                out[field] = t_in
                continue

        out[field] = "TRUSTED"

    # If any field remains tainted, the whole result is tainted for
    # directive-argument routing, even though arithmetic fields promoted.
    if any(t != "TRUSTED" for t in out.values()):
        out["__directive_taint__"] = t_in
    else:
        out["__directive_taint__"] = "TRUSTED"

    return out


def route_privileged_call(field_taint: dict, directive_field: str) -> None:
    """Block a privileged call if the directive's source is tainted."""
    if field_taint.get("__directive_taint__") != "TRUSTED":
        raise TaintLaunderingError(
            f"privileged call blocked: directive field {directive_field!r} "
            "derives from a result containing an unvalidated free-text field"
        )
    return None
