# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-sanitized-tool-arguments-when-the-sanitizer-and-the-tool-disagree-on-the-taint-lattice.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-sanitized-tool-arguments-when-the-sanitizer-and-the-tool-disagree-on-the-taint-lattice.warrant.json
# Markdown SHA-256:   1e95c7a3cef2d6c12dea848e78be1d8fd4b9577d4036209168a6271685a9335b
# Code AST SHA-256:   113710e367599ba11e2814800cf182cc276d131c56468913e8fb5e7f6aa70504
# Verified Classes:   TaintAxis, Level, TaintLaunderingError, Label, ToolPrecondition
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, FrozenSet


class TaintAxis(Enum):
    PATH_CONTROL = "PATH_CONTROL"
    INSTRUCTION = "INSTRUCTION"
    SHELL_METACHARACTER = "SHELL_METACHARACTER"
    SQL_FRAGMENT = "SQL_FRAGMENT"


class Level(Enum):
    LOW = 0
    UNKNOWN = 1
    HIGH = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a sanitizer emits a label that drops an axis the gate requires,
    or when a gate would admit a value on an axis that was never assigned."""


@dataclass(frozen=True)
class Label:
    axes: Dict[TaintAxis, Level]

    def has(self, axis: TaintAxis) -> bool:
        return axis in self.axes


@dataclass(frozen=True)
class ToolPrecondition:
    name: str
    axes: FrozenSet[TaintAxis]
    thresholds: Dict[TaintAxis, Level]


def sanitize_path_only(incoming: Label) -> Label:
    # Correct behavior: reduce PATH_CONTROL, carry every other axis through verbatim.
    out = dict(incoming.axes)
    if TaintAxis.PATH_CONTROL in out:
        out[TaintAxis.PATH_CONTROL] = Level.LOW
    return Label(axes=out)


def sanitize_projection_bug(incoming: Label) -> Label:
    # The observed failure: emits a fresh label describing only what it validated.
    return Label(axes={TaintAxis.PATH_CONTROL: Level.LOW})


def check_sanitizer_closure(before: Label, after: Label) -> None:
    missing = {a for a in before.axes if not after.has(a)}
    if missing:
        raise TaintLaunderingError(
            f"sanitizer dropped axes {sorted(a.value for a in missing)}; "
            f"omission is indistinguishable from laundering at the gate"
        )


def gate(tool: ToolPrecondition, label: Label) -> bool:
    for axis in tool.axes:
        if not label.has(axis):
            raise TaintLaunderingError(
                f"tool {tool.name!r} requires axis {axis.value} but label omits it; "
                f"absent != LOW, gate must fail closed"
            )
        if label.axes[axis] is Level.UNKNOWN:
            raise TaintLaunderingError(
                f"tool {tool.name!r} axis {axis.value} is UNKNOWN; fail closed"
            )
        if label.axes[axis].value > tool.thresholds[axis].value:
            return False
    return True


def run_pipeline() -> None:
    extracted = Label(axes={
        TaintAxis.PATH_CONTROL: Level.HIGH,
        TaintAxis.INSTRUCTION: Level.HIGH,
    })
    shell = ToolPrecondition(
        name="shell_runner",
        axes=frozenset({TaintAxis.PATH_CONTROL, TaintAxis.SHELL_METACHARACTER}),
        thresholds={TaintAxis.PATH_CONTROL: Level.LOW,
                    TaintAxis.SHELL_METACHARACTER: Level.LOW},
    )

    good = sanitize_path_only(extracted)
    check_sanitizer_closure(extracted, good)
    # Shell precondition includes SHELL_METACHARACTER, absent from label -> must deny.
    try:
        gate(shell, good)
    except TaintLaunderingError:
        pass  # expected: axis closure denies the call

    bad = sanitize_projection_bug(extracted)
    # This is the laundering: sanitizer dropped INSTRUCTION and never added SHELL.
    check_sanitizer_closure(extracted, bad)


if __name__ == "__main__":
    run_pipeline()
