# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-output-normalization-and-memory-write-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-output-normalization-and-memory-write-summarization.warrant.json
# Markdown SHA-256:   fc61d315297f8e3ea499107277f960d614d778b4178478c5a0b415a5e08ec37c
# Code AST SHA-256:   369ee2b0b811eb23a0ca35102e4698a18f71d71a9ef275a8a0a8dfe84afcdfde
# Verified Classes:   Taint, TaintLaunderingError, Artifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a transform lowers a label without a warrant, or a sink
    receives tainted data without quarantine."""


@dataclass(frozen=True)
class Artifact:
    content: str
    label: Taint
    parents: tuple[str, ...] = field(default_factory=tuple)

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode("utf-8")).hexdigest()


def join_labels(inputs: Iterable[Artifact]) -> Taint:
    # Monotone join: any untrusted input taints the output. Never re-derive
    # from output content.
    return Taint(max((a.label for a in inputs), default=Taint.TRUSTED))


def transform(inputs: list[Artifact], new_content: str, warrant: str | None = None) -> Artifact:
    inherited = join_labels(inputs)
    if inherited == Taint.UNTRUSTED and warrant is None:
        # Allowed: keep untrusted. Forbidden: silently promote to trusted.
        return Artifact(new_content, Taint.UNTRUSTED, tuple(a.content_hash for a in inputs))
    if inherited == Taint.UNTRUSTED and warrant is not None:
        # Declassification requires an explicit, audited warrant.
        return Artifact(new_content, Taint.TRUSTED, tuple(a.content_hash for a in inputs))
    return Artifact(new_content, inherited, tuple(a.content_hash for a in inputs))


def memory_write(artifact: Artifact, store: dict[str, Artifact]) -> None:
    # Sink check: fail closed on tainted writes unless quarantined explicitly.
    if artifact.label == Taint.UNTRUSTED:
        raise TaintLaunderingError(
            f"refusing trusted memory write of tainted artifact {artifact.content_hash[:12]}"
        )
    store[artifact.content_hash] = artifact


def egress(artifact: Artifact, destination: str) -> None:
    # Sink check at the tool-egress boundary.
    if artifact.label == Taint.UNTRUSTED:
        raise TaintLaunderingError(
            f"egress to {destination} blocked: artifact {artifact.content_hash[:12]} is tainted"
        )


def detect_provenance_gap(artifact: Artifact, known_parents: set[str]) -> None:
    # A recovering transform that dropped parent hashes is a protocol violation.
    if any(p not in known_parents for p in artifact.parents):
        raise TaintLaunderingError(
            f"artifact {artifact.content_hash[:12]} cites unknown parents; "
            "possible unlogged recovering transform"
        )
