# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-sanitizer-provenance-loss-when-mcp-tool-output-crosses-a-taint-laundering-boundary-inside-a-single-reasoning-step.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-sanitizer-provenance-loss-when-mcp-tool-output-crosses-a-taint-laundering-boundary-inside-a-single-reasoning-step.warrant.json
# Markdown SHA-256:   2112411aba07c76bba32c7ef4d309610ef9458bdbb673816d514fa0e34b039b5
# Code AST SHA-256:   c39a6899163c80b3254935fca53ef277b4fca3d38b5aa9a60b177b1b965fd276
# Verified Classes:   ProvenanceLaunderingError, SanitizerResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ProvenanceLaunderingError(RuntimeError):
    """Raised when an assembled payload's provenance does not cover its bytes."""
    pass


@dataclass(frozen=True)
class SanitizerResult:
    payload: dict
    label: str
    output_digest: str  # sha256 over canonical serialization of payload


def canonical_digest(obj: dict) -> str:
    blob = json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def assemble_context(
    sanitized: SanitizerResult,
    extra_fields: dict,
    extra_source_label: str,
) -> tuple[dict, str]:
    """
    Merge sanitized payload with extra fields fetched separately.
    Refuses to emit a single clean label over a composite object.
    """
    assembled = {**sanitized.payload, **extra_fields}

    # Invariant: the assembled object must equal the sanitizer's output,
    # OR the composite label must be the join of contributor labels.
    if canonical_digest(assembled) != sanitized.output_digest:
        if extra_source_label != sanitized.label:
            # Composite object: label is least-trusted contributor.
            joined = _join_labels(sanitized.label, extra_source_label)
            if joined != sanitized.label:
                # We are about to emit a label different from the sanitizer's.
                # This is only safe if downstream policy accepts `joined`.
                return assembled, joined
        # Same label but digest mismatch => bytes changed under a stable label.
        # This is laundering: refuse.
        raise ProvenanceLaunderingError(
            f"assembled digest {canonical_digest(assembled)} != "
            f"sanitizer output_digest {sanitized.output_digest}; "
            f"label {sanitized.label!r} would cover bytes it never saw"
        )

    return assembled, sanitized.label


_TRUST_ORDER = ["CLEAN", "INTERNAL", "EXTERNAL_UNTRUSTED"]


def _join_labels(a: str, b: str) -> str:
    return max(a, b, key=_TRUST_ORDER.index)
