# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-multi-hop-tool-call-dataflow-without-silently-laundering-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-multi-hop-tool-call-dataflow-without-silently-laundering-provenance.warrant.json
# Markdown SHA-256:   da9d070f1a60998e4bdf191fe2b5f0dd9007d7e27537870eea87026a079dc670
# Code AST SHA-256:   4c90435cad8d34e6708809e925ff6f5bd5c937884944cdfecf82166c42789095
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a dataflow hop would drop a taint label without a valid de-taint proof."""
    pass


NON_INFLUENTIAL_TRANSFORMS = frozenset({"hash_sha256", "byte_length", "exists_bool"})


def propagate_taint(
    input_envelope: dict,
    output_envelope: dict,
    transform_id: str,
    transform_kind: str,
    declassify_proof: dict | None = None,
) -> dict:
    """
    input_envelope:  {"value": ..., "taint": bool, "provenance": str}
    output_envelope: envelope as constructed by the orchestrator for the tool result
    transform_kind:  "copy_through" | "model_mediated" | "certified_non_influential"
    """
    if not input_envelope.get("taint", False):
        return output_envelope  # nothing to propagate

    if transform_kind == "certified_non_influential":
        if transform_id not in NON_INFLUENTIAL_TRANSFORMS:
            raise TaintLaunderingError(
                f"transform {transform_id!r} claims non-influence but is not on the "
                f"certified list; refusing to de-taint"
            )
        if declassify_proof is None:
            raise TaintLaunderingError(
                f"de-taint of {transform_id!r} requires a proof object binding the "
                f"transform implementation and model version"
            )
        output_envelope["taint"] = False
        output_envelope["declassify_proof"] = declassify_proof
        return output_envelope

    if transform_kind == "copy_through":
        # span-match must be supplied by the transform; absence = match failure
        spans = declassify_proof.get("matched_spans") if declassify_proof else None
        if not spans:
            # match failure must fail CLOSED, not default to trusted
            output_envelope["taint"] = True
            output_envelope["provenance"] = input_envelope["provenance"]
            output_envelope["taint_note"] = "copy_through_match_failed"
            return output_envelope
        output_envelope["taint"] = True
        output_envelope["provenance"] = input_envelope["provenance"]
        output_envelope["matched_spans"] = spans
        return output_envelope

    if transform_kind == "model_mediated":
        # unconditional propagation: dependence is not computable from output alone
        output_envelope["taint"] = True
        output_envelope["provenance"] = input_envelope["provenance"]
        output_envelope["taint_note"] = f"model_mediated:{transform_id}"
        return output_envelope

    raise TaintLaunderingError(
        f"unknown transform_kind {transform_kind!r}; cannot decide taint propagation"
    )


def enforce_sink_policy(envelope: dict, sink_id: str) -> None:
    if envelope.get("taint", False) and sink_id in {"write_record", "send_email", "execute"}:
        raise TaintLaunderingError(
            f"tainted value reached side-effecting sink {sink_id!r} with provenance "
            f"{envelope.get('provenance')!r}; refusing execution "
            f"(note={envelope.get('taint_note')!r})"
        )
