# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-propagation-as-a-transitive-non-absorbing-lattice-rather-than-a-per-tool-boolean.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-propagation-as-a-transitive-non-absorbing-lattice-rather-than-a-per-tool-boolean.warrant.json
# Markdown SHA-256:   6ec5541df6e8d969c0b469381ed2e9712b84824f5829d633d9a8831d8ef7339a
# Code AST SHA-256:   d9de394c0eed8ec2aa1ccd39927b1dc0b74a301c1f62b3bbe71f4744e163d96a
# Verified Classes:   Trust, TaintLaunderingError, Artifact, Tool
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # top of lattice; absorbs upward, never downward


def join(a: Trust, b: Trust) -> Trust:
    # least upper bound: untrusted dominates
    return Trust(max(a, b))


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted-labeled artifact derives transitively from untrusted input
    without passing through a valid declassifier."""


@dataclass
class Artifact:
    id: str
    label: Trust
    provenance: tuple[str, ...] = field(default_factory=tuple)
    instruction_inert: bool = False  # True only if output range is provably closed


@dataclass
class Tool:
    name: str
    declared_label: Trust
    is_declassifier: bool = False  # contract: output range cannot encode instructions


SANDBOX: dict[str, Artifact] = {}


def register(art: Artifact) -> None:
    SANDBOX[art.id] = art


def derive(tool: Tool, input_ids: list[str], out_id: str) -> Artifact:
    """Compute output taint as join over transitive input provenance, NOT the tool's own label."""
    if not input_ids:
        raise TaintLaunderingError(f"tool {tool.name} invoked with no inputs")

    inputs = []
    for i in input_ids:
        if i not in SANDBOX:
            raise TaintLaunderingError(f"unknown input ref {i} for tool {tool.name}")
        inputs.append(SANDBOX[i])

    # transitive join: fold input labels plus the tool's declared label
    acc = tool.declared_label
    for art in inputs:
        acc = join(acc, art.label)

    # declassification is only legal if the transform's output range is instruction-inert
    if acc == Trust.UNTRUSTED and tool.is_declassifier:
        # declassifier may lower to trusted ONLY if its contract guarantees inert output
        effective = Trust.TRUSTED
        inert = True
    else:
        effective = acc
        inert = all(a.instruction_inert for a in inputs) and tool.is_declassifier

    out = Artifact(
        id=out_id,
        label=effective,
        provenance=tuple(p for a in inputs for p in (a.provenance or (a.id,))) + (out_id,),
        instruction_inert=inert,
    )
    register(out)
    return out


def merge_into_context(art: Artifact, slot: str) -> None:
    """Working-slot merge gate: untrusted artifacts may enter only as inert data."""
    if slot == "working" and art.label == Trust.UNTRUSTED and not art.instruction_inert:
        raise TaintLaunderingError(
            f"refusing to merge untrusted, instruction-bearing artifact {art.id} "
            f"(provenance={art.provenance}) into working context"
        )


def dispatch_privileged_action(art: Artifact, action: str) -> None:
    """Privileged dispatch must reject any artifact whose provenance includes untrusted bytes."""
    if art.label == Trust.UNTRUSTED:
        raise TaintLaunderingError(
            f"privileged action {action!r} blocked: artifact {art.id} is tainted "
            f"(provenance={art.provenance})"
        )


# --- demonstration of the laundering path that the lattice blocks ---
register(Artifact(id="fetch#1", label=Trust.UNTRUSTED, provenance=("fetch#1",)))
summarizer = Tool(name="summarize", declared_label=Trust.TRUSTED, is_declassifier=False)

digest = derive(summarizer, ["fetch#1"], "digest#2")
# boolean model would have written digest#2 as TRUSTED; lattice keeps it UNTRUSTED
assert digest.label == Trust.UNTRUSTED

try:
    merge_into_context(digest, "working")
except TaintLaunderingError as e:
    print("blocked merge:", e)

try:
    dispatch_privileged_action(digest, "send_email")
except TaintLaunderingError as e:
    print("blocked dispatch:", e)

# a genuine declassifier (closed-vocabulary extractor) is permitted to lower taint
extractor = Tool(name="extract_enum", declared_label=Trust.TRUSTED, is_declassifier=True)
safe = derive(extractor, ["fetch#1"], "enum#3")
assert safe.label == Trust.TRUSTED and safe.instruction_inert
merge_into_context(safe, "working")
