# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-tainted-label-has-been-laundered-through-a-semantically-equivalent-paraphrase.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-tainted-label-has-been-laundered-through-a-semantically-equivalent-paraphrase.warrant.json
# Markdown SHA-256:   ba4a9cd4ed1dbd25af5f85fbd179048ce803c14ffee9ab2a4cccce5283817837
# Code AST SHA-256:   263207b2a6309cd5b4754f138e26fc2ae9aa79f7bb40b9098cc3be5d3744aacd
# Verified Classes:   TrustLevel, TaintLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum


class TrustLevel(IntEnum):
    UNTRUSTED = 0
    ADVISORY = 1
    INTERNAL = 2
    TRUSTED = 3


class TaintLaunderingError(RuntimeError):
    """Raised when a span's trust class cannot be justified by its provenance DAG."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    trust: TrustLevel
    parents: tuple[str, ...] = field(default_factory=tuple)
    generative_hop: bool = False


def join_trust(parents: list[Span]) -> TrustLevel:
    if not parents:
        raise TaintLaunderingError("span has no provenance parents; cannot establish trust")
    return TrustLevel(min(p.trust for p in parents))


def resolve_effective_trust(span: Span, registry: dict[str, Span]) -> TrustLevel:
    """Walk the provenance DAG and return the minimum trust along every path.

    Fails closed if any ancestor is missing from the registry, because a
    missing ancestor is indistinguishable from a laundered one.
    """
    seen: set[str] = set()
    stack: list[Span] = [span]
    effective = span.trust
    while stack:
        current = stack.pop()
        if current.span_id in seen:
            continue
        seen.add(current.span_id)
        effective = TrustLevel(min(effective, current.trust))
        for parent_id in current.parents:
            parent = registry.get(parent_id)
            if parent is None:
                raise TaintLaunderingError(
                    f"provenance hole: span {current.span_id!r} references "
                    f"unknown parent {parent_id!r}; refusing to authorize"
                )
            stack.append(parent)
    return effective


def authorize_tool_call(
    span: Span,
    registry: dict[str, Span],
    required: TrustLevel,
    channel_trust: TrustLevel,
) -> None:
    """Authorize a tool call only if content provenance meets the bar.

    The channel's own trust class is deliberately ignored for authorization;
    it may only ever lower the effective trust, never raise it.
    """
    effective = resolve_effective_trust(span, registry)
    effective = TrustLevel(min(effective, channel_trust))
    if effective < required:
        raise TaintLaunderingError(
            f"tool call on span {span.span_id!r} rejected: effective trust "
            f"{effective.name} < required {required.name}; channel trust "
            f"{channel_trust.name} does not upgrade content provenance"
        )
