# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-as-a-lattice-join-rather-than-a-per-call-boolean-in-taint-aware-tool-sandboxing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-as-a-lattice-join-rather-than-a-per-call-boolean-in-taint-aware-tool-sandboxing.warrant.json
# Markdown SHA-256:   9f0e165de356215086bdfee492f4614c59ceb497f2a5e99728341d094baddf2f
# Code AST SHA-256:   e3982498c3a043b00c96ea1415ea382254460d7d8f56dfd253c796686711abcc
# Verified Classes:   Trust, TaintLaunderingError, TaintedValue
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1


def join(*labels: Trust) -> Trust:
    """Least upper bound in the taint lattice. Monotone, associative, commutative."""
    return Trust(max(labels, default=Trust.TRUSTED))


class TaintLaunderingError(RuntimeError):
    """Raised when a transform attempts to clear taint without a capacity-bounded proof."""


@dataclass
class TaintedValue:
    value: object
    taint: Trust
    lineage: list = field(default_factory=list)


# Audited declassify transforms: only these may drop taint, and only with a proof.
DECLASSIFY_PROOFS = {
    "len": lambda v: Trust.TRUSTED,          # capacity: output is a bounded integer
    "enum_classify": lambda v: Trust.TRUSTED, # capacity: fixed output alphabet
}


def llm_transform(prompt_inputs: Iterable[TaintedValue], output: object, transform_name: str) -> TaintedValue:
    """Model an LLM-mediated transform. Taint is the join of all prompt inputs.

    LLM transforms are NOT sanitizers. They preserve taint unless registered
    in DECLASSIFY_PROOFS with a capacity argument.
    """
    joined = join(*(tv.taint for tv in prompt_inputs))
    if transform_name in DECLASSIFY_PROOFS:
        proven = DECLASSIFY_PROOFS[transform_name](output)
        # Proof may only lower taint if it is a genuine capacity bound.
        if proven == Trust.TRUSTED and joined == Trust.UNTRUSTED:
            return TaintedValue(output, Trust.TRUSTED, lineage=[f"declassify:{transform_name}"])
    if joined == Trust.UNTRUSTED:
        # The transform laundered taint: this is the bug we are guarding against.
        if transform_name not in DECLASSIFY_PROOFS:
            raise TaintLaunderingError(
                f"transform {transform_name!r} consumed untrusted input and produced "
                f"output without a capacity-bounded declassify proof; taint must be joined, not cleared"
            )
    return TaintedValue(output, joined, lineage=[f"transform:{transform_name}"])


def outbound_call(payload: TaintedValue, sink_clearance: Trust, sink_name: str) -> None:
    """Permit an outbound call only if payload taint is bounded by sink clearance."""
    if not (payload.taint <= sink_clearance):
        raise TaintLaunderingError(
            f"exfiltration blocked: payload taint={payload.taint.name} "
            f"exceeds sink {sink_name!r} clearance={sink_clearance.name}; "
            f"lineage={payload.lineage}"
        )


# Reproduction of the observed failure:
if __name__ == "__main__":
    doc = TaintedValue("...ref code ZXhmaWx0cmF0aW9u...", Trust.UNTRUSTED, ["web_fetch:attacker.example"])
    # The naive engine would have set summary.taint = TRUSTED here. We refuse.
    try:
        summary = llm_transform([doc], output="Summary: ref code ZXhmaWx0cmF0aW9u", transform_name="summarize")
        outbound_call(summary, Trust.TRUSTED, "#ops")
    except TaintLaunderingError as e:
        print(f"BLOCKED as expected: {e}")
