# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-taint-cleared-argument-has-been-re-derived-from-untrusted-memory-rather-than-user-input.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-taint-cleared-argument-has-been-re-derived-from-untrusted-memory-rather-than-user-input.warrant.json
# Markdown SHA-256:   4e4aa8d4d496adaa6ab8d2c684923ffcbf2af29f9495c96b3afae698a1ba48cf
# Code AST SHA-256:   8294f15d4a02ef08cea12ee65796b76a83b38ee4e23fb02496655064aa819164
# Verified Classes:   TaintLaunderingError, Region, ContextSpan, ToolCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class TaintLaunderingError(RuntimeError):
    """Raised when a sensitive-sink argument cannot be attributed to a
    user-authority span in the model's context, i.e. it was re-derived
    from tainted context rather than copied from a labeled source."""


class Region(Enum):
    USER = "user"            # direct user message: highest authority
    USER_RETRIEVED = "user_retrieved"   # user-authored, but retrieved
    THIRD_PARTY = "third_party"         # KB chunks, tool output, memory


@dataclass
class ContextSpan:
    span_id: str
    region: Region
    text: str


@dataclass
class ToolCall:
    sink: str
    args: dict
    # model-emitted citation: arg name -> span_id it claims to derive from
    citations: dict = field(default_factory=dict)


SENSITIVE_SINKS = {"send_email", "execute_sql", "write_file"}


def _span_authority(span: ContextSpan) -> int:
    return {
        Region.USER: 3,
        Region.USER_RETRIEVED: 2,
        Region.THIRD_PARTY: 1,
    }[span.region]


def gate_tool_call(call: ToolCall, spans: dict[str, ContextSpan],
                   tainted_span_present: bool) -> None:
    """Enforce: every sensitive-sink argument must cite a user-authority
    span, and the citation must actually contain the argument value.
    Ablation flag signals whether a tainted span was in context; if so,
    an uncited argument is presumed laundered."""
    if call.sink not in SENSITIVE_SINKS:
        return

    for arg_name, value in call.args.items():
        span_id = call.citations.get(arg_name)
        if span_id is None:
            if tainted_span_present:
                raise TaintLaunderingError(
                    f"argument {arg_name!r} on sink {call.sink!r} has no "
                    f"citation while tainted context is present; presumed "
                    f"re-derived from untrusted memory"
                )
            continue

        span = spans.get(span_id)
        if span is None:
            raise TaintLaunderingError(
                f"argument {arg_name!r} cites unknown span {span_id!r}"
            )
        if _span_authority(span) < _span_authority(
                ContextSpan("_", Region.USER_RETRIEVED, "")):
            raise TaintLaunderingError(
                f"argument {arg_name!r} cites third-party span {span_id!r}; "
                f"third-party content cannot authorize a sensitive sink"
            )
        # Citation must be substantive: the cited span must actually
        # contain the value, else the model fabricated the citation.
        if value not in span.text:
            raise TaintLaunderingError(
                f"argument {arg_name!r} cites span {span_id!r} which does "
                f"not contain the value; citation is fabricated"
            )


def enforce(call: ToolCall, spans: dict[str, ContextSpan],
            ablation_diverged: bool) -> None:
    """Wrapper: ablation_diverged=True means removing tainted context
    changed the emitted argument -> it was causally tainted-derived."""
    if ablation_diverged:
        raise TaintLaunderingError(
            f"sink {call.sink!r}: argument changed under tainted-context "
            f"ablation; refusing emission and requiring user confirmation"
        )
    gate_tool_call(call, spans, tainted_span_present=True)
