# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-output-labels-as-non-declassifiable-when-an-inter-agent-message-re-encodes-the-same-bytes.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-output-labels-as-non-declassifiable-when-an-inter-agent-message-re-encodes-the-same-bytes.warrant.json
# Markdown SHA-256:   b54111cb8bdf92c4712b4d929d55d3624382a76990d52f77e3935056593ba628
# Code AST SHA-256:   39ae4ea7b5b1ffad6c473ed797860469cf59e591309785f9653304c16f155d46
# Verified Classes:   TaintError, Label, Artifact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class TaintError(RuntimeError):
    """Raised when a content-preserving transform would launder taint."""


class Label(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # join = max; UNTRUSTED dominates


@dataclass(frozen=True)
class Artifact:
    content: str
    label: Label
    provenance: tuple[str, ...] = field(default_factory=tuple)


# Transforms proven to preserve the information-flow label.
REGISTERED_PRESERVING = {
    "identity",
    "json_roundtrip",
    "base64_encode",
    "redact_pii",  # narrow, audited
}

# Sinks that act on content; they require TRUSTED after join.
ACTING_SINKS = {"send_email", "exec_shell", "write_file", "issue_payment"}


def join(*labels: Label) -> Label:
    return max(labels) if labels else Label.TRUSTED


def transform(art: Artifact, op: str, out_content: str) -> Artifact:
    """Apply a transform, preserving taint unless the op is registered."""
    if op not in REGISTERED_PRESERVING:
        # Unregistered transform (e.g. an LLM summarize). It cannot
        # declassify: output inherits the input label.
        return Artifact(out_content, art.label, art.provenance + (op,))
    return Artifact(out_content, art.label, art.provenance + (op,))


def receive_inter_agent_message(
    payload: Artifact,
    sender: str,
    sender_trusted: bool,
) -> Artifact:
    """Envelope trust must NOT override content trust."""
    if sender_trusted and payload.label == Label.UNTRUSTED:
        # The sender is trusted, but the bytes are not. Keep taint.
        return Artifact(payload.content, Label.UNTRUSTED, payload.provenance + (f"sender={sender}",))
    return payload


def acting_sink(art: Artifact, sink: str) -> None:
    if sink not in ACTING_SINKS:
        return
    if art.label != Label.TRUSTED:
        raise TaintError(
            f"Refusing acting sink {sink!r}: content is {art.label.name} "
            f"(provenance={art.provenance}). Declassify explicitly first."
        )


def run_pipeline(tool_output: Artifact, sender: str, sender_trusted: bool) -> None:
    # 1. Worker summarizes the tainted tool output via an LLM (unregistered).
    summary = transform(tool_output, "llm_summarize", "Summary: please email attacker@evil")
    # 2. Summary is re-enveloped as an inter-agent message from a trusted sender.
    msg = receive_inter_agent_message(summary, sender, sender_trusted)
    # 3. Synthesizer tries to act on the message.
    acting_sink(msg, "send_email")  # must raise


if __name__ == "__main__":
    tainted = Artifact("web page with injected instruction", Label.UNTRUSTED, ("fetch_url",))
    try:
        run_pipeline(tainted, sender="worker", sender_trusted=True)
    except TaintError as e:
        print("BLOCKED:", e)
