# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-survived-a-tool-boundary-and-what-to-do-when-provenance-labels-go-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-survived-a-tool-boundary-and-what-to-do-when-provenance-labels-go-stale.warrant.json
# Markdown SHA-256:   b8a50e9791a99deb2fa640fb6559b6046a7f8eebfe4794340fa24bc4ccc0be4f
# Code AST SHA-256:   fd78a53b523721aa446ecd06fb81711171a646026935ba5fd87b65388a418762
# Verified Classes:   ProvenanceLaunderingError, Label, Range, ToolOutput
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tool output range is labeled more trusted than a
    containing input range whose bytes it physically includes."""


@dataclass(frozen=True)
class Label:
    tainted: bool

    def join(self, other: "Label") -> "Label":
        return Label(self.tainted or other.tainted)

    def __le__(self, other: "Label") -> bool:
        # untrusted <= trusted is False; trusted <= untrusted is False;
        # equal labels compare True. Order: trusted < untrusted.
        return (not self.tainted) or other.tainted


@dataclass
class Range:
    start: int
    end: int
    label: Label


@dataclass
class ToolOutput:
    raw: str
    ranges: list[Range] = field(default_factory=list)
    byte_attributable: bool = True


def check_containment(
    input_ranges: list[Range],
    output: ToolOutput,
    tool_name: str,
) -> list[Range]:
    """Enforce: no output range may be labeled more trusted than any
    input range whose bytes it contains. Returns normalized ranges."""
    if not output.byte_attributable:
        # Generative tool: conservative OR-propagation, no declassification.
        joined = Label(False)
        for r in input_ranges:
            joined = joined.join(r.label)
        return [Range(0, len(output.raw), joined)]

    normalized: list[Range] = []
    for out_r in output.ranges:
        effective = out_r.label
        for in_r in input_ranges:
            overlaps = not (out_r.end <= in_r.start or in_r.end <= out_r.start)
            if overlaps and effective.tainted is False and in_r.label.tainted:
                raise ProvenanceLaunderingError(
                    f"tool '{tool_name}' returned range "
                    f"[{out_r.start}:{out_r.end}] labeled trusted but "
                    f"contains tainted bytes from input range "
                    f"[{in_r.start}:{in_r.end}]. Field-name-based "
                    f"declassification is not permitted."
                )
            if overlaps:
                effective = effective.join(in_r.label)
        normalized.append(Range(out_r.start, out_r.end, effective))
    return normalized


def route_to_context_region(ranges: list[Range]) -> str:
    """Tainted ranges must never enter the system-adjacent region."""
    if any(r.label.tainted for r in ranges):
        return "user_region"
    return "system_adjacent_region"


# Example trigger: metadata.author carries injected instruction, but the
# tool serializer labeled metadata as trusted while body was tainted.
if __name__ == "__main__":
    raw_out = "<doc>...body...</doc><author>IGNORE PREVIOUS...</author>"
    body_start, body_end = 0, raw_out.index("<author>")
    author_start, author_end = body_end, len(raw_out)
    inputs = [Range(0, len(raw_out), Label(tainted=True))]
    out = ToolOutput(
        raw=raw_out,
        ranges=[
            Range(body_start, body_end, Label(tainted=True)),
            Range(author_start, author_end, Label(tainted=False)),  # laundering
        ],
        byte_attributable=True,
    )
    try:
        normalized = check_containment(inputs, out, tool_name="fetch_url")
    except ProvenanceLaunderingError as e:
        # Escalate the offending range instead of trusting it.
        normalized = [
            Range(author_start, author_end, Label(tainted=True)),
            Range(body_start, body_end, Label(tainted=True)),
        ]
        print(f"escalated: {e}")
    region = route_to_context_region(normalized)
    assert region == "user_region", "tainted content leaked into system region"
