# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-prompt-injection-taint-break-at-the-tool-output-to-memory-write-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-prompt-injection-taint-break-at-the-tool-output-to-memory-write-seam.warrant.json
# Markdown SHA-256:   9ad4bd0177725b0dde74987b4f918d01820e203aee9d059847506b1c84c5a832
# Code AST SHA-256:   0a693af75f801e80695969bcf238303c4fdcddb9f3f3fcb7184675216e826cc2
# Verified Classes:   TaintAncestryError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintAncestryError(RuntimeError):
    """Raised when a value reaches a sink without a continuous derived_from chain
    to its original source, or when trust is redeclared instead of joined."""
    pass


TRUST_ORDER = {"external": 0, "tool": 1, "user": 2}  # min-join lattice


def resolve_sink_trust(value, ancestry_graph, sink):
    """
    value: dict with keys 'id', 'declared_trust', 'derived_from' (list of node ids)
    ancestry_graph: dict[node_id -> {'trust': str, 'derived_from': [ids]}]
    sink: str naming the effect class (e.g. 'policy_write', 'outbound_message')
    """
    # Walk ancestry; if any node lacks an edge or trust, fail closed.
    frontier = list(value.get("derived_from", []))
    if not frontier and value.get("declared_trust") != "user":
        # A non-user value with no ancestry is a laundering candidate.
        raise TaintAncestryError(
            f"sink={sink} value={value.get('id')} has no derived_from edge; "
            f"declared_trust={value.get('declared_trust')} cannot be accepted"
        )

    seen = set()
    trusts = [value.get("declared_trust", "external")]
    while frontier:
        node_id = frontier.pop()
        if node_id in seen:
            continue
        seen.add(node_id)
        node = ancestry_graph.get(node_id)
        if node is None:
            raise TaintAncestryError(
                f"sink={sink} ancestry node {node_id} missing from graph; "
                f"chain is broken and trust cannot be computed"
            )
        trust = node.get("trust")
        if trust not in TRUST_ORDER:
            raise TaintAncestryError(
                f"sink={sink} ancestry node {node_id} has unknown trust={trust!r}"
            )
        trusts.append(trust)
        frontier.extend(node.get("derived_from", []))

    joined = min(trusts, key=lambda t: TRUST_ORDER[t])
    return joined


def guarded_memory_write(value, ancestry_graph, sink="memory_write"):
    trust = resolve_sink_trust(value, ancestry_graph, sink)
    if sink == "policy_write" and trust == "external":
        raise TaintAncestryError(
            f"sink={sink} rejected: joined trust={trust} from external ancestry; "
            f"policy effects require trust >= tool"
        )
    return {"content": value.get("content"), "trust": trust}
