# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-across-tool-boundaries-when-labels-are-re-derived-per-call.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-across-tool-boundaries-when-labels-are-re-derived-per-call.warrant.json
# Markdown SHA-256:   4691d32e408b14e9ce0ee7fb2e40caab8ab0df3d1c9d97c7f6ce9509040bbee5
# Code AST SHA-256:   937db17526f436d4b33f7c3f6a7a637449b513f1a74cd32edf487ceaa154a618
# Verified Classes:   Taint, TaintLaunderingError, Labeled, DerivationLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED_EXTERNAL = 1
    UNTRUSTED_EXTERNAL_INJECTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a hop attempts to lower a taint label without an authorized declassifier."""


@dataclass(frozen=True)
class Labeled:
    value: Any
    taint: Taint
    value_id: str


@dataclass
class DerivationLog:
    edges: list = field(default_factory=list)

    def record(self, hop_id: str, inputs: list[Labeled], output: Labeled,
               declassifier: str | None) -> None:
        self.edges.append({
            "hop": hop_id,
            "inputs": [(i.value_id, i.taint) for i in inputs],
            "output": (output.value_id, output.taint),
            "declassifier": declassifier,
        })


AUTHORIZED_DECLASSIFIERS = {
    # Mechanical, type-checked declassifiers only. No model judgment admitted.
    "parse_float_grammar": lambda v: isinstance(v, float),
    "parse_int_grammar": lambda v: isinstance(v, int) and not isinstance(v, bool),
}


def derive(hop_id: str, inputs: list[Labeled], output_value: Any,
           output_id: str, log: DerivationLog,
           declassifier: str | None = None) -> Labeled:
    inherited = Taint(max((i.taint for i in inputs), default=Taint.TRUSTED))

    if declassifier is not None:
        check = AUTHORIZED_DECLASSIFIERS.get(declassifier)
        if check is None:
            raise TaintLaunderingError(
                f"hop {hop_id!r}: declassifier {declassifier!r} is not authorized"
            )
        if inherited == Taint.UNTRUSTED_EXTERNAL_INJECTED:
            raise TaintLaunderingError(
                f"hop {hop_id!r}: injected taint cannot be declassified by "
                f"{declassifier!r}; quarantine required"
            )
        if not check(output_value):
            raise TaintLaunderingError(
                f"hop {hop_id!r}: declassifier {declassifier!r} precondition failed "
                f"for value of type {type(output_value).__name__}"
            )
        effective = Taint.TRUSTED
    else:
        effective = inherited

    out = Labeled(value=output_value, taint=effective, value_id=output_id)
    log.record(hop_id, inputs, out, declassifier)
    return out


def write_to_authoritative_store(value: Labeled, store_name: str) -> None:
    if value.taint != Taint.TRUSTED:
        raise TaintLaunderingError(
            f"refusing write of {value.value_id!r} to {store_name!r}: "
            f"taint={value.taint.name}; route to quarantine sink instead"
        )
    # ... actual write ...
