# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-from-a-retrieval-hit-into-a-tool-argument-and-when-is-that-propagation-a-false-positive.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-from-a-retrieval-hit-into-a-tool-argument-and-when-is-that-propagation-a-false-positive.warrant.json
# Markdown SHA-256:   db073617b4d669b95ad8b9fca24a571677ca9bf9a4136a824a21b619b6c0453c
# Code AST SHA-256:   c5895979634fa21ed6ca440bbbb30c48e738d931e941b76791f237fddc431821
# Verified Classes:   TaintPropagationError, Label, Span, ToolArgument
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class TaintPropagationError(RuntimeError):
    """Raised when a taint edge cannot be classified under the declared policy."""


class Label(str, Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"
    DERIVED = "derived"
    CONTEXT = "context"


@dataclass(frozen=True)
class Span:
    span_id: str
    label: Label
    text: str


@dataclass
class ToolArgument:
    name: str
    value: str
    fields: dict[str, Label] = field(default_factory=dict)


MIN_SUBSTRING_BYTES = 24
MIN_SUBSTRING_TOKENS = 8
RETIRE_AFTER_STEPS = 3


def _verbatim_overlap(arg: str, untrusted: str) -> bool:
    if len(arg.encode()) >= MIN_SUBSTRING_BYTES and arg in untrusted:
        return True
    tokens = arg.split()
    if len(tokens) >= MIN_SUBSTRING_TOKENS:
        window = " ".join(tokens[:MIN_SUBSTRING_TOKENS])
        if window in untrusted:
            return True
    return False


def classify_edge(
    arg: ToolArgument,
    sources: list[Span],
    *,
    derived_from: set[str] = frozenset(),
    branch_determinant: str | None = None,
    extraction_verified: bool = False,
) -> dict[str, Label]:
    """Return per-field provenance labels for a tool argument.

    Raises TaintPropagationError when a source is untrusted and the edge
    cannot be established (opaque argument, unverified derivation).
    """
    labels: dict[str, Label] = {}

    for name, value in arg.fields.items():
        field_value = value if isinstance(value, str) else str(value)
        label = Label.TRUSTED

        for src in sources:
            if src.label is Label.TRUSTED:
                continue
            if src.span_id in derived_from and not extraction_verified:
                label = Label.DERIVED
                continue
            if _verbatim_overlap(field_value, src.text):
                label = Label.UNTRUSTED
                continue
            if branch_determinant == src.span_id:
                label = Label.UNTRUSTED

        if label is Label.DERIVED and not extraction_verified:
            labels[name] = Label.DERIVED
        else:
            labels[name] = label

    if not arg.fields:
        raise TaintPropagationError(
            f"argument {arg.name!r} has no inspectable fields; "
            "cannot establish dataflow edge — fall back to context taint"
        )

    return labels


def should_block(labels: dict[str, Label], *, read_only: bool) -> bool:
    worst = Label.TRUSTED
    order = [Label.TRUSTED, Label.CONTEXT, Label.DERIVED, Label.UNTRUSTED]
    for label in labels.values():
        if order.index(label) > order.index(worst):
            worst = label
    if worst is Label.UNTRUSTED:
        return True
    if worst is Label.DERIVED and not read_only:
        return True
    return False


def retire_stale(labels: dict[str, Label], steps_since_seen: int) -> dict[str, Label]:
    if steps_since_seen >= RETIRE_AFTER_STEPS:
        return {k: Label.TRUSTED for k in labels}
    return labels


def enforce(arg: ToolArgument, sources: list[Span], *, read_only: bool, **kw) -> dict[str, Label]:
    labels = classify_edge(arg, sources, **kw)
    if should_block(labels, read_only=read_only):
        raise TaintPropagationError(
            f"tool argument {arg.name!r} blocked under labels {labels}"
        )
    return labels
