# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-taint-its-own-tool-output-after-an-mcp-server-returns-a-response-that-transitively-references-a-previously-sanitized-field.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-taint-its-own-tool-output-after-an-mcp-server-returns-a-response-that-transitively-references-a-previously-sanitized-field.warrant.json
# Markdown SHA-256:   a865fe5192bcdcb166ca4b3b2251ff785a2951674592beb0ff6001bf9291d6dc
# Code AST SHA-256:   30c7c6e0dc3049a4fb418e90bd46bc1310adc4bc223574d86fe4d43b0bb5113e
# Verified Classes:   TaintLaunderingError, TaintLabel, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a planner attempts to act on evidence that re-emerged
    from a previously sanitized field via a derivation server, without a
    byte-identical hash match."""
    pass


@dataclass
class TaintLabel:
    value_hash: str
    label: str  # "TRUSTED" | "UNTRUSTED"
    reemerged_from: Optional[str] = None  # hash of the sanitized ancestor, if any
    chain: tuple = field(default_factory=tuple)


class ProvenanceStore:
    def __init__(self):
        self._sanitized: dict[str, TaintLabel] = {}  # hash -> label at sanitization time

    def record_sanitized(self, raw: str, sanitized: str) -> TaintLabel:
        h = hashlib.sha256(sanitized.encode()).hexdigest()
        label = TaintLabel(value_hash=h, label="TRUSTED", reemerged_from=None, chain=())
        self._sanitized[h] = label
        return label

    def label_response(self, value: str, declared_transform: str) -> TaintLabel:
        h = hashlib.sha256(value.encode()).hexdigest()
        # Identity servers: byte-identical round-trip is safe to trust.
        if declared_transform == "identity" and h in self._sanitized:
            return self._sanitized[h]
        # Derivation servers: any hash match to a sanitized ancestor is a
        # re-emergence; non-matches are freshly untrusted with no ancestor.
        ancestor = self._sanitized.get(h)
        if ancestor is not None:
            return TaintLabel(value_hash=h, label="UNTRUSTED",
                              reemerged_from=ancestor.value_hash,
                              chain=ancestor.chain + (ancestor.value_hash,))
        # Heuristic re-emergence detection: if any sanitized value's hash
        # appears as a substring of the response, treat as derivative.
        for sh, sl in self._sanitized.items():
            if sh in value:
                return TaintLabel(value_hash=h, label="UNTRUSTED",
                                  reemerged_from=sh, chain=sl.chain + (sh,))
        return TaintLabel(value_hash=h, label="UNTRUSTED")


def plan_tool_call(store: ProvenanceStore, args: dict[str, str],
                   declared_transform: str) -> None:
    """Veto any tool call whose arguments include a value that re-emerged
    from a sanitized field without a byte-identical hash match."""
    for name, val in args.items():
        lab = store.label_response(val, declared_transform)
        if lab.reemerged_from is not None:
            raise TaintLaunderingError(
                f"argument {name!r} (hash {lab.value_hash[:12]}) re-emerged "
                f"from sanitized ancestor {lab.reemerged_from[:12]} via a "
                f"derivation path; refusing to execute. chain={lab.chain}"
            )
