# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-provenance-token-before-re-planning-and-why-transitive-taint-closure-across-tool-call-graphs-f.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-provenance-token-before-re-planning-and-why-transitive-taint-closure-across-tool-call-graphs-f.warrant.json
# Markdown SHA-256:   1c1e085c5219701eee1faf29b0baf541fc57641a03a6b5c83855073388f76bb3
# Code AST SHA-256:   2c8cca9f0af08a29facb4926c615cec72835dded8dcd5ae405d8b56f2b3b2e8a
# Verified Classes:   TaintClosureViolation, Value
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class TaintClosureViolation(RuntimeError):
    """Raised when an effector argument carries UNTRUSTED provenance at any depth."""
    pass

@dataclass
class Value:
    content: str
    taint: str                      # "CLEAN" | "UNTRUSTED"
    provenance: list = field(default_factory=list)  # list of origin ids, root-first

    def derive(self, new_content: str, transform: str, sanitizer_clears: bool = False) -> "Value":
        # A derived value inherits provenance unless a registered sanitizer cut the path.
        if sanitizer_clears:
            return Value(new_content, "CLEAN", [])
        # Monotone: taint is UNTRUSTED if any ancestor is UNTRUSTED.
        inherited = "UNTRUSTED" if self.taint == "UNTRUSTED" else "CLEAN"
        return Value(new_content, inherited, self.provenance + [transform])

def guard_effector_call(arg: Value, sink: str) -> None:
    # The check is on provenance DEPTH, not the immediate label.
    if arg.taint == "UNTRUSTED" or any(p.startswith("fetch_doc") for p in arg.provenance):
        raise TaintClosureViolation(
            f"effector '{sink}' argument carries untrusted provenance at depth "
            f"{len(arg.provenance)}: {arg.provenance}. Quarantine and re-plan."
        )

def run_graph(fetch_doc, extract_entities, send_message, doc_id: str):
    hop1 = fetch_doc(doc_id)                      # Value(taint=UNTRUSTED, provenance=[fetch_doc:...])
    hop2 = hop1.derive(extract_entities(hop1.content), "extract_entities")  # inherits UNTRUSTED
    # Naive runtime would have labeled hop2 CLEAN because extract_entities is "trusted".
    # Correct runtime keeps provenance and fails closed here:
    guard_effector_call(hop2, "send_message")
    return send_message(hop2.content)
