# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-launder-an-untrusted-label-across-a-tool-boundary-that-returns-a-superset-of-the-requested-fields.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-launder-an-untrusted-label-across-a-tool-boundary-that-returns-a-superset-of-the-requested-fields.warrant.json
# Markdown SHA-256:   d5a7a023e076d5cc9fbdf1d19ca2a82ea1a84d44986622f560bb05c1d3147bcb
# Code AST SHA-256:   268c05a31a910e413b887696bff9521d57d50dce1219e48de44c6a4784bb669b
# Verified Classes:   TaintLaunderingError, Labeled, ToolContract
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a response field with no request match would inherit declared trust."""


@dataclass
class Labeled:
    value: Any
    label: str  # "trusted" | "untrusted"


@dataclass
class ToolContract:
    name: str
    declared_trust: str
    # fields the tool is allowed to promote to trusted without a request match
    promotion_rules: dict[str, str] = field(default_factory=dict)


def propagate(
    contract: ToolContract,
    request: dict[str, Labeled],
    response: dict[str, Any],
) -> dict[str, Labeled]:
    """Label every response field. Unmatched fields are untrusted unless explicitly promoted."""
    out: dict[str, Labeled] = {}
    request_labels = {k: v.label for k, v in request.items()}

    for key, value in response.items():
        if key in request_labels:
            out[key] = Labeled(value, request_labels[key])
            continue

        if key in contract.promotion_rules:
            rule = contract.promotion_rules[key]
            if rule == "independent":
                out[key] = Labeled(value, "trusted")
                continue
            if rule == "join_request":
                joined = "untrusted" if "untrusted" in request_labels.values() else "trusted"
                out[key] = Labeled(value, joined)
                continue
            raise TaintLaunderingError(
                f"tool {contract.name!r} field {key!r} has unknown promotion rule {rule!r}"
            )

        # No match, no promotion rule: fail closed.
        # Do NOT fall back to contract.declared_trust.
        if contract.declared_trust == "trusted":
            # The tool is authenticated, but this field is an unmatched derivation.
            # Refuse to launder it into trusted.
            raise TaintLaunderingError(
                f"tool {contract.name!r} returned unmatched field {key!r} "
                f"with declared trust {contract.declared_trust!r}; "
                f"add a promotion rule or strip the field"
            )
        out[key] = Labeled(value, "untrusted")

    return out
