# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-arguments-as-tainted-after-a-prompt-injection-boundary-crossing-and-how-does-taint-laundering-throu.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-arguments-as-tainted-after-a-prompt-injection-boundary-crossing-and-how-does-taint-laundering-throu.warrant.json
# Markdown SHA-256:   4a307803780bfd7d3659b0c8f28769c9d4ffaf60a392fe8b56094ca4e34a092b
# Code AST SHA-256:   ea589567ab728939c082ce7d88a1f600bfe17f0ed4dc67c06b9f644ae528ddff
# Verified Classes:   TaintLaunderingError, Provenance, ContextSegment, ToolCallArgument
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a tool-call argument is constructed from sanitized-but-tainted provenance."""
    pass


class Provenance(Enum):
    TRUSTED = "trusted"
    EXTERNAL = "external"


@dataclass(frozen=True)
class ContextSegment:
    seg_id: str
    provenance: Provenance
    content_risk: str          # set by sanitizer; does NOT affect provenance
    provenance_tainted: bool   # immutable except via declassification


@dataclass
class ToolCallArgument:
    name: str
    value_hash: str
    derivation_set: FrozenSet[str]  # seg_ids attended during generation


def construct_argument(
    arg: ToolCallArgument,
    context: dict[str, ContextSegment],
    declassified_hashes: FrozenSet[str],
) -> ToolCallArgument:
    """Enforce monotonic taint propagation across model-mediated transforms.

    Sanitizer labels (content_risk) are deliberately ignored here: a segment
    marked content_risk='low' but provenance_tainted=True still taints any
    argument whose derivation set includes it. Only an exact-match
    declassification on the final argument value clears taint.
    """
    if arg.value_hash in declassified_hashes:
        return arg  # explicit declassification bound to final value

    for seg_id in arg.derivation_set:
        seg = context.get(seg_id)
        if seg is None:
            raise TaintLaunderingError(
                f"argument {arg.name!r} derives from unknown segment {seg_id!r}; "
                f"derivation set incomplete — cannot certify provenance"
            )
        if seg.provenance is Provenance.EXTERNAL and seg.provenance_tainted:
            raise TaintLaunderingError(
                f"argument {arg.name!r} derives from tainted external segment "
                f"{seg_id!r} (content_risk={seg.content_risk!r} ignored). "
                f"Sanitization does not clear provenance; require declassification "
                f"on value hash {arg.value_hash!r}."
            )
    return arg


# Reproduces the observed failure: sanitizer cleared the label, model
# paraphrased the intent into a fresh argument, provenance was lost.
ctx = {
    "doc:appendix": ContextSegment(
        seg_id="doc:appendix",
        provenance=Provenance.EXTERNAL,
        content_risk="low",          # sanitizer said clean
        provenance_tainted=True,     # but provenance is still external
    ),
}
arg = ToolCallArgument(
    name="send_email",
    value_hash="sha256:9f2c...",
    derivation_set=frozenset({"doc:appendix"}),
)

construct_argument(arg, ctx, declassified_hashes=frozenset())
# -> raises TaintLaunderingError, blocking the egress call
