# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-graph-taint-laundering-in-agent-context-assembly.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-graph-taint-laundering-in-agent-context-assembly.warrant.json
# Markdown SHA-256:   db27b0379ea82bc987f8e00f9eff076e847fe667f2fe38ae771a024e13d5f419
# Code AST SHA-256:   6a1d9f46a887dfad7bef1b5d0528ad9f9c83a00f14581db5d5cf2d11154bc3f9
# Verified Classes:   Node, TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Taint = Literal["TRUSTED", "UNTRUSTED"]

# Taint lattice: UNTRUSTED is the top (most restrictive). join is the LUB.
_RANK = {"TRUSTED": 0, "UNTRUSTED": 1}

def join(a: Taint, b: Taint) -> Taint:
    return a if _RANK[a] >= _RANK[b] else b

@dataclass
class Node:
    id: str
    taint: Taint
    role: str = "leaf"           # declared role, e.g. "summary"
    ancestors: list[str] = field(default_factory=list)

class TaintLaunderingError(RuntimeError):
    """Raised when a derived node's taint is weaker than the join of its ancestors,
    or when the auditor prunes an instruction-bearing edge by role."""

def build_derived_node(node_id: str, ancestors: list[Node],
                       declared_role: str) -> Node:
    # Invariant: derived taint MUST be the join over ALL ancestors.
    expected = "TRUSTED"
    for a in ancestors:
        expected = join(expected, a.taint)
    node = Node(id=node_id, taint=expected, role=declared_role,
                ancestors=[a.id for a in ancestors])
    return node

def audit_generation(gen: Node, graph: dict[str, Node],
                     pruned_by_role: bool) -> None:
    if pruned_by_role:
        raise TaintLaunderingError(
            f"auditor pruned edges into {gen.id} by role; "
            f"role-based pruning severs taint paths and is unsound"
        )
    # Walk ALL ancestors, no role filter.
    stack = list(gen.ancestors)
    seen: set[str] = set()
    while stack:
        nid = stack.pop()
        if nid in seen:
            continue
        seen.add(nid)
        n = graph[nid]
        if n.role == "summary" and n.taint == "TRUSTED" and any(
            graph[a].taint == "UNTRUSTED" for a in n.ancestors
        ):
            raise TaintLaunderingError(
                f"node {nid} declares role=summary, taint=TRUSTED, but has "
                f"UNTRUSTED ancestor(s) {n.ancestors}; taint was laundered "
                f"by treating derivation as sanitization"
            )
        stack.extend(n.ancestors)

# --- Reproduce the observed failure and show the guardrail catching it ---
c1 = Node("C1", "TRUSTED", role="retrieved_chunk")
c2 = Node("C2", "UNTRUSTED", role="retrieved_chunk")

# Vulnerable builder: inherits from first ancestor only.
s1_bad = Node("S1", c1.taint, role="summary", ancestors=["C1", "C2"])
graph = {"C1": c1, "C2": c2, "S1": s1_bad}
gen_bad = Node("G", s1_bad.taint, role="generation", ancestors=["S1"])
graph["G"] = gen_bad

# Guardrail builder: join over all ancestors.
s1_good = build_derived_node("S1", [c1, c2], declared_role="summary")
assert s1_good.taint == "UNTRUSTED", "join must propagate UNTRUSTED"

try:
    audit_generation(gen_bad, graph, pruned_by_role=True)
except TaintLaunderingError as e:
    print(f"blocked (role-pruned audit): {e}")

try:
    audit_generation(gen_bad, graph, pruned_by_role=False)
except TaintLaunderingError as e:
    print(f"blocked (laundering detected): {e}")
