# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-tool-call-argument-from-a-tainted-retrieval-chunk-after-sanitization-has-already-passed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-tool-call-argument-from-a-tainted-retrieval-chunk-after-sanitization-has-already-passed.warrant.json
# Markdown SHA-256:   3d61dafaba97bfc7b6ef0c23d520c6e85e377acbf24372c2aca34cce8018987f
# Code AST SHA-256:   2c691ec22ebcfeace819bab1c7b277e7e5d99828251a93580691ebe486d3bafe
# Verified Classes:   TaintLaunderingError, Chunk, Referent, Artifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a tool-call argument resolves through a tainted provenance edge
    that the egress span-sanitizer did not see because the argument was paraphrased."""
    pass


@dataclass
class Chunk:
    chunk_id: str
    source: str
    taint: str  # "none" | "untrusted_user_content" | ...
    text: str


@dataclass
class Referent:
    """An entity (URL, account id, handle) and the chunk that introduced it."""
    value: str
    introduced_by: str  # chunk_id


@dataclass
class Artifact:
    """Agent-authored text plus the referents it depends on and the edges it logged."""
    artifact_id: str
    text: str
    referents: list[Referent] = field(default_factory=list)
    resolved_edges: list[tuple[str, str]] = field(default_factory=list)  # (referent_value, chunk_id)


def egress_sanitize(
    argument: dict,
    artifact: Artifact,
    chunks: dict[str, Chunk],
    span_blocklist: set[str],
) -> None:
    """Egress check. Span-matching alone is insufficient; we also walk the
    referent dependency closure. Fails closed on any unlogged resolution."""
    # Layer 1: verbatim span check (the check that passed in the observed failure).
    for value in argument.values():
        if isinstance(value, str):
            for bad in span_blocklist:
                if bad in value:
                    raise TaintLaunderingError(
                        f"verbatim tainted span {bad!r} in argument"
                    )

    # Layer 2: referent closure. Every entity in the argument must trace to a
    # chunk, and that chunk's taint governs the call.
    for value in argument.values():
        if not isinstance(value, str):
            continue
        introducing = [
            r.introduced_by for r in artifact.referents if r.value in value
        ]
        if not introducing:
            # Argument contains an entity with no recorded provenance edge.
            # This is the paraphrased-referent case: the model resolved a
            # referent without logging it. Fail closed.
            raise TaintLaunderingError(
                f"unprovenanced entity in argument value {value!r}; "
                f"cannot establish taint closure — refusing call"
            )
        for chunk_id in introducing:
            chunk = chunks.get(chunk_id)
            if chunk is None:
                raise TaintLaunderingError(
                    f"provenance edge points to unknown chunk {chunk_id!r}"
                )
            if chunk.taint != "none":
                raise TaintLaunderingError(
                    f"argument value {value!r} resolves through tainted chunk "
                    f"{chunk_id!r} (taint={chunk.taint!r}); "
                    f"paraphrase does not launder provenance"
                )


def file_ticket(
    ticket_body: str,
    refund_target: str,
    artifact: Artifact,
    chunks: dict[str, Chunk],
) -> None:
    blocklist = {"acct-verify.example.net"}
    argument = {"ticket_body": ticket_body, "refund_target": refund_target}
    # In the observed failure, artifact.referents was empty (the summarizer
    # stripped the URL to "the verification portal" without logging an edge),
    # so Layer 2 fires here instead of passing silently.
    egress_sanitize(argument, artifact, chunks, blocklist)
    # ... dispatch to tool ...
    raise TaintLaunderingError(
        "unreachable: egress_sanitize should have rejected this call"
    )
