# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-across-a-multi-hop-tool-chain-when-the-taint-is-laundered-through-a-summarization-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-across-a-multi-hop-tool-chain-when-the-taint-is-laundered-through-a-summarization-hop.warrant.json
# Markdown SHA-256:   6a932efb6d576c78bb929d1a6caf8cc99df6adb3074a6b8a95043a596af1481c
# Code AST SHA-256:   672ed535515b355d88f800c0271d0901026700c8c8e5e6790521e2f8159450a6
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a model hop consumes tainted input and emits output
    that a lexical tracker would mislabel as clean."""
    pass


def propagate_taint(hop_inputs: list[dict], hop_output: str) -> dict:
    """
    Each hop_input: {"content": str, "taint": "clean" | "external" | "mixed"}
    Taint is a join (worst-case) over all inputs. A model hop is a
    transform, never a sanitizer: output inherits input taint unconditionally.
    """
    rank = {"clean": 0, "external": 1, "mixed": 2}
    inherited = "clean"
    for inp in hop_inputs:
        if rank[inp["taint"]] > rank[inherited]:
            inherited = inp["taint"]

    # Detect the laundering signature: tainted inputs, but output shares
    # no lexical overlap with any tainted source. That is exactly the
    # condition under which a substring tracker would wrongly clear.
    tainted_sources = [i["content"] for i in hop_inputs if i["taint"] != "clean"]
    if inherited != "clean" and tainted_sources:
        overlap = any(
            _token_overlap(hop_output, src) > 0.0 for src in tainted_sources
        )
        if not overlap:
            # Paraphrase laundering suspected. Do NOT clear taint.
            return {"taint": inherited, "laundering_suspected": True}

    return {"taint": inherited, "laundering_suspected": False}


def route_to_sink(hop_output: str, taint_result: dict, sink_is_privileged: bool) -> str:
    if taint_result["taint"] != "clean" and sink_is_privileged:
        if taint_result["laundering_suspected"]:
            raise TaintLaunderingError(
                "Privileged sink reachable from paraphrased tainted content; "
                "strip to schema or require human approval before dispatch."
            )
        raise TaintLaunderingError(
            "Privileged sink reachable from tainted content; gate required."
        )
    return "dispatched"


def _token_overlap(a: str, b: str) -> float:
    ta, tb = set(a.lower().split()), set(b.lower().split())
    if not ta or not tb:
        return 0.0
    return len(ta & tb) / len(ta | tb)
