# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-mcp-output-envelopes-during-tool-sandbox-quarantine.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-mcp-output-envelopes-during-tool-sandbox-quarantine.warrant.json
# Markdown SHA-256:   8bd06d2927ca5144810ad751b0cf5f1a4fac6d5e136e7a33458e56579cebd90c
# Code AST SHA-256:   502ad233a9d661195b841dfbf910ff5ffb8ee03ea792b1b73339ca1a4a319eb4
# Verified Classes:   TaintLaunderingError, ProvenanceNode, OutputEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when an output's provenance closure reaches an untrusted node
    through a path the quarantine decision did not account for."""


@dataclass(frozen=True)
class ProvenanceNode:
    node_id: str
    trusted: bool
    # References are resolved lazily; they are NOT part of the envelope's
    # asserted trust and must be walked before any merge decision.
    refs: tuple[str, ...] = field(default_factory=tuple)


@dataclass(frozen=True)
class OutputEnvelope:
    node_id: str
    asserted_taint: str | None  # server-supplied; never authoritative
    payload: dict[str, Any]


def provenance_closure(
    root: str, graph: dict[str, ProvenanceNode]
) -> set[str]:
    seen: set[str] = set()
    stack = [root]
    while stack:
        nid = stack.pop()
        if nid in seen:
            continue
        seen.add(nid)
        node = graph.get(nid)
        if node is None:
            # Unresolvable reference: fail closed by treating as untrusted.
            continue
        stack.extend(node.refs)
    return seen


def assert_mergeable(
    envelope: OutputEnvelope, graph: dict[str, ProvenanceNode]
) -> None:
    """Gate a quarantined output before context merge.

    The invariant: taint is a function of the provenance closure, never of
    the envelope's asserted_taint field.
    """
    closure = provenance_closure(envelope.node_id, graph)
    untrusted = {
        nid for nid in closure if not graph.get(nid, ProvenanceNode(nid, False)).trusted
    }
    if untrusted:
        raise TaintLaunderingError(
            f"refusing to merge {envelope.node_id!r}: provenance closure "
            f"reaches untrusted nodes {sorted(untrusted)}; "
            f"asserted_taint={envelope.asserted_taint!r} is not authoritative"
        )
    if envelope.asserted_taint not in (None, "trusted"):
        # A server asserting a non-trusted label on a trusted-closure node is
        # a structural anomaly worth surfacing, not silently accepting.
        raise TaintLaunderingError(
            f"{envelope.node_id!r} asserts taint {envelope.asserted_taint!r} "
            f"but its provenance closure is trusted; re-derive before merge"
        )


# Example: the outer envelope looks clean, but a lazy reference reaches an
# untrusted node via a second server's resource.
_graph = {
    "outer": ProvenanceNode("outer", trusted=True, refs=("res://srv-b/42",)),
    "res://srv-b/42": ProvenanceNode("res://srv-b/42", trusted=False),
}
_env = OutputEnvelope(
    node_id="outer",
    asserted_taint="trusted",
    payload={"content": [{"type": "resource", "uri": "res://srv-b/42"}]},
)
assert_mergeable(_env, _graph)  # raises TaintLaunderingError
