# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-tainted-tool-output-silently-lose-its-taint-when-it-crosses-a-serialization-boundary-in-agentic-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-tainted-tool-output-silently-lose-its-taint-when-it-crosses-a-serialization-boundary-in-agentic-pipelines.warrant.json
# Markdown SHA-256:   19a57cddcf74fce8f5a74d87f8216ad1dc85601325c1487eb62339773596e43a
# Code AST SHA-256:   6e84608eb9056af0b37355438ebef47912d77d0e37b9377305c9ed978c964353
# Verified Classes:   TaintEnvelopeMissingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintEnvelopeMissingError(RuntimeError):
    """Raised when a value crosses a boundary without a provenance envelope."""
    pass


TRUST_LEVELS = ("trusted", "external", "unknown")


def propagate_across_boundary(value, envelope, producer_taint):
    """
    Enforce the envelope-completeness invariant at a serialization boundary.

    A value may only be treated as clean if its envelope explicitly carries
    a trust level. Absence of an envelope is taint-unknown, never clean.
    """
    if envelope is None or "trust" not in envelope:
        # Fail closed: do not silently default to trusted.
        raise TaintEnvelopeMissingError(
            f"value from producer={producer_taint!r} crossed boundary "
            f"without a trust envelope; refusing to label it clean"
        )

    trust = envelope["trust"]
    if trust not in TRUST_LEVELS:
        raise TaintEnvelopeMissingError(
            f"unrecognized trust level {trust!r} in envelope"
        )

    # Derived values inherit the most restrictive of producer and envelope.
    rank = {lvl: i for i, lvl in enumerate(TRUST_LEVELS)}
    effective = max(trust, producer_taint, key=lambda l: rank[l])
    return {"value": value, "trust": effective}


def build_command(summary, summary_envelope, summary_producer_taint):
    """Sink-side check: privileged construction requires a verified envelope."""
    labeled = propagate_across_boundary(
        summary, summary_envelope, summary_producer_taint
    )
    if labeled["trust"] != "trusted":
        raise TaintEnvelopeMissingError(
            f"refusing to build command from taint={labeled['trust']!r} input"
        )
    return ["sh", "-c", labeled["value"]]
