# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-conjunctive-tool-call-recombination-across-a-quarantine-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-conjunctive-tool-call-recombination-across-a-quarantine-boundary.warrant.json
# Markdown SHA-256:   fb55ea89cd0ca9ab98e5dc489e0c56fe08371bda9307db68f3eb031b80d7e235
# Code AST SHA-256:   67b51bddb09f0f2879bdb56d682d536c769d9b442a457c990f6f5cffb6f7ad8f
# Verified Classes:   TaintLaunderingError, Provenance, ToolResult, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a mutating call is admitted despite conjunctive taint."""


@dataclass
class Provenance:
    roots: frozenset  # provenance root ids, e.g. {"operator:req_11", "quarantine:doc_7"}

    def intersects(self, quarantine: frozenset) -> bool:
        return bool(self.roots & quarantine)


@dataclass
class ToolResult:
    value: object
    provenance: Provenance


@dataclass
class ToolCall:
    tool: str
    mutating: bool
    args: dict
    arg_provenance: dict          # arg name -> Provenance
    rationale_provenance: Provenance
    declassification_warrant: Optional[dict] = None  # {"operator_root":..., "schema":{param: type}}


def derivation_closure(arg_provenance: dict) -> Provenance:
    roots = frozenset()
    for p in arg_provenance.values():
        roots |= p.roots
    return Provenance(roots)


def warrant_is_valid(call: ToolCall) -> bool:
    w = call.declassification_warrant
    if not w:
        return False
    # Warrant must root in operator intent and must not authorize operation selection.
    if "operator_root" not in w["operator_root"]:
        return False
    allowed = w.get("schema", {})
    if "op" in allowed or "operation" in allowed:
        return False  # operation choice may never be declassified from quarantine
    for arg in call.args:
        if arg not in allowed:
            return False
        if allowed[arg] not in (str, int):
            return False
    return True


def dispatch(call: ToolCall, active_quarantine: frozenset) -> ToolResult:
    if call.mutating:
        arg_taint = derivation_closure(call.arg_provenance)
        rationale_taint = call.rationale_provenance
        conjunctively_tainted = (
            arg_taint.intersects(active_quarantine)
            or rationale_taint.intersects(active_quarantine)
        )
        if conjunctively_tainted and not warrant_is_valid(call):
            raise TaintLaunderingError(
                f"mutating call {call.tool} refused: conjunctive taint "
                f"(args={sorted(arg_taint.roots)}, rationale={sorted(rationale_taint.roots)})"
            )
    return ToolResult(value=f"executed:{call.tool}", provenance=Provenance(frozenset({"tool:" + call.tool})))


# Reproduction of the observed laundering chain.
q = frozenset({"quarantine:doc_7"})
op = Provenance(frozenset({"operator:req_11"}))

# Step 1: read-only search steered by tainted query -> output inherits taint.
r1 = ToolResult("res_8841", Provenance(op.roots | q))
# Step 2: describe with laundered id -> still tainted under transitive rule.
call = ToolCall(
    tool="invoke_operation",
    mutating=True,
    args={"resource": "res_8841", "op": "rotate_credentials"},
    arg_provenance={"resource": r1.provenance, "op": op},
    rationale_provenance=Provenance(op.roots | q),  # operation chosen in tainted context
)
try:
    dispatch(call, q)
except TaintLaunderingError as e:
    print("BLOCKED:", e)
    raise
