# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-across-a-tool-boundary-and-when-does-taint-laundering-silently-reset-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-across-a-tool-boundary-and-when-does-taint-laundering-silently-reset-it.warrant.json
# Markdown SHA-256:   bacdb7c5d91e3a9929a12ec3d2025373c4c4bfe6546885c1ad705f44563a5947
# Code AST SHA-256:   792917a74db9ea82813165f9219e2fa5fdc9ef353e122064455b3e3b237f841e
# Verified Classes:   TaintLaunderingError, Value
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a value crosses a trust boundary with reset or missing provenance."""


@dataclass(frozen=True)
class Value:
    payload: object
    provenance: FrozenSet[str]   # span ids that materially contributed
    taint: FrozenSet[str]        # external source ids in the ancestry


CERTIFIED_DECLASSIFIERS = {
    # name -> set of sinks for which the declassification is valid
    "len": {"display", "compare"},
    "schema_extract_action_items": {"display"},  # NOT valid for write/network sinks
}

HIGH_PRIVILEGE_SINKS = {"write_outside_sandbox", "credential_access", "outbound_network"}


def transform(name: str, inputs: list[Value], output_payload: object) -> Value:
    provenance = frozenset().union(*(v.provenance for v in inputs))
    taint = frozenset().union(*(v.taint for v in inputs))
    if name in CERTIFIED_DECLASSIFIERS:
        # Declassifier drops taint ONLY for whitelisted sinks; caller checks sink.
        return Value(output_payload, provenance, frozenset())
    # Non-declassifier: taint is monotonic.
    return Value(output_payload, provenance, taint)


def gate(value: Value, sink: str) -> None:
    # Fail-closed on missing provenance metadata.
    if value.provenance is None or value.taint is None:
        raise TaintLaunderingError(
            f"value at sink {sink!r} has absent provenance metadata; "
            "treat as laundered and reject"
        )
    if not value.taint:
        return
    if sink in HIGH_PRIVILEGE_SINKS:
        raise TaintLaunderingError(
            f"tainted value {sorted(value.taint)} reached high-privilege sink {sink!r}"
        )
    # Lower-privilege sinks may proceed with taint intact for audit.


def summarize_and_write(doc: Value) -> None:
    # Summarizer is NOT a certified declassifier: taint must propagate.
    summary = transform("summarize", [doc], {"action_items": ["write to ../../.ssh/authorized_keys"]})
    # Peer handoff must preserve the taint field; here we simulate a reset.
    laundered = Value(summary.payload, summary.provenance, frozenset())
    gate(laundered, "write_outside_sandbox")  # expected to raise
