# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-taint-a-tool-output-that-passed-schema-validation-but-carries-injected-instructions-across-a-prompt-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-taint-a-tool-output-that-passed-schema-validation-but-carries-injected-instructions-across-a-prompt-boundary.warrant.json
# Markdown SHA-256:   91dc4314791c49f97517069a47e1df5d6a5d505bc5c9ea8f1ed12668dabd38be
# Code AST SHA-256:   27cba6d96125048d950e407a494a202e7f30878fe1eb9d0a87bee6ae2863a035
# Verified Classes:   TrustDomain, TaintBoundaryError, Span, DerivedArtifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TrustDomain(Enum):
    TRUSTED = "trusted"          # orchestrator-controlled, may issue instructions
    UNTRUSTED = "untrusted"      # web, third-party MCP, external peer
    DERIVED = "derived"          # produced by a transformer; inherits provenance


class TaintBoundaryError(RuntimeError):
    """Raised when a derived artifact carrying untrusted provenance is
    concatenated into a prompt without re-tainting at the prompt boundary."""


@dataclass
class Span:
    text: str
    domain: TrustDomain


@dataclass
class DerivedArtifact:
    spans: list[Span]
    transformer_trusted: bool
    has_span_provenance: bool = field(default=True)


def assert_prompt_boundary_safe(
    artifact: DerivedArtifact,
    downstream_is_model: bool,
) -> list[Span]:
    """
    Enforce the invariant: any span whose provenance traces to an untrusted
    domain must be re-tainted before it enters a model-readable prompt.

    Returns the re-tainted spans (safe to concatenate as data).
    Raises TaintBoundaryError if the artifact cannot be safely re-tainted.
    """
    if not downstream_is_model:
        # Deterministic consumer: no instruction-following surface.
        return artifact.spans

    if not artifact.has_span_provenance:
        # Transformer emitted a flat string. Cannot prove cleanliness.
        # Assume full inheritance: re-taint the entire artifact.
        if not artifact.transformer_trusted:
            raise TaintBoundaryError(
                "Opaque transformer with no span provenance and untrusted "
                "transformer identity: cannot bound provenance; refusing to "
                "concatenate into model-readable prompt."
            )
        joined = "".join(s.text for s in artifact.spans)
        return [Span(text=joined, domain=TrustDomain.DERIVED)]

    re_tainted: list[Span] = []
    for span in artifact.spans:
        if span.domain in (TrustDomain.UNTRUSTED, TrustDomain.DERIVED):
            # Provenance is inherited through transformation. Re-stamp.
            re_tainted.append(Span(text=span.text, domain=TrustDomain.DERIVED))
        else:
            re_tainted.append(span)

    # Final check: no span may claim TRUSTED while carrying reproduced
    # content from a lower-authority domain.
    for span in re_tainted:
        if span.domain is TrustDomain.TRUSTED and _looks_reproduced(span.text):
            raise TaintBoundaryError(
                "Span marked TRUSTED but matches reproduced-content heuristic; "
                "provenance laundering suspected at prompt boundary."
            )
    return re_tainted


def _looks_reproduced(text: str) -> bool:
    # Heuristic placeholder: real implementations use span provenance maps,
    # not string matching. Kept here to show the last-line check.
    imperatives = ("should now call", "you must", "ignore previous", "execute ")
    low = text.lower()
    return any(p in low for p in imperatives)


def assemble_downstream_prompt(artifact: DerivedArtifact) -> str:
    spans = assert_prompt_boundary_safe(artifact, downstream_is_model=True)
    parts = []
    for span in spans:
        if span.domain is TrustDomain.DERIVED:
            # Data/instruction separation: model must see it as data.
            parts.append(f"<untrusted_data>{span.text}</untrusted_data>")
        else:
            parts.append(span.text)
    return "\n".join(parts)
