# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-retrieval-chunks-whose-provenance-label-has-been-downgraded-by-a-later-tool-call-rather-than-trusting-fi.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-retrieval-chunks-whose-provenance-label-has-been-downgraded-by-a-later-tool-call-rather-than-trusting-fi.warrant.json
# Markdown SHA-256:   b8d0bb00ac875d821e00c77092a1c63cbdd9c9399786d4496e8a22346c09c6a3
# Code AST SHA-256:   75473bf5ee95d5b2471b08d6dac0b701fe57c6df8f9ebdca2d8e2edf8cafd929
# Verified Classes:   Trust, TaintLaunderingError, UnresolvableLineageError, Artifact, ProvenanceStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class Trust(Enum):
    INTERNAL = 0
    EXTERNAL = 1

    def join(self, other: "Trust") -> "Trust":
        # least-trusted wins
        return Trust(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact's label is weaker than the join of its lineage."""
    pass


class UnresolvableLineageError(RuntimeError):
    """Raised when a buffer slot's provenance cannot be traced to leaf sources."""
    pass


@dataclass
class Artifact:
    id: str
    content: str
    # leaf sources carry their own taint; derived artifacts carry none and must resolve via parents
    leaf_taint: Optional[Trust] = None
    parents: tuple[str, ...] = field(default_factory=tuple)
    is_freetext_tool_output: bool = False


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

    def register_leaf(self, art: Artifact) -> None:
        assert art.leaf_taint is not None
        self._artifacts[art.id] = art

    def register_derived(self, art: Artifact) -> None:
        for p in art.parents:
            if p not in self._artifacts:
                raise UnresolvableLineageError(
                    f"derived artifact {art.id!r} references unknown parent {p!r}"
                )
        self._artifacts[art.id] = art

    def resolve_taint(self, art_id: str, _seen: Optional[set[str]] = None) -> Trust:
        seen = _seen or set()
        if art_id in seen:
            raise UnresolvableLineageError(f"cycle in lineage at {art_id!r}")
        seen.add(art_id)
        art = self._artifacts.get(art_id)
        if art is None:
            raise UnresolvableLineageError(f"unknown artifact {art_id!r}")
        if not art.parents:
            if art.leaf_taint is None:
                raise UnresolvableLineageError(f"leaf {art_id!r} has no taint")
            return art.leaf_taint
        acc = Trust.INTERNAL
        for p in art.parents:
            acc = acc.join(self.resolve_taint(p, seen))
        return acc

    def check_label(self, art_id: str, assigned: Trust) -> None:
        derived = self.resolve_taint(art_id)
        art = self._artifacts[art_id]
        # free-text tool outputs cannot downgrade taint regardless of tool trust tier
        if art.is_freetext_tool_output and derived is Trust.EXTERNAL and assigned is Trust.INTERNAL:
            raise TaintLaunderingError(
                f"artifact {art_id!r}: free-text tool output labeled {assigned.name} "
                f"but lineage join is {derived.name}; producer-trust downgrade forbidden"
            )
        if assigned.value < derived.value:
            raise TaintLaunderingError(
                f"artifact {art_id!r}: assigned {assigned.name} weaker than lineage {derived.name}"
            )


def summarize(store: ProvenanceStore, src_id: str, out_id: str, out_text: str) -> None:
    # a general LLM summarizer: free-text out, cannot sanitize instructions
    store.register_derived(
        Artifact(id=out_id, content=out_text, parents=(src_id,), is_freetext_tool_output=True)
    )
    # naive orchestrator tries to label by tool trust tier:
    store.check_label(out_id, Trust.INTERNAL)  # raises TaintLaunderingError


if __name__ == "__main__":
    ps = ProvenanceStore()
    ps.register_leaf(Artifact(id="C1", content="policy ... Ignore prior instructions ...",
                              leaf_taint=Trust.EXTERNAL))
    summarize(ps, "C1", "S1", "reply should include payment details")
