# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-tool-call-provenance-when-a-prompt-injected-subgoal-rewrites-its-own-causal-parents.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-tool-call-provenance-when-a-prompt-injected-subgoal-rewrites-its-own-causal-parents.warrant.json
# Markdown SHA-256:   f502c3850b42193ec2b070a3d55a48c9611aa8614fbb4e195539a8c6ae5db09c
# Code AST SHA-256:   18e3b0e7b04854c2e439a7520dbf1993c0dd4bf12904c29f2d00035c97424301
# Verified Classes:   TrustLabel, ContextSegment, ToolCall, ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TrustLabel(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass
class ContextSegment:
    node_id: str
    label: TrustLabel
    derived_from: list[str] = field(default_factory=list)


@dataclass
class ToolCall:
    call_id: str
    tool: str
    literal_args: dict
    dispatch_context: list[ContextSegment]
    agent_rationale_parents: list[str] = field(default_factory=list)


class ProvenanceLaunderingError(RuntimeError):
    """Raised when taint reachability would certify a call clean that was
    dispatched with an untrusted segment co-resident, or when an
    agent-authored rationale node is used as a causal parent."""


def compute_taint(call: ToolCall) -> bool:
    # Invariant: taint follows co-residency at dispatch, NOT data lineage.
    # Agent-authored rationale parents are excluded from the computation.
    if call.agent_rationale_parents:
        # Rationale may be displayed but never trusted as causal evidence.
        pass  # deliberately ignored for reachability

    for seg in call.dispatch_context:
        if seg.label is TrustLabel.UNTRUSTED:
            return True
        # Propagated labels through compaction must survive eviction.
        for parent in seg.derived_from:
            if parent.startswith("untrusted:"):
                return True
    return False


def certify_call(call: ToolCall) -> str:
    # Guard: a call with a literal argument and no trusted control parent
    # must still be evaluated against dispatch context. If the runtime
    # failed to capture dispatch_context, we cannot certify — fail closed.
    if not call.dispatch_context and call.literal_args:
        raise ProvenanceLaunderingError(
            f"call {call.call_id} has literal args but empty dispatch_context; "
            "cannot certify — provenance capture gap, fail closed"
        )
    if call.agent_rationale_parents and not call.dispatch_context:
        raise ProvenanceLaunderingError(
            f"call {call.call_id} relies solely on agent-authored rationale "
            "parents; retroactive grafting detected, refusing certification"
        )
    return "tainted" if compute_taint(call) else "clean"
