# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-provenance-taint-labels-through-tool-outputs-but-a-downstream-tool-re-serializes-a-tainted-substring-as-an-un.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-provenance-taint-labels-through-tool-outputs-but-a-downstream-tool-re-serializes-a-tainted-substring-as-an-un.warrant.json
# Markdown SHA-256:   3010656b05e4e85e4192778a38f0bb8bc399c29b405f0d200238a9a967938823
# Code AST SHA-256:   934f5ad1d0ccb010cbd88159b5d71d451a8d001726ca1384a61491427ca3aab1
# Verified Classes:   TaintLaunderingError, LabeledField, Declassification
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional

TRUSTED = 0
TAINTED = 1  # lattice: join = max


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output field is promoted to trusted without an
    explicit declassification record, or when derivation metadata is
    unverifiable."""


@dataclass
class LabeledField:
    value: object
    label: int
    derivation: Optional[List[str]] = None  # source span ids, or None if undeclared


@dataclass
class Declassification:
    span_id: str
    actor: str
    policy: str


def join(*labels: int) -> int:
    return max(labels) if labels else TRUSTED


def gate_side_effect(
    tool_name: str,
    args: Dict[str, LabeledField],
    declassifications: List[Declassification],
) -> None:
    """Refuse any side-effecting call whose argument fields are tainted,
    unless each tainted field has an authority declassification."""
    declassified_spans = {d.span_id for d in declassifications}
    for name, f in args.items():
        if f.label == TAINTED:
            if f.derivation is None:
                raise TaintLaunderingError(
                    f"{tool_name}: field {name!r} is tainted with undeclared "
                    f"derivation; cannot verify declassification"
                )
            covered = all(span in declassified_spans for span in f.derivation)
            if not covered:
                raise TaintLaunderingError(
                    f"{tool_name}: field {name!r} tainted via {f.derivation}; "
                    f"no authority declassification for span(s) "
                    f"{[s for s in f.derivation if s not in declassified_spans]}"
                )


def propagate_tool_output(
    tool_name: str,
    tool_trust: int,
    arg_fields: Dict[str, LabeledField],
    raw_output: Dict[str, object],
    declared_derivation: Optional[Dict[str, List[str]]],
) -> Dict[str, LabeledField]:
    """Apply the derivation lattice. Pessimistic default: if derivation is
    undeclared, every output field inherits the join of all arg labels."""
    arg_join = join(*[f.label for f in arg_fields.values()])
    out: Dict[str, LabeledField] = {}
    for name, value in raw_output.items():
        if declared_derivation is None or name not in declared_derivation:
            # undeclared -> pessimistic: tainted if any arg was tainted
            out[name] = LabeledField(value, join(tool_trust, arg_join), None)
            continue
        spans = declared_derivation[name]
        # verify declared spans actually exist among arg derivations
        known = {s for f in arg_fields.values() for s in (f.derivation or [])}
        unverifiable = [s for s in spans if s not in known]
        if unverifiable:
            raise TaintLaunderingError(
                f"{tool_name}: field {name!r} claims derivation from unknown "
                f"spans {unverifiable}; treating as lying oracle"
            )
        src_labels = [
            f.label for f in arg_fields.values()
            if any(s in (f.derivation or []) for s in spans)
        ]
        out[name] = LabeledField(
            value, join(tool_trust, *src_labels) if src_labels else tool_trust, spans
        )
    return out


# --- failure trace reproduction ---
if __name__ == "__main__":
    web = LabeledField("...contact ops@acme.example...", TAINTED, ["span:web:1"])
    summary = propagate_tool_output(
        "summarize", TRUSTED, {"text": web},
        {"summary": "s", "entities": {"contact": "ops@acme.example"}},
        declared_derivation=None,  # summarizer publishes no span metadata
    )
    # pessimistic rule marks entities.contact tainted -> gate fires
    try:
        gate_side_effect(
            "send_email",
            {"to": summary["entities"], "body": LabeledField("hi", TRUSTED)},
            declassifications=[],
        )
    except TaintLaunderingError as e:
        print("BLOCKED:", e)
