# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-sanitizer-tool-that-re-emits-injected-content-in-a-new-provenance-class.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-sanitizer-tool-that-re-emits-injected-content-in-a-new-provenance-class.warrant.json
# Markdown SHA-256:   b97a1d14aa738a414fea6fcbb1e7af79fa26f8a78caba8ca991b1084af51d8f4
# Code AST SHA-256:   d609ef94bbcae61cc6bc3a71ee85ba016393a13c251a8c5c6fc2755bc5304e23
# Verified Classes:   TaintLaunderingError, LineageUnreconstructibleError, LabeledValue
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output's declared labels do not cover its inputs' labels."""


class LineageUnreconstructibleError(RuntimeError):
    """Raised when a value's provenance cannot be traced to labeled inputs."""


@dataclass(frozen=True)
class LabeledValue:
    value_id: str
    provenance: str
    labels: frozenset[str]
    derived_from: tuple[str, ...] = ()


# Tool registry: which classes a tool is permitted to *declassify* with a proof
# obligation. Summarizers are absent by design -- they derive, they do not declassify.
DECLASSIFIERS: dict[str, frozenset[str]] = {
    "schema_validator_closed_enum": frozenset({"untrusted:web", "untrusted:user"}),
    "numeric_parser": frozenset({"untrusted:web", "untrusted:user"}),
}
# Tools that transform content without discharging any label.
DERIVERS: frozenset[str] = frozenset({"summarize_document", "html_to_text", "json_reserialize"})


def admit_tool_output(
    output: LabeledValue,
    label_index: dict[str, LabeledValue],
    tool_name: str,
) -> LabeledValue:
    """Gate an incoming tool result before it enters the reasoning context.

    Enforces: labels(output) superset-of union(labels(inputs)) for all inputs,
    minus only classes the tool is registered to declassify.
    """
    if not output.derived_from:
        # No declared lineage. Fail closed: cannot prove safety.
        raise LineageUnreconstructibleError(
            f"value {output.value_id} from tool {tool_name} declares no derived_from; "
            "cannot reconstruct lineage, admitting as untrusted"
        )

    try:
        inputs = [label_index[vid] for vid in output.derived_from]
    except KeyError as exc:
        raise LineageUnreconstructibleError(
            f"value {output.value_id} references unknown input {exc.args[0]}"
        ) from exc

    inherited: set[str] = set()
    for inp in inputs:
        inherited |= inp.labels

    if tool_name in DERIVERS:
        # Derivers must preserve every inherited label.
        missing = inherited - set(output.labels)
        if missing:
            raise TaintLaunderingError(
                f"tool {tool_name} dropped labels {sorted(missing)} on value "
                f"{output.value_id}; declared={sorted(output.labels)}, "
                f"inherited={sorted(inherited)}"
            )
        return output

    if tool_name in DECLASSIFIERS:
        permitted = DECLASSIFIERS[tool_name]
        undeclared = inherited - permitted - set(output.labels)
        if undeclared:
            raise TaintLaunderingError(
                f"tool {tool_name} declassified classes it is not registered for: "
                f"{sorted(undeclared)} on value {output.value_id}"
            )
        return output

    # Unknown tool: fail closed, treat as deriver with full inheritance required.
    missing = inherited - set(output.labels)
    if missing:
        raise TaintLaunderingError(
            f"unregistered tool {tool_name} dropped labels {sorted(missing)} on "
            f"value {output.value_id}"
        )
    return output
