# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-through-a-provenance-label-it-never-re-derives-at-the-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-through-a-provenance-label-it-never-re-derives-at-the-tool-boundary.warrant.json
# Markdown SHA-256:   007fa73c5fcdb0f40e56940f507a180239cb354caeb3ba20af0e3d2ea551a982
# Code AST SHA-256:   b10e3907585b8b894e212abf6134e073033336051ac0519250f30ae8fd90b5fe
# Verified Classes:   ProvenanceMonotonicityError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceMonotonicityError(RuntimeError):
    """Raised when a derived value's taint is lower than an ancestor's."""
    pass


# Trust lattice: higher rank == more tainted. Join = max rank.
_TAINT_RANK = {
    "trusted:user": 0,
    "tool:derived": 1,
    "untrusted:web": 2,
    "untrusted:injected": 3,
}


@dataclass(frozen=True)
class Span:
    span_id: str
    label: str
    ancestors: FrozenSet[str] = field(default_factory=frozenset)


def join_labels(*labels: str) -> str:
    if not labels:
        raise ProvenanceMonotonicityError("cannot join empty provenance set")
    return max(labels, key=lambda l: _TAINT_RANK[l])


def derive_tool_result(
    tool_name: str,
    intrinsic_taint: str,
    arg_spans: list[Span],
    result_span_id: str,
) -> Span:
    """
    Compute the provenance of a tool result as the join of:
      - the intrinsic taint declared by the callee (e.g. fetch_url -> untrusted:web)
      - the labels of every span that materially influenced the call arguments
    A tool may only ADD taint; it may never reduce it.
    """
    if not arg_spans:
        # A tool call with no provenance-bearing arguments is itself suspicious:
        # the argument was synthesized from context the runtime failed to track.
        raise ProvenanceMonotonicityError(
            f"tool {tool_name!r} called with no tracked argument provenance; "
            "refusing to assign a clean label to an untracked derivation"
        )

    input_label = join_labels(*(s.label for s in arg_spans))
    computed = join_labels(input_label, intrinsic_taint)

    # Monotonicity check: computed must be >= every ancestor's label.
    for s in arg_spans:
        if _TAINT_RANK[computed] < _TAINT_RANK[s.label]:
            raise ProvenanceMonotonicityError(
                f"label laundering at tool {tool_name!r}: "
                f"result label {computed!r} is less tainted than ancestor "
                f"span {s.span_id!r} ({s.label!r})"
            )

    ancestors = frozenset(
        {s.span_id for s in arg_spans}
        | {a for s in arg_spans for a in s.ancestors}
    )
    return Span(span_id=result_span_id, label=computed, ancestors=ancestors)


def gate_side_effect(sink: str, arg_spans: list[Span], forbidden: str = "untrusted:web") -> None:
    """Reject side-effecting calls whose arguments trace to forbidden taint."""
    for s in arg_spans:
        chain = {s.label}
        # ancestors are span_ids; in a real runtime we'd resolve their labels.
        # Here we conservatively reject if the direct label is forbidden.
        if _TAINT_RANK[s.label] >= _TAINT_RANK[forbidden]:
            raise ProvenanceMonotonicityError(
                f"sink {sink!r} blocked: argument span {s.span_id!r} "
                f"carries taint {s.label!r} >= {forbidden!r}"
            )
