# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survival-across-multi-hop-tool-invocations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survival-across-multi-hop-tool-invocations.warrant.json
# Markdown SHA-256:   695912774d27cb49590dddf964ba18bd50abd2945015a65e4388f1ff204a4b41
# Code AST SHA-256:   0d9660eb0e7d4f8b672d95f8971d5697f21c77cf5e57410d9ddb2efcfe60e360
# Verified Classes:   TaintLaunderingError, Payload
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

UNTRUSTED = "untrusted"
DERIVED = "derived"
TRUSTED = "trusted"
PRIVILEGED_SINKS = {"write_file", "exec", "http_post", "a2a_send", "exfiltrate"}


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is invoked with untrusted lineage that was laundered through derivation."""
    pass


@dataclass
class Payload:
    content: str
    taint: FrozenSet[str] = field(default_factory=frozenset)
    lineage: tuple = ()


def derive(inputs: list[Payload], output_content: str) -> Payload:
    # Join taints across all inputs; never collapse to a flat enum.
    joined = frozenset().union(*(p.taint for p in inputs))
    # Directive detection: imperative directed at the agent survives paraphrase.
    directive_markers = ("you must", "before doing", "reply only", "ignore prior", "should first")
    has_directive = any(m in output_content.lower() for m in directive_markers)
    taint = set(joined)
    if has_directive and UNTRUSTED in joined:
        taint.add(DERIVED)  # taint_carry bit, survives re-serialization
    return Payload(output_content, frozenset(taint), tuple(id(p) for p in inputs))


def invoke_sink(sink: str, args: list[Payload]) -> None:
    if sink not in PRIVILEGED_SINKS:
        return
    join = frozenset().union(*(a.taint for a in args))
    if UNTRUSTED in join:
        raise TaintLaunderingError(
            f"sink '{sink}' invoked with untrusted lineage surviving {len(args)} derivation hops; "
            f"taint={sorted(join)}"
        )
