# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-nested-tool-call-s-return-value-as-tainted-even-after-the-parent-agent-has-sanitized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-nested-tool-call-s-return-value-as-tainted-even-after-the-parent-agent-has-sanitized-it.warrant.json
# Markdown SHA-256:   8d52fbe6566b0101489f1efb5ea3b6dc0da91c04521529748f8d45e429246443
# Code AST SHA-256:   f6c38fc96019cecbf3550b380d9121c7544cd150ceadbb83345e37d05244a90a
# Verified Classes:   Taint, TransformClass, TaintLaunderingError, Labeled
# Defensive Guards:   2 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"
    INJECTION = "injection"


class TransformClass(str, Enum):
    # Effect-based: output is a strict function of input, no model in loop.
    BYTE_TRUNCATE = "byte_truncate"
    STRUCTURED_EXTRACT = "structured_extract"
    REGEX_ALLOWLIST = "regex_allowlist"
    # Semantic: model generates output tokens. NEVER declassifies.
    SEMANTIC_SUMMARY = "semantic_summary"
    PARAPHRASE = "paraphrase"


EFFECT_BASED = {
    TransformClass.BYTE_TRUNCATE,
    TransformClass.STRUCTURED_EXTRACT,
    TransformClass.REGEX_ALLOWLIST,
}


class TaintLaunderingError(RuntimeError):
    """Raised when a label is lowered by annotation or semantic transform
    rather than by a registered effect-based transform."""


@dataclass
class Labeled:
    payload: str
    taint: Taint
    lineage: list = field(default_factory=list)  # list[tuple[str, str]]


def join(a: Taint, b: Taint) -> Taint:
    return Taint.INJECTION if Taint.INJECTION in (a, b) else Taint.CLEAN


def declassify(
    src: Labeled,
    transform: TransformClass,
    annotation: str | None = None,
) -> Labeled:
    if src.taint is Taint.CLEAN:
        return src
    if transform not in EFFECT_BASED:
        # Semantic transform: preserve taint, record the edge.
        return Labeled(
            payload=src.payload,
            taint=src.taint,
            lineage=src.lineage + [("semantic_transform", transform.value)],
        )
    if annotation is not None:
        # Annotation cannot justify a drop; only the transform class can.
        # If both are present, the transform class governs, but flag it.
        pass
    return Labeled(
        payload=src.payload,
        taint=Taint.CLEAN,
        lineage=src.lineage + [("declassified_by", transform.value)],
    )


def nested_return(
    parent_input: Labeled,
    child_output: Labeled,
    child_claims_clean: bool,
) -> Labeled:
    """A nested agent's return value inherits the max taint of its input
    unless the child can point to an effect-based transform in its lineage.
    A child's *claim* of cleanliness is not evidence."""
    derived = any(kind == "semantic_transform" for kind, _ in child_output.lineage)
    if child_claims_clean and parent_input.taint is Taint.INJECTION and derived:
        raise TaintLaunderingError(
            "nested agent returned CLEAN after a semantic transform; "
            "label must be preserved as INJECTION"
        )
    return Labeled(
        payload=child_output.payload,
        taint=join(parent_input.taint, child_output.taint),
        lineage=parent_input.lineage + child_output.lineage,
    )


def sink_send_email(payload: Labeled, content_blind: bool) -> None:
    if payload.taint is Taint.INJECTION and not content_blind:
        raise TaintLaunderingError(
            "content-interpreting sink received INJECTION-tainted payload; "
            "route through human-confirm or an effect-based declassifier"
        )
    # ... perform send ...


# Reproduces the observed incident and shows where it now halts.
def _replay() -> None:
    web = Labeled("...wire details before proceeding...", Taint.INJECTION,
                  [("src", "web")])
    summarized = declassify(web, TransformClass.SEMANTIC_SUMMARY)
    # Runtime *would* have applied summary_of -> CLEAN here; we don't.
    nested = nested_return(web, summarized, child_claims_clean=True)
    sink_send_email(nested, content_blind=False)  # raises


if __name__ == "__main__":
    _replay()
