# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-label-laundering-at-the-tool-return-boundary-in-prompt-injection-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-label-laundering-at-the-tool-return-boundary-in-prompt-injection-taint-tracking.warrant.json
# Markdown SHA-256:   ffcd655e36c9f614ed44525b22f9ab63aabf4f2bfad5e735d346a3a216fc1331
# Code AST SHA-256:   ad721bb23bbfdba8683e214bd934fbeee595e2c267565bacdd8b4fdb6c2b35cf
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool return would reset provenance instead of joining input labels."""
    pass


TRUST_ORDER = {"clean": 0, "opaque": 1, "untrusted": 2}


def join_labels(input_labels: set[str], tool_intrinsic: str = "clean") -> str:
    """Conservative join: output label is the max-trust of all influencing inputs."""
    if not input_labels:
        # A tool with no declared inputs is opaque by default, never clean.
        return "opaque"
    worst = max(input_labels | {tool_intrinsic}, key=lambda l: TRUST_ORDER[l])
    return worst


def label_tool_return(tool_name: str, declared_inputs: set[str] | None,
                      input_labels: set[str], output_preview: str) -> str:
    """
    Assign a provenance label to a tool's return value.

    The only sound rule is the join over all inputs the tool read. A tool that
    cannot declare its read-set is opaque and must not be relabeled clean.
    """
    if declared_inputs is None:
        # Opaque tool: cannot prove what influenced the output.
        return "opaque"

    # Verify the declared read-set is actually covered by the labels we hold.
    missing = declared_inputs - input_labels
    if missing:
        raise TaintLaunderingError(
            f"tool {tool_name!r} read inputs {sorted(missing)} for which no "
            f"provenance label exists; refusing to assign a clean label"
        )

    joined = join_labels(input_labels, tool_intrinsic="clean")

    # Guard: a transform tool must never emit 'clean' from a tainted input,
    # even if the output preview looks benign. This is the laundering check.
    if joined == "untrusted" and output_preview.strip():
        return "untrusted"

    return joined


def gate_privileged_action(action: str, context_label: str) -> None:
    if TRUST_ORDER[context_label] >= TRUST_ORDER["opaque"]:
        raise TaintLaunderingError(
            f"action {action!r} blocked: context label {context_label!r} "
            f"is not clean; require explicit approval or de-taint via trusted re-derivation"
        )
