# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-label-laundering-through-summarization-and-the-join-poin.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-label-laundering-through-summarization-and-the-join-poin.warrant.json
# Markdown SHA-256:   411f46f4c3e8049ca5f138f6e5ca5f8c271d67b207981b6e0a1452047bfe6d1e
# Code AST SHA-256:   2826948faa10e0c422e9593142d92a9973fa059b46c4e953fb8803b4d0efd08a
# Verified Classes:   Trust, Label, TaintCollapseError
# Defensive Guards:   3 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  # join is max; untrusted dominates


@dataclass(frozen=True)
class Label:
    trust: Trust
    provenance: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        return Label(
            trust=Trust(max(self.trust, other.trust)),
            provenance=self.provenance | other.provenance,
        )


class TaintCollapseError(RuntimeError):
    """Raised when a transformation would emit a label weaker than its input join
    without an audited declassification rule."""


AUDITED_SANITIZERS = {
    # name -> requires bounded (schema-validated) output surface
    "typed_extract_v1": True,
}


def transform_label(
    inputs: Iterable[Label],
    *,
    sanitizer: str | None = None,
    output_is_schema_bounded: bool = False,
) -> Label:
    joined = Label(Trust.TRUSTED)
    for lbl in inputs:
        joined = joined.join(lbl)

    if joined.trust is Trust.TRUSTED:
        return joined

    # Untrusted input: only an audited, schema-bounded sanitizer may declassify.
    if sanitizer is None:
        return joined  # carry taint forward (correct default)

    if sanitizer not in AUDITED_SANITIZERS:
        raise TaintCollapseError(
            f"unknown sanitizer {sanitizer!r}; cannot declassify untrusted join "
            f"from provenance {sorted(joined.provenance)}"
        )
    if AUDITED_SANITIZERS[sanitizer] and not output_is_schema_bounded:
        raise TaintCollapseError(
            f"sanitizer {sanitizer!r} requires schema-bounded output; free-text "
            f"summary cannot be declassified (provenance {sorted(joined.provenance)})"
        )
    return Label(Trust.TRUSTED, joined.provenance | {f"sanitized:{sanitizer}"})


def gate_privileged_action(action: str, context: Label) -> None:
    PRIVILEGED = {"send_email", "write_file", "execute", "http_post"}
    if action in PRIVILEGED and context.trust is Trust.UNTRUSTED:
        raise TaintCollapseError(
            f"refusing privileged action {action!r}: context tainted by "
            f"{sorted(context.provenance)}"
        )
