# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-summarized-by-a-sub-agent-and-re-ingested-as-a-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-summarized-by-a-sub-agent-and-re-ingested-as-a-memory-write.warrant.json
# Markdown SHA-256:   eb6b1f1aa9e13df1f2ef572a96e0f5cc0b145db3bf2d74dff7fcadd3065a2d10
# Code AST SHA-256:   9d5649ab7651e8f3fde05c5531616d23c11817345061747aded14477533af4e5
# Verified Classes:   Taint, TaintLaunderingError, Artifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Taint(str, Enum):
    CLEAN = "clean"
    TAINTED = "tainted"


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact drops or resets inherited taint."""


@dataclass
class Artifact:
    content: str
    taint: Taint = Taint.CLEAN
    provenance: str = "internal"
    ancestors: list = field(default_factory=list)


# Transforms that are lexically lossy MUST be registered as taint-propagating.
LOSSY_TRANSFORMS = {"summarize", "paraphrase", "translate", "extract"}


def _join(inputs: Iterable[Artifact]) -> Taint:
    return Taint.TAINTED if any(a.taint is Taint.TAINTED for a in inputs) else Taint.CLEAN


def derive(transform: str, inputs: list[Artifact], output_content: str,
           declared_taint: Taint | None) -> Artifact:
    inherited = _join(inputs)
    if transform in LOSSY_TRANSFORMS:
        # Missing label at a lossy boundary => default-deny, not "internal".
        if declared_taint is None:
            raise TaintLaunderingError(
                f"lossy transform '{transform}' emitted no taint label; "
                f"default-deny requires tainted"
            )
        if inherited is Taint.TAINTED and declared_taint is not Taint.TAINTED:
            raise TaintLaunderingError(
                f"transform '{transform}' reset taint from tainted to clean "
                f"(laundering via reformatting)"
            )
    resolved = inherited if declared_taint is None else declared_taint
    return Artifact(
        content=output_content,
        taint=resolved,
        provenance="derived",
        ancestors=[id(a) for a in inputs],
    )


def memory_write(record: Artifact) -> Artifact:
    # Memory reconstruction must inherit lineage, never re-derive from content.
    if record.taint is Taint.TAINTED:
        raise TaintLaunderingError(
            "refusing to write tainted artifact to trusted memory without "
            "explicit declassification bound to original source"
        )
    return record


def declassify(artifact: Artifact, original_source: Artifact,
               human_approved: bool) -> Artifact:
    if not human_approved:
        raise TaintLaunderingError("declassification requires audited approval")
    # Declassification must verify against the ORIGINAL tainted source,
    # not the (possibly laundered) summary.
    if original_source.taint is not Taint.TAINTED:
        raise TaintLaunderingError("declassification target is not the tainted original")
    return Artifact(content=artifact.content, taint=Taint.CLEAN,
                    provenance="declassified", ancestors=artifact.ancestors)
