# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-when-prompt-injection-taint-crosses-a-tool-graph-fan-in.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-when-prompt-injection-taint-crosses-a-tool-graph-fan-in.warrant.json
# Markdown SHA-256:   9f7a8da0a6f5940ca0aeff3d972af23e4812517f5734695a3cfb202e5742e21e
# Code AST SHA-256:   ba7f150469674976e105b121474f936a9665e9bc4180b8a61b63060ee388f19a
# Verified Classes:   TaintLaunderingError, Fragment, MergedContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a fan-in merge attempts to clear taint by aggregation."""


@dataclass(frozen=True)
class Fragment:
    fragment_id: str
    source_tier: int          # higher = more authoritative, metadata only
    taint: bool               # True = derived from untrusted content
    text: str


@dataclass
class MergedContext:
    fragments: list[Fragment] = field(default_factory=list)
    taint: bool = False
    tier: int = 0


def merge_fan_in(fragments: Iterable[Fragment], *, consumer_can_act: bool) -> MergedContext:
    frags = list(fragments)
    if not frags:
        raise TaintLaunderingError("empty fan-in: cannot compute provenance")

    # Sticky OR: taint survives any aggregation.
    merged_taint = any(f.taint for f in frags)
    merged_tier = max(f.source_tier for f in frags)

    # If any fragment is tainted and the consumer can emit side effects,
    # aggregation rules (majority / max-tier) are forbidden.
    if merged_taint and consumer_can_act:
        tainted_ids = [f.fragment_id for f in frags if f.taint]
        # An aggregation rule would have produced taint=False here; refuse it.
        trusted_count = sum(1 for f in frags if not f.taint)
        if trusted_count >= len(frags) - trusted_count:
            raise TaintLaunderingError(
                f"fan-in would launder taint by majority: tainted={tainted_ids}, "
                f"trusted={trusted_count}/{len(frags)}; declassify by removal, not vote"
            )
        return MergedContext(fragments=frags, taint=True, tier=merged_tier)

    return MergedContext(fragments=frags, taint=merged_taint, tier=merged_tier)


def admit_to_action_surface(ctx: MergedContext, action: str) -> None:
    if ctx.taint:
        raise TaintLaunderingError(
            f"action '{action}' rejected: context carries unresolved taint from "
            f"{[f.fragment_id for f in ctx.fragments if f.taint]}"
        )
    # action proceeds only on a declassified (taint=False) context
