# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-reasoning-continues-and-how-do-dynamic-information-flow-labels-survive-the-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-reasoning-continues-and-how-do-dynamic-information-flow-labels-survive-the-tool-boundary.warrant.json
# Markdown SHA-256:   9dea754369fd63fc23454c6b7413795200cb25903d5c72a495a9effb15c0f7bc
# Code AST SHA-256:   7e6d9e80a58f4040ad1a54b2d114188ce5842e9f814801a3efbb102284d12b30
# Verified Classes:   Integrity, TaintLaunderingError, Span, ToolDecl
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class Integrity(IntEnum):
    UNTRUSTED = 0
    INTERNAL = 1
    TRUSTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a tool result would reach a gated action with laundered integrity."""


@dataclass
class Span:
    text: str
    integrity: Integrity
    taint_ids: frozenset = field(default_factory=frozenset)


@dataclass
class ToolDecl:
    name: str
    produces: Integrity
    propagates_taint: bool = True
    gated_at: Optional[Integrity] = None  # side-effecting tools declare a floor


def admit_tool_result(
    decl: ToolDecl,
    result_text: str,
    requesting_context: list,
    dest_reaches_gated_action: bool,
) -> Span:
    # Taint closure of the REQUESTING context at call-emission time.
    live = frozenset().union(*(s.taint_ids for s in requesting_context))
    min_req_integrity = min((s.integrity for s in requesting_context), default=Integrity.TRUSTED)

    effective = decl.produces
    if decl.propagates_taint:
        effective = Integrity(min(int(effective), int(min_req_integrity)))

    span = Span(result_text, effective, live)

    if (
        effective < Integrity.INTERNAL
        and dest_reaches_gated_action
        and decl.gated_at is not None
        and decl.gated_at >= Integrity.INTERNAL
    ):
        raise TaintLaunderingError(
            f"tool '{decl.name}' result has effective integrity {effective.name} "
            f"(requesting taint_ids={sorted(live)}) but feeds a gated action "
            f"requiring {decl.gated_at.name}; quarantine or declassify explicitly"
        )
    return span


def check_action_guard(prompt_spans: list, required: Integrity) -> None:
    # Guard reads the taint closure of the WHOLE prompt, not just last turn.
    worst = min((s.integrity for s in prompt_spans), default=Integrity.TRUSTED)
    if worst < required:
        raise TaintLaunderingError(
            f"action requires {required.name} but prompt closure floor is {worst.name}; "
            f"tainted spans present: {sorted(set().union(*(s.taint_ids for s in prompt_spans)))}"
        )
