# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-survival-across-retrieval-boundaries-in-indirect-prompt-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-survival-across-retrieval-boundaries-in-indirect-prompt-injection.warrant.json
# Markdown SHA-256:   fd019bd61d98e9074831c577362b5184d106617084f07a61265a2f6b79548e92
# Code AST SHA-256:   a51ed5368e2f171c732b3a7fdc08768dcd294061499c5038f4943f0d29c296e3
# Verified Classes:   TaintPromotionError, Authority, Chunk, AssembledContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TaintPromotionError(RuntimeError):
    """Raised when a retrieved chunk reaches the instruction plane without a surviving structural label."""


class Authority(Enum):
    SYSTEM = 3
    SUBAGENT_SUMMARY = 2
    CACHED_TURN = 1
    WEB_FETCH = 0
    USER_UPLOAD = 0


@dataclass
class Chunk:
    text: str
    source: str | None
    authority: Authority
    fenced: bool
    position: int
    total: int
    derived_from: Authority | None = None  # set when produced by a summarizer


@dataclass
class AssembledContext:
    chunks: list[Chunk] = field(default_factory=list)
    terminal_adjacent_to_preamble: bool = False


def check_structural_taint(ctx: AssembledContext, agent_authority: Authority) -> None:
    """Enforce label preservation. Raise on any promotion event."""
    for c in ctx.chunks:
        # Signal 1: provenance collapse during merge
        if c.source is None:
            raise TaintPromotionError(
                f"chunk at position {c.position} lost its source label during merge; "
                "taint-promotion site at assembly"
            )

        # Signal 3: delimiter erosion under chunking
        if not c.fenced:
            raise TaintPromotionError(
                f"chunk from {c.source} arrived unfenced at position {c.position}; "
                "chunker severed syntactic enclosure"
            )

        # Signal 5: authority-rank laundering
        if c.derived_from is not None and c.authority.value > c.derived_from.value:
            raise TaintPromotionError(
                f"chunk from {c.source} laundered authority from "
                f"{c.derived_from.name} to {c.authority.name}; "
                "summarizer must inherit minimum input authority"
            )

        # Signal 2: recency-position inversion at terminal slot
        is_terminal = c.position == c.total - 1
        if is_terminal and c.authority.value < agent_authority.value:
            raise TaintPromotionError(
                f"low-authority chunk ({c.authority.name}) occupies terminal position; "
                "positional authority exceeds source authority"
            )

        # Signal 4: adjacency grafting onto tool preamble
        if is_terminal and ctx.terminal_adjacent_to_preamble:
            raise TaintPromotionError(
                f"chunk from {c.source} adjacent to tool preamble with no role boundary; "
                "grafting risk"
            )


def assemble(raw_chunks: list[Chunk], agent_authority: Authority) -> AssembledContext:
    ctx = AssembledContext(chunks=raw_chunks)
    check_structural_taint(ctx, agent_authority)
    return ctx
