# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-tool-output-as-tainted-egress-rather-than-trusted-instruction-and-how-does-capability-scoped-routing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-tool-output-as-tainted-egress-rather-than-trusted-instruction-and-how-does-capability-scoped-routing.warrant.json
# Markdown SHA-256:   2ad889831a5c05e67fec36b46b799e6e2811e90f086a9b7e3fca547fdb6f23b2
# Code AST SHA-256:   e97457930f2bf30f510726cb44a46f761771f6f032b5eaa091c7e0f90bfcb47a
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is invoked with arguments whose
    lineage includes untrusted tool output, regardless of transport taint."""


PRIVILEGED_SINKS = {"forward_to", "write_ledger", "delete", "send_external"}


def guard_sink_call(tool_name: str, args: dict, lineage: dict, transport_taint: bool) -> None:
    # Lineage is authoritative; transport_taint is advisory only and MUST NOT
    # be used to clear a tainted argument.
    if tool_name not in PRIVILEGED_SINKS:
        return

    tainted_args = [k for k, node in lineage.items() if node.get("taint") == 1]
    if tainted_args and not lineage.get("__declassified__", False):
        raise TaintLaunderingError(
            f"Privileged sink {tool_name!r} invoked with tainted args "
            f"{tainted_args}; transport_taint={transport_taint} ignored. "
            f"Requires explicit declassification before execution."
        )


def handle_peer_envelope(envelope: dict, executor_lineage: dict) -> None:
    # Merge peer payload lineage; do NOT trust envelope['taint'].
    for arg, node in envelope.get("payload_lineage", {}).items():
        executor_lineage[arg] = node
    guard_sink_call(
        envelope["proposed_tool"],
        envelope.get("args", {}),
        executor_lineage,
        transport_taint=envelope.get("taint", False),
    )
