# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-values-when-a-sub-agent-re-emits-poisoned-state-as-clean-output.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-values-when-a-sub-agent-re-emits-poisoned-state-as-clean-output.warrant.json
# Markdown SHA-256:   16621c3e8c80ff47d4da7736f6a12267c6280d9db5b99b8dc65b31dcc6539ed0
# Code AST SHA-256:   ff9c9dbad8d8edac54f83f197da44318355bd8eab04bee27150bbfcff35ca9e4
# Verified Classes:   TaintLaunderingError, TaintVocabularyError, Label, AgentCard, A2AResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a sub-agent response would strip or coerce provenance."""


class TaintVocabularyError(TaintLaunderingError):
    """Raised when a label is outside the closed vocabulary (fail closed)."""


CLOSED_LABELS = frozenset({"TRUSTED", "UNTRUSTED:external", "AUTHORED"})
ASSERTION_CAPS = frozenset({"summarize", "extract", "rank", "reason"})
TRANSFORM_CAPS = frozenset({"parse", "format", "retrieve"})


@dataclass(frozen=True)
class Label:
    tags: FrozenSet[str]

    def join(self, other: "Label") -> "Label":
        return Label(self.tags | other.tags)

    def is_trusted(self) -> bool:
        return self.tags == frozenset({"TRUSTED"})


@dataclass
class AgentCard:
    capability: str
    pure_transform: bool = False


@dataclass
class A2AResponse:
    payload: dict
    taint_field: FrozenSet[str] | None  # None == field absent


def propagate(
    card: AgentCard,
    input_label: Label,
    response: A2AResponse,
) -> Label:
    # 1. Validate the capability is known.
    if card.capability not in ASSERTION_CAPS | TRANSFORM_CAPS:
        raise TaintLaunderingError(
            f"unknown capability {card.capability!r}; cannot bound taint"
        )

    # 2. Fail closed if the envelope dropped provenance.
    if response.taint_field is None:
        inherited = input_label
    else:
        # 3. Closed vocabulary: never coerce unknown labels to TRUSTED.
        unknown = response.taint_field - CLOSED_LABELS
        if unknown:
            raise TaintVocabularyError(
                f"labels outside closed vocabulary: {sorted(unknown)}"
            )
        inherited = input_label.join(Label(frozenset(response.taint_field)))

    # 4. Pure transforms inherit exactly; assertions gain AUTHORED.
    if card.capability in TRANSFORM_CAPS and card.pure_transform:
        return inherited
    return inherited.join(Label(frozenset({"AUTHORED"})))


def guard_privileged_sink(label: Label, sink: str) -> None:
    if not label.is_trusted():
        raise TaintLaunderingError(
            f"refusing tainted value into privileged sink {sink!r}: "
            f"tags={sorted(label.tags)}"
        )


# --- Replay of the observed trace ---
if __name__ == "__main__":
    untrusted = Label(frozenset({"UNTRUSTED:external"}))
    summarizer = AgentCard(capability="summarize", pure_transform=False)

    # Sub-agent faithfully paraphrased the page; envelope carried no taint.
    resp = A2AResponse(
        payload={"entities": [{"name": "XK-4471", "type": "token"}]},
        taint_field=None,
    )
    out = propagate(summarizer, untrusted, resp)
    assert "AUTHORED" in out.tags and "UNTRUSTED:external" in out.tags

    try:
        guard_privileged_sink(out, "admin_override")
    except TaintLaunderingError as e:
        print(f"BLOCKED: {e}")

    # The "derived" coercion bug now raises instead of silently trusting.
    bad = A2AResponse(payload={}, taint_field=frozenset({"derived"}))
    try:
        propagate(summarizer, untrusted, bad)
    except TaintVocabularyError as e:
        print(f"PROTOCOL ERROR: {e}")
