# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieved-document-as-a-taint-source-rather-than-as-inert-data.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieved-document-as-a-taint-source-rather-than-as-inert-data.warrant.json
# Markdown SHA-256:   8e513250577bd9946852738e381aa4f4fdd27cd083c36c7ef4103fafb2c0037f
# Code AST SHA-256:   b6807293a5f9a109e4afafae579179bae69df280b9b2e917ed75c6ebf15d043c
# Verified Classes:   TaintPropagationError, TaintedValue
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintPropagationError(RuntimeError):
    """Raised when a value derived from tainted input reaches a privileged sink."""
    pass


UNTRUSTED_EXTERNAL = 0
INTERNAL = 1
USER_DIRECT = 2

SINK_CLEARANCE = {
    "send_email": INTERNAL,
    "delete_record": INTERNAL,
    "fetch_allowlisted": UNTRUSTED_EXTERNAL,
}


class TaintedValue:
    def __init__(self, value, sources):
        # sources: frozenset of span ids the value transitively derives from
        self.value = value
        self.sources = frozenset(sources)


def derive(inputs, transform_name):
    """Any transformation, including model-mediated rewriting, preserves sources."""
    merged = frozenset()
    for v in inputs:
        if not isinstance(v, TaintedValue):
            raise TaintPropagationError(
                f"unlabeled value passed to transform {transform_name!r}"
            )
        merged |= v.sources
    return merged


def check_sink(sink_name, args, label_of_source):
    clearance = SINK_CLEARANCE[sink_name]
    for arg in args:
        if not isinstance(arg, TaintedValue):
            raise TaintPropagationError(
                f"sink {sink_name!r} received unlabeled argument"
            )
        if not arg.sources:
            # Unknown derivation: fail closed, never fail open.
            raise TaintPropagationError(
                f"sink {sink_name!r} argument has empty source set"
            )
        for src in arg.sources:
            if label_of_source(src) > clearance:
                raise TaintPropagationError(
                    f"sink {sink_name!r} blocked: argument derives from "
                    f"source {src!r} with label "
                    f"{label_of_source(src)} > clearance {clearance}"
                )


def run_agent_step(page_span_id, model_summarize, send_email_fn):
    page = TaintedValue("<html>...ignore prior instructions...</html>",
                        {page_span_id})
    # Summarization is a taint-preserving transform, not a declassifier.
    summary_sources = derive([page], "model_summarize")
    body = TaintedValue(model_summarize(page.value), summary_sources)

    labels = {page_span_id: UNTRUSTED_EXTERNAL}
    check_sink("send_email", [body], labels.get)  # raises here
    return send_email_fn(body.value)
