# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-scope-collapse-during-injection-propagated-tool-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-scope-collapse-during-injection-propagated-tool-authorization.warrant.json
# Markdown SHA-256:   0a1d224413642edf68f97d5753e52bdac3161016ba7e70bb8ccee8fad2887b6d
# Code AST SHA-256:   fab14fd4bea7450aed483936ae07b1da2b86310df3996b9e862617651596a7f5
# Verified Classes:   TaintScopeCollapse, ProvenanceNode, Tool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintScopeCollapse(RuntimeError):
    """Raised when a side-effecting tool call's argument traces to an untrusted
    provenance root without an explicit, warranted de-taint on the derivation path."""


class ProvenanceNode:
    def __init__(self, value, taint, parents=None, is_de_taint=False, warrant=None):
        self.value = value
        self.taint = taint                      # "trusted" | "untrusted:<source>"
        self.parents = parents or []            # derivation edges, NOT value matches
        self.is_de_taint = is_de_taint
        self.warrant = warrant                  # required if is_de_taint

    def derivation_roots(self, seen=None):
        seen = seen or set()
        if id(self) in seen:
            return set()
        seen.add(id(self))
        if not self.parents:
            return {self}
        roots = set()
        for p in self.parents:
            roots |= p.derivation_roots(seen)
        return roots


def authorize_side_effect(tool, args, arg_nodes):
    """Gate a persistent-write tool on the derivation graph, not the argument string."""
    if tool.side_effect != "persistent":
        return True

    for name, node in arg_nodes.items():
        for root in node.derivation_roots():
            if root.taint == "trusted":
                continue
            # Untrusted root reaches this argument. Walk the path; a valid
            # de-taint node with a warrant must sit on EVERY path from root.
            if not _warranted_de_taint_on_all_paths(root, node):
                raise TaintScopeCollapse(
                    f"tool={tool.name!r} arg={name!r} value={node.value!r} "
                    f"traces to untrusted root {root.taint!r} ({root.value!r}) "
                    f"with no warranted de-taint on the derivation path. "
                    f"Abstraction is not de-taint; scope collapsed."
                )
    return True


def _warranted_de_taint_on_all_paths(root, node, seen=None):
    seen = seen or set()
    if id(node) in seen:
        return False
    seen.add(id(node))
    if node is root:
        return False  # reached root without crossing a warrant
    if node.is_de_taint and node.warrant:
        return True
    # Every parent path must independently be warranted.
    if not node.parents:
        return False
    return all(_warranted_de_taint_on_all_paths(root, p, seen) for p in node.parents)


# --- Trace that triggers the guard ---
fetched = ProvenanceNode("Contact: D. Reyes <dana@evil.example>", "untrusted:web")
plan = ProvenanceNode("set CRM email to dana@evil.example", "untrusted:web",
                      parents=[fetched])                 # summarization, NOT de-taint
arg = ProvenanceNode("dana@evil.example", "clean",       # laundered label
                     parents=[plan])

class Tool:
    name = "crm.update_contact"
    side_effect = "persistent"

authorize_side_effect(Tool(), {"email": arg.value}, {"email": arg})
