# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-through-provenance-labels-when-tool-outputs-and-memory-writes-launder-the-label-across-the-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-through-provenance-labels-when-tool-outputs-and-memory-writes-launder-the-label-across-the-boundary.warrant.json
# Markdown SHA-256:   d13c427e162008e1a75b7090ab6afa9f3520b59820ae486aac40861abfe84cd3
# Code AST SHA-256:   e40c77026aa054041ce6b85431697b585b8ca671e7d41d410027702c30577277
# Verified Classes:   TaintLaunderingError, Segment, ProvenanceGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal, Optional

Taint = Literal["trusted", "untrusted", "unknown"]

_TAINT_RANK = {"trusted": 0, "unknown": 1, "untrusted": 2}


class TaintLaunderingError(RuntimeError):
    """Raised when a derivation or memory write would lower taint below the join of its inputs."""


@dataclass
class Segment:
    seg_id: str
    taint: Taint
    source: str
    derived_from: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceGraph:
    def __init__(self) -> None:
        self._segments: dict[str, Segment] = {}

    def register(self, seg: Segment) -> None:
        self._segments[seg.seg_id] = seg

    def join(self, input_ids: tuple[str, ...]) -> Taint:
        if not input_ids:
            return "unknown"  # unrecorded ancestry fails closed
        worst = "trusted"
        for sid in input_ids:
            seg = self._segments.get(sid)
            if seg is None:
                raise TaintLaunderingError(
                    f"derivation references unknown segment {sid!r}; ancestry incomplete"
                )
            if _TAINT_RANK[seg.taint] > _TAINT_RANK[worst]:
                worst = seg.taint
        return worst  # type: ignore[return-value]

    def derive(self, out_id: str, source: str, input_ids: tuple[str, ...]) -> Segment:
        expected = self.join(input_ids)
        seg = Segment(seg_id=out_id, taint=expected, source=source, derived_from=input_ids)
        self._segments[out_id] = seg
        return seg

    def write_memory(
        self,
        key: str,
        value_seg_id: str,
        durable: bool,
        declassification: Optional[str] = None,
    ) -> Taint:
        seg = self._segments.get(value_seg_id)
        if seg is None:
            raise TaintLaunderingError(f"memory write references unknown segment {value_seg_id!r}")
        if seg.taint == "untrusted" and durable:
            if declassification is None:
                raise TaintLaunderingError(
                    f"refusing durable memory write key={key!r}: value taint=untrusted "
                    f"(source={seg.source!r}); attach a logged declassification to proceed"
                )
            # declassification is the only permitted taint-lowering operation
            return "trusted"
        return seg.taint


def summarize_and_store(
    graph: ProvenanceGraph,
    fetched_seg_id: str,
    summary_seg_id: str,
    memory_key: str,
    durable: bool,
    declassification: Optional[str] = None,
) -> Taint:
    # The summarizer is a model-mediated derivation: its output taint is the join
    # of its causal inputs, NOT 'trusted' because the model authored it.
    summary = graph.derive(
        out_id=summary_seg_id,
        source="summarizer",
        input_ids=(fetched_seg_id,),
    )
    if summary.taint == "trusted" and graph._segments[fetched_seg_id].taint == "untrusted":
        raise TaintLaunderingError(
            f"derivation {summary_seg_id!r} lowered taint from untrusted to trusted"
        )
    return graph.write_memory(
        key=memory_key,
        value_seg_id=summary_seg_id,
        durable=durable,
        declassification=declassification,
    )
