# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-at-the-tool-boundary-when-its-own-tool-output-re-enters-as-trusted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-at-the-tool-boundary-when-its-own-tool-output-re-enters-as-trusted-context.warrant.json
# Markdown SHA-256:   b0f23d0a9e768e4cdf0db5c18553a222735331cfc4f2ac6d1b270b25c91bd266
# Code AST SHA-256:   008f32ed15a27f66687b69b079c9bf2c9fd08547212faae7539b1ba627b11f87
# Verified Classes:   TaintLevel, Segment, ToolResponse, TaintBoundaryError, LineageStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum


class TaintLevel(IntEnum):
    TRUSTED = 0
    EXTERNAL = 1


@dataclass(frozen=True)
class Segment:
    seg_id: str
    data: str
    taint: TaintLevel
    lineage: tuple[str, ...]          # IDs of input segments this was derived from
    cleared_by_warrant: str | None = None


@dataclass
class ToolResponse:
    data: str
    # Emitter's self-reported taint is only a HINT, never a verdict.
    reported_taint: TaintLevel | None = None


class TaintBoundaryError(RuntimeError):
    """Raised when a segment's label cannot be authoritatively established."""


class LineageStore:
    def __init__(self) -> None:
        self._segments: dict[str, Segment] = {}

    def register(self, seg: Segment) -> None:
        self._segments[seg.seg_id] = seg

    def get(self, seg_id: str) -> Segment:
        if seg_id not in self._segments:
            raise TaintBoundaryError(f"unknown segment {seg_id!r}; cannot trace lineage")
        return self._segments[seg_id]


def ingest_tool_output(
    store: LineageStore,
    new_seg_id: str,
    response: ToolResponse,
    input_seg_ids: tuple[str, ...],
    emitting_tool: str,
) -> Segment:
    """
    Recompute taint from DATA LINEAGE, not from emitter identity.
    Meet (max) of all input taints; emitter trust is irrelevant.
    """
    if not input_seg_ids:
        raise TaintBoundaryError(
            f"tool {emitting_tool!r} produced {new_seg_id!r} with no declared inputs; "
            "lineage is unattributable, refusing to label"
        )

    derived_taint = TaintLevel.TRUSTED
    for sid in input_seg_ids:
        src = store.get(sid)
        derived_taint = TaintLevel(max(derived_taint, src.taint))

    # Emitter hint may only ESCALATE, never de-escalate. A lying tool that
    # reports TRUSTED while its inputs were EXTERNAL is overruled by lineage.
    if response.reported_taint is not None:
        derived_taint = TaintLevel(max(derived_taint, response.reported_taint))

    seg = Segment(
        seg_id=new_seg_id,
        data=response.data,
        taint=derived_taint,
        lineage=input_seg_ids,
    )
    store.register(seg)
    return seg


def clear_taint(store: LineageStore, seg_id: str, warrant: str | None) -> Segment:
    """Downgrade requires a warrant bound to the segment; identity is not enough."""
    seg = store.get(seg_id)
    if seg.taint == TaintLevel.TRUSTED:
        return seg
    if warrant is None:
        raise TaintBoundaryError(
            f"cannot clear taint on {seg_id!r}: no warrant supplied"
        )
    if warrant != f"clear:{seg_id}":
        raise TaintBoundaryError(
            f"warrant {warrant!r} not bound to segment {seg_id!r}"
        )
    cleared = Segment(
        seg_id=seg.seg_id,
        data=seg.data,
        taint=TaintLevel.TRUSTED,
        lineage=seg.lineage,
        cleared_by_warrant=warrant,
    )
    store.register(cleared)
    return cleared


def guarded_tool_call(store: LineageStore, arg_seg_ids: tuple[str, ...]) -> None:
    """Any tool call drawing arguments from tainted segments must be blocked."""
    for sid in arg_seg_ids:
        seg = store.get(sid)
        if seg.taint == TaintLevel.EXTERNAL and seg.cleared_by_warrant is None:
            raise TaintBoundaryError(
                f"tool call argument {sid!r} is tainted (external) and not cleared; "
                "possible prompt-injection propagation across tool boundary"
            )
