# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-taint-sink-a-tool-response-before-its-derived-facts-are-promoted-to-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-taint-sink-a-tool-response-before-its-derived-facts-are-promoted-to-semantic-memory.warrant.json
# Markdown SHA-256:   e7547272b1b4706e2056af45ec6667134e256bfc65db4ddb64318d441bc7e7df
# Code AST SHA-256:   2b3d147ca432173ca6887c1e9f3478963e4fdf292c5988db7c51c8a755ea68b2
# Verified Classes:   Trust, ProvenanceLossError, Segment, DerivedFact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # join is max: any untrusted input taints the output


class ProvenanceLossError(RuntimeError):
    """Raised when a derived fact cannot be soundly labeled from its true inputs."""


@dataclass
class Segment:
    label: Trust
    source: str


@dataclass
class DerivedFact:
    text: str
    label: Trust
    sources: tuple[str, ...] = field(default_factory=tuple)


def join(labels: Iterable[Trust]) -> Trust:
    labels = list(labels)
    if not labels:
        # No observable inputs => cannot prove trust; conservative default.
        raise ProvenanceLossError("empty input set: join undefined, refusing TRUSTED")
    return Trust(max(labels))


def distill(context: list[Segment], summary: str, context_observable: bool) -> DerivedFact:
    if not context_observable:
        # Black-box summarizer: true input set unknown, join uncomputable.
        raise ProvenanceLossError(
            "summarizer context not instrumented; cannot compute input join"
        )
    label = join(seg.label for seg in context)
    return DerivedFact(text=summary, label=label, sources=tuple(s.source for s in context))


def promote(fact: DerivedFact, store_partition: str) -> None:
    if fact.label is Trust.UNTRUSTED and store_partition == "first_party":
        raise ProvenanceLossError(
            f"refusing to promote UNTRUSTED fact {fact.text!r} into first-party memory"
        )
    if not fact.sources:
        raise ProvenanceLossError(
            f"fact {fact.text!r} has no source-span pointer; replay unverifiable"
        )
    # write to partition ...


def check_tool_call(args_context: list[Segment], tool: str) -> None:
    if join(seg.label for seg in args_context) is Trust.UNTRUSTED:
        raise ProvenanceLossError(
            f"tainted context reached sink tool={tool!r}; require re-derivation"
        )
