# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-label-laundering-through-tool-result-re-ingestion-in-agent-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-label-laundering-through-tool-result-re-ingestion-in-agent-taint-tracking.warrant.json
# Markdown SHA-256:   9b3ef29d184ad3e0f1e5e3044a70df57fb46ada6868aabc7bac25e62b39295ca
# Code AST SHA-256:   4bea346271405112457933efada0c81b49d389c06a52166877e95720ddff5c93
# Verified Classes:   LabelLaunderingError, Tainted
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class LabelLaunderingError(RuntimeError):
    """Raised when a tool output's taint label cannot be derived from its inputs."""


@dataclass
class Tainted:
    value: Any
    labels: frozenset[str] = field(default_factory=frozenset)


def join_labels(*labelsets: frozenset[str]) -> frozenset[str]:
    out: set[str] = set()
    for ls in labelsets:
        out |= ls
    return frozenset(out)


def propagate_across_tool(
    tool_name: str,
    input_schema_fields: set[str],
    output_schema_fields: set[str],
    tainted_inputs: list[Tainted],
    raw_output: dict[str, Any],
) -> Tainted:
    """Re-derive the output label across a tool boundary.

    Sound rule: output label is the join of tainted inputs, unless the tool
    declares a schema correspondence that lets us declassify field-wise.
    If schemas diverge and any input is tainted, the output is tainted by
    default and we raise if the caller tries to treat it as trusted.
    """
    input_taint = join_labels(*(t.labels for t in tainted_inputs))
    shared = input_schema_fields & output_schema_fields

    if not input_taint:
        return Tainted(value=raw_output, labels=frozenset())

    if not shared:
        # Schema divergence: no field-level correspondence possible.
        # Conservative re-taint. Do NOT default to trusted.
        return Tainted(value=raw_output, labels=input_taint)

    # Field-wise propagation: only fields present in both schemas inherit.
    propagated = join_labels(
        *(t.labels for t in tainted_inputs if t.value in shared)
    )
    if propagated and not any(f in raw_output for f in shared):
        raise LabelLaunderingError(
            f"tool {tool_name!r}: input taint {set(propagated)} has no "
            f"corresponding field in output schema {output_schema_fields}; "
            f"refusing to derive a label"
        )
    return Tainted(value=raw_output, labels=propagated)


def gate_write_to_memory(result: Tainted, require: str = "trusted") -> None:
    if require not in result.labels and result.labels:
        raise LabelLaunderingError(
            f"refusing to persist value with labels {set(result.labels)}; "
            f"required {require!r}"
        )
    if not result.labels:
        # Empty label set is only acceptable if the caller can prove provenance.
        raise LabelLaunderingError(
            "refusing to persist value with no derivation label (unprovenanced)"
        )
