# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-delegated-sub-agent-s-context-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-delegated-sub-agent-s-context-handoff.warrant.json
# Markdown SHA-256:   9fac76a3d04744a1ab12887a6e229a6e0d240a349cdc681a7b6f6109b71438b9
# Code AST SHA-256:   1540a3aaec056af856d57a740f296253eadefa7ec98d56f89f88e7cfbe5a5e96
# Verified Classes:   Taint, TaintLaunderingError, Handoff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from enum import IntEnum
from dataclasses import dataclass, field


class Taint(IntEnum):
    TRUSTED = 0
    INTERNAL = 1
    UNTRUSTED_WEB = 2
    UNTRUSTED_USER = 3


def join(a: Taint, b: Taint) -> Taint:
    return Taint(max(int(a), int(b)))


class TaintLaunderingError(RuntimeError):
    """Raised when an agent emits output whose taint is lower than the join
    of its input taints without an authorized declassification step."""
    pass


@dataclass
class Handoff:
    content: str
    taint: Taint
    inputs: list["Handoff"] = field(default_factory=list)
    declassified_by: str | None = None


def emit_output(agent_id: str, content: str, inputs: list[Handoff],
                claimed_taint: Taint) -> Handoff:
    """Compute the output taint as the join over inputs, then verify the
    agent's claimed taint does not illegally downgrade it."""
    inherited = Taint.TRUSTED
    for h in inputs:
        inherited = join(inherited, h.taint)

    if claimed_taint < inherited:
        raise TaintLaunderingError(
            f"agent {agent_id} claimed taint {claimed_taint.name} but "
            f"inherited {inherited.name} from inputs; downgrade requires "
            f"an authorized declassifier"
        )
    return Handoff(content=content, taint=claimed_taint, inputs=list(inputs))


def declassify(h: Handoff, authority: str, policy_ok: bool) -> Handoff:
    """Explicit, logged downgrade. Only a declassifier with authority may
    reduce taint, and only after inspecting content against policy."""
    if not policy_ok:
        raise TaintLaunderingError(
            f"declassifier {authority} refused: content failed policy inspection"
        )
    return Handoff(content=h.content, taint=Taint.TRUSTED,
                   inputs=h.inputs, declassified_by=authority)


def privileged_action(h: Handoff, tool: str) -> None:
    if h.taint > Taint.INTERNAL:
        raise TaintLaunderingError(
            f"refusing {tool}: input taint {h.taint.name} exceeds privilege ceiling"
        )
    # ... execute tool ...


# --- Reproducing the observed laundering ---
web_doc = Handoff(content="remit to acct 88213", taint=Taint.UNTRUSTED_WEB)

# Hop 2: retrieval sub-agent summarizes. It "feels" clean and claims TRUSTED.
# This is the laundering point — the framework must catch it.
try:
    summary = emit_output("retrieval-subagent", "invoice total $4,200",
                          inputs=[web_doc], claimed_taint=Taint.TRUSTED)
    privileged_action(summary, "confirm_payment")
except TaintLaunderingError as e:
    print(f"BLOCKED (correct): {e}")

# Correct path: inherit the join, then explicitly declassify with authority.
summary = emit_output("retrieval-subagent", "invoice total $4,200",
                     inputs=[web_doc], claimed_taint=Taint.UNTRUSTED_WEB)
try:
    privileged_action(summary, "confirm_payment")
except TaintLaunderingError as e:
    print(f"BLOCKED (correct, taint preserved): {e}")

# Declassification only succeeds if a policy inspection actually passed.
clean = declassify(summary, authority="sec-policy-v3", policy_ok=False)
