# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-the-label-laundering-boundary-in-prompt-injection-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-the-label-laundering-boundary-in-prompt-injection-taint-tracking.warrant.json
# Markdown SHA-256:   e0f417c361e13de4c0b198fe2bbc57fc10ac0769704ff5d4264f818f50753165
# Code AST SHA-256:   21c42ffa634aae7c46d3de3a8b14cede3dee28dd97c6968bf18b80484dcb3d5f
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool result claims higher trust than its inputs permit."""
    pass


# Integrity lattice: lower is more restrictive.
UNTRUSTED = 0   # attacker-influenceable
INTERNAL = 1    # trusted-by-construction
TRUSTED = 2     # hermetic, signed


def join_labels(input_labels, tool_intrinsic_label, envelope_label):
    """Meet over integrity. Envelope may only lower trust, never raise it."""
    candidates = list(input_labels) + [tool_intrinsic_label]
    # Envelope is an untrusted hint: it can only restrict, so it acts as a cap.
    cap = min(candidates + [envelope_label])
    return min(candidates + [cap])


def label_tool_result(tool_name, input_labels, tool_intrinsic_label,
                      envelope_label, sink_is_egress, prior_label=None):
    joined = join_labels(input_labels, tool_intrinsic_label, envelope_label)

    # Laundering: envelope claimed more trust than the join permits.
    if envelope_label > joined:
        raise TaintLaunderingError(
            f"tool {tool_name!r} envelope claimed label {envelope_label} "
            f"but join over inputs {input_labels} and intrinsic "
            f"{tool_intrinsic_label} yields {joined}; refusing to honor envelope"
        )

    # Label instability: identical content observed with divergent labels.
    if prior_label is not None and prior_label != joined:
        raise TaintLaunderingError(
            f"tool {tool_name!r} label instability: prior={prior_label} "
            f"now={joined}; label is not content-derived"
        )

    if joined == UNTRUSTED and sink_is_egress:
        raise TaintLaunderingError(
            f"tool {tool_name!r} produced UNTRUSTED result routed to egress sink; "
            f"quarantine required"
        )

    return joined
