# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-through-derived-tool-call-arguments-rather-than-only-through-retrieved-context.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-through-derived-tool-call-arguments-rather-than-only-through-retrieved-context.warrant.json
# Markdown SHA-256:   95f49c895cb658b4babbe3f5f843098fb9d5146ba26a6eb41a3f92be2c74266f
# Code AST SHA-256:   952d30fdca1c8b673483caf837654548cf2657a6638edbb27068144a7f583a26
# Verified Classes:   TaintProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintProvenanceError(RuntimeError):
    """Raised when a tool call carries an argument derived from tainted content."""


# Spans are tagged at ingestion. Taint is a set of span ids.
TAINTED_SPANS: set[str] = set()


def derive_argument(span_id: str, transform: str, value: str) -> dict:
    """Compute a tool argument from a context span.

    The derived value inherits the source span's taint status regardless of
    how many generation hops or transformations separate it from the source.
    """
    return {
        "value": value,
        "source_span": span_id,
        "transform": transform,
        "tainted": span_id in TAINTED_SPANS,
    }


def validate_tool_call(tool: str, args: list[dict], schema_ok: bool) -> None:
    """Gate a tool call on argument provenance, not merely schema conformance.

    A call is clean only when it is schema-conformant AND no argument is
    taint-reachable. Schema conformance is necessary but not sufficient.
    """
    tainted_args = [a for a in args if a.get("tainted")]

    if tainted_args:
        sources = sorted({a["source_span"] for a in tainted_args})
        raise TaintProvenanceError(
            f"tool '{tool}' invoked with taint-reachable arguments "
            f"derived from spans {sources}; schema_ok={schema_ok}. "
            f"Route to restricted execution / confirmation."
        )

    if not schema_ok:
        raise TaintProvenanceError(
            f"tool '{tool}' arguments failed schema validation; refusing execution."
        )


def handle_create_ticket(summary: dict, assignee: dict, description: dict) -> None:
    # assignee and description were derived from a retrieved document at turn 3.
    validate_tool_call(
        tool="create_ticket",
        args=[summary, assignee, description],
        schema_ok=True,  # enum and string checks pass; provenance still fails
    )
