# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-prompt-injection-taint-propagation-from-legitimate-instruction-flow-when-labels-cross-tool-output-and-retrieval-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-prompt-injection-taint-propagation-from-legitimate-instruction-flow-when-labels-cross-tool-output-and-retrieval-bou.warrant.json
# Markdown SHA-256:   5bc97a3c0e0326fc3a2a602ef7e64947d3ef7e26ece42de1a74b0d67dfa34674
# Code AST SHA-256:   d5ca467d28bc7744b7d3f6362acaf84c6eaf9d8ecaec1d646caf54d8a578f51e
# Verified Classes:   TaintBoundaryError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Tuple


class TaintBoundaryError(RuntimeError):
    """Raised when a context segment's label set violates the origin-set invariant."""
    pass


@dataclass(frozen=True)
class Segment:
    content: str
    origins: FrozenSet[str]
    transforms: Tuple[Tuple[str, str], ...] = field(default_factory=tuple)

    def derive(self, kind: str, actor: str, new_content: str) -> "Segment":
        # Model-mediated transform must preserve origins and append to transforms.
        return Segment(
            content=new_content,
            origins=self.origins,
            transforms=self.transforms + ((kind, actor),),
        )


TRUSTED_ORIGINS = frozenset({"system", "user"})


def check_instruction_admissible(seg: Segment) -> None:
    model_mediated_over_untrusted = any(
        actor == "model" and not (seg.origins <= TRUSTED_ORIGINS)
        for _, actor in seg.transforms
    )
    if model_mediated_over_untrusted:
        raise TaintBoundaryError(
            f"segment derived via model transform over untrusted origins "
            f"{sorted(seg.origins)}; cannot issue instructions"
        )


def reingest_summary(summary_text: str, source: Segment) -> Segment:
    derived = source.derive("summarize", "model", summary_text)
    # The bug we are guarding against: re-labeling as MODEL_GENERATED.
    if derived.origins != source.origins:
        raise TaintBoundaryError(
            "origin set collapsed during model-mediated transform"
        )
    return derived
