# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-span-whose-taint-provenance-is-ambiguous-rather-than-treat-it-as-clean.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-span-whose-taint-provenance-is-ambiguous-rather-than-treat-it-as-clean.warrant.json
# Markdown SHA-256:   b1dd654c35614d2910d0c683295b1ac2722b3582f018940d1c4e717f9711fd7e
# Code AST SHA-256:   749a6f2cc2ada6b0c214043009563c698a8997877a6e6886538c4669d3b4fcac
# Verified Classes:   Trust, ProvenanceLaunderingError, Span, TransformOutput
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class Trust(Enum):
    TRUSTED = 0
    AMBIGUOUS = 1
    TAINTED = 2

    def join(self, other: "Trust") -> "Trust":
        # least-trusted wins; AMBIGUOUS dominates TRUSTED, TAINTED dominates all
        return Trust(max(self.value, other.value))


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a transform output would be promoted above the join of its inputs
    without an attribution certificate that justifies the promotion."""


@dataclass
class Span:
    span_id: str
    trust: Trust
    text: str


@dataclass
class TransformOutput:
    output_id: str
    text: str
    input_ids: list[str]
    # None means the transform did not emit per-output attribution
    attribution: dict[str, list[str]] | None = None
    # True if the transform can synthesize content absent from any single input
    generative: bool = False


def join_inputs(spans: dict[str, Span], input_ids: Iterable[str]) -> Trust:
    result = Trust.TRUSTED
    for sid in input_ids:
        result = result.join(spans[sid].trust)
    return result


def label_transform_output(
    spans: dict[str, Span],
    out: TransformOutput,
    *,
    length_ratio_bound: float = 3.0,
) -> Trust:
    """Compute the only sound label for a transform output.

    Rules:
      - If the transform emitted per-output attribution, join over the
        inputs that actually contributed to each output region, and take the
        worst region. Exact, so no Ambiguous arises from attribution alone.
      - If attribution is missing and inputs are mixed-trust, the output is
        AMBIGUOUS unless the transform is generative AND the output exceeds
        the bounded ratio, in which case it is TAINTED (quarantine).
    """
    input_join = join_inputs(spans, out.input_ids)
    input_text_len = sum(len(spans[s].text) for s in out.input_ids)
    out_len = len(out.text)

    if out.attribution is not None:
        # exact join over contributing inputs per region
        region_trust = Trust.TRUSTED
        for contributors in out.attribution.values():
            region_trust = region_trust.join(join_inputs(spans, contributors))
        return region_trust.join(input_join) if input_join is Trust.TAINTED else region_trust

    # No attribution. If all inputs share a label, that label is sound.
    labels = {spans[s].trust for s in out.input_ids}
    if len(labels) == 1:
        return next(iter(labels))

    # Mixed-trust, no attribution: never promote above AMBIGUOUS.
    if out.generative and input_text_len > 0 and out_len > length_ratio_bound * input_text_len:
        # transform had room to synthesize beyond inputs -> treat as tainted
        return Trust.TAINTED
    return Trust.AMBIGUOUS


def place_in_context(
    spans: dict[str, Span],
    out: TransformOutput,
    *,
    target_role: str,
    length_ratio_bound: float = 3.0,
) -> Trust:
    """Assign a span to a context position, enforcing the positional invariant:
    AMBIGUOUS may occupy data positions only, never directive positions."""
    label = label_transform_output(spans, out, length_ratio_bound=length_ratio_bound)

    directive_roles = {"system", "tool_schema", "planner_scratchpad"}
    if target_role in directive_roles and label is not Trust.TRUSTED:
        raise ProvenanceLaunderingError(
            f"span {out.output_id!r} labeled {label.name} cannot occupy "
            f"directive role {target_role!r}; inputs={out.input_ids}, "
            f"attribution={'present' if out.attribution else 'MISSING'}"
        )

    if label is Trust.TAINTED and target_role not in {"quarantine", "audit_log"}:
        raise ProvenanceLaunderingError(
            f"span {out.output_id!r} is TAINTED (generative, over-length, "
            f"non-attributive) and must be quarantined, not placed in {target_role!r}"
        )

    return label
