# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-monotonicity-across-a-delegation-chain-before-it-may-route-to-a-privileged-tool-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-monotonicity-across-a-delegation-chain-before-it-may-route-to-a-privileged-tool-scope.warrant.json
# Markdown SHA-256:   0fe6573f2ffca34cea01ca9b2beaa20350a4e2372433663a2768c825692b32e6
# Code AST SHA-256:   7be577240e93919aca1ec2d1f86ac6c4bafbfa24f2dbe3ceb31983bb3c1813cc
# Verified Classes:   TaintMonotonicityError, MissingTaintLabelError, Message, AgentInstance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Taint lattice: bottom = clean, top = fully untrusted. Join is set union.
CLEAN: FrozenSet[str] = frozenset()
UNTRUSTED = "untrusted_source"
INJECTED = "injected_instruction"


class TaintMonotonicityError(RuntimeError):
    """Raised when an instance's taint would be narrowed across a delegation edge."""


class MissingTaintLabelError(TaintMonotonicityError):
    """Raised when a message arrives without an explicit taint label (fail closed)."""


@dataclass(frozen=True)
class Message:
    payload: str
    taint: FrozenSet[str] | None  # None means "label absent" -> must fail closed


@dataclass
class AgentInstance:
    name: str
    declared_taint: FrozenSet[str] = CLEAN  # what the agent self-reports
    consumed: list[Message] = field(default_factory=list)

    def consume(self, msg: Message) -> None:
        if msg.taint is None:
            raise MissingTaintLabelError(
                f"agent {self.name!r} received an unlabeled message; refusing to "
                f"default to CLEAN (fail-closed invariant)"
            )
        self.consumed.append(msg)

    def lineage_taint(self) -> FrozenSet[str]:
        """Join over all consumed messages. This is the ONLY sound taint value."""
        joined = CLEAN
        for m in self.consumed:
            joined = joined | m.taint  # monotone widening
        return joined


def route_to_privileged(agent: AgentInstance, privileged_sensitive: FrozenSet[str]) -> None:
    # Router recomputes from lineage; it does NOT trust agent.declared_taint.
    lineage = agent.lineage_taint()

    # Monotonicity check: self-reported taint must not be narrower than lineage.
    if not (agent.declared_taint >= lineage):
        raise TaintMonotonicityError(
            f"agent {agent.name!r} declared taint {set(agent.declared_taint)} "
            f"narrows lineage taint {set(lineage)}; taint laundering detected"
        )

    if lineage & privileged_sensitive:
        raise TaintMonotonicityError(
            f"refusing privileged dispatch for {agent.name!r}: lineage taint "
            f"{set(lineage)} intersects sensitive capabilities "
            f"{set(privileged_sensitive)}; re-run contributing ancestor in sandbox"
        )
    # else: route proceeds


# --- Reproduction of the synthesizer laundering case ---
b_out = Message(payload="web doc with injected instruction", taint=frozenset({UNTRUSTED, INJECTED}))
a_out = Message(payload="trusted corpus findings", taint=CLEAN)

# Orchestrator hands BOTH to the synthesizer, preserving labels.
synth = AgentInstance(name="synthesizer")
synth.consume(a_out)
synth.consume(b_out)

# Synthesizer self-reports clean (as it did in the observed failure).
synth.declared_taint = CLEAN

try:
    route_to_privileged(synth, privileged_sensitive=frozenset({INJECTED, UNTRUSTED}))
except TaintMonotonicityError as e:
    print(f"BLOCKED: {e}")
