# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-tool-output-summarization-label-decay-across-the-retrieval-to-context-laundering-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-tool-output-summarization-label-decay-across-the-retrieval-to-context-laundering-path.warrant.json
# Markdown SHA-256:   8074d07f57c11c695b53f8db4af6ba38c1c9d80c237a2a3ed2ff1f05d2125566
# Code AST SHA-256:   7cac737edbc358202ec88e2fdf7dbb3e227d7e8365fa9597b5c0175a555b66cc
# Verified Classes:   TrustLevel, TaintPropagationError, Artifact, TaintGraph
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class TrustLevel(IntEnum):
    """Ordered trust lattice. Lower = less trusted. Join = min."""
    EXTERNAL = 0
    DERIVED_EXTERNAL = 1   # laundered through a generative transform
    INTERNAL_SELF = 2
    VERIFIED_TRUSTED = 3


class TaintPropagationError(RuntimeError):
    """Raised when a derivation edge is missing or an egress leaks taint."""


@dataclass(frozen=True)
class Artifact:
    artifact_id: str
    label: TrustLevel
    inputs: tuple[str, ...] = field(default_factory=tuple)


class TaintGraph:
    def __init__(self) -> None:
        self._nodes: dict[str, Artifact] = {}

    def register(self, art: Artifact) -> None:
        self._nodes[art.artifact_id] = art

    def _label_of(self, artifact_id: str) -> TrustLevel:
        try:
            return self._nodes[artifact_id].label
        except KeyError as exc:
            raise TaintPropagationError(
                f"unknown artifact {artifact_id!r}: derivation edge dangling"
            ) from exc

    def join_label(self, input_ids: Iterable[str]) -> TrustLevel:
        """Least-upper-bound in the trust lattice: the least-trusted input wins."""
        ids = list(input_ids)
        if not ids:
            raise TaintPropagationError(
                "generative transform recorded zero inputs; input capture incomplete"
            )
        return TrustLevel(min(self._label_of(i) for i in ids))

    def record_derivation(
        self, output_id: str, actual_input_ids: Iterable[str]
    ) -> TrustLevel:
        """Compute the join from the *actual* input set the model saw."""
        joined = self.join_label(actual_input_ids)
        self._nodes[output_id] = Artifact(
            artifact_id=output_id,
            label=joined,
            inputs=tuple(actual_input_ids),
        )
        return joined

    def check_egress(self, artifact_id: str, allowed: TrustLevel) -> None:
        label = self._label_of(artifact_id)
        if label < allowed:
            raise TaintPropagationError(
                f"egress blocked: {artifact_id!r} carries {label.name} "
                f"but tool requires >= {allowed.name}"
            )


def summarize_documents(
    graph: TaintGraph,
    output_id: str,
    chunks_seen_by_model: list[str],
) -> TrustLevel:
    """
    A generative transform. The label MUST be computed from the chunks the
    model actually consumed, not asserted by the tool author as 'self-authored'.
    """
    if not chunks_seen_by_model:
        raise TaintPropagationError(
            "summarizer invoked with no recorded inputs; cannot compute join"
        )
    for cid in chunks_seen_by_model:
        if cid not in graph._nodes:
            raise TaintPropagationError(
                f"summarizer consumed unregistered chunk {cid!r}; "
                "taint cannot be propagated through an unlabeled input"
            )
    return graph.record_derivation(output_id, chunks_seen_by_model)


# --- reproduction of the observed failure trace ---
graph = TaintGraph()
graph.register(Artifact("chunk_4471", TrustLevel.EXTERNAL))

summarize_documents(graph, "summary_01", ["chunk_4471"])
# summary_01 is now DERIVED_EXTERNAL == EXTERNAL (join), not INTERNAL_SELF.

# The agent writes the summary to its scratchpad. The runtime must NOT
# upgrade the label because "the agent wrote it."
graph.register(
    Artifact("scratchpad_step_1", graph._label_of("summary_01"),
             inputs=("summary_01",))
)

# Egress guard now blocks the exfiltration attempt.
try:
    graph.check_egress("scratchpad_step_1", allowed=TrustLevel.INTERNAL_SELF)
except TaintPropagationError as err:
    print(f"BLOCKED: {err}")
else:
    raise TaintPropagationError("egress guard failed to block laundered taint")
