# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-launder-a-delegated-capability-through-an-untainted-intermediary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-launder-a-delegated-capability-through-an-untainted-intermediary.warrant.json
# Markdown SHA-256:   c6aaba487b688f7aa2d4bbc3e7da917080813c841e9541e6002795cc348eac23
# Code AST SHA-256:   e566df019f5a9cedce970733a6ea16ac36a5d7187553614964e20ace6dd2cfad
# Verified Classes:   TaintBoundaryViolation, TaintResetError, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintBoundaryViolation(RuntimeError):
    """Raised when a delegation hop would launder taint past a capability's max_taint."""
    pass


class TaintResetError(RuntimeError):
    """Raised when a spawn or return would decrease taint along the chain."""
    pass


# Taint lattice: untrusted < internal < trusted, join = max.
TAINT_ORDER = {"trusted": 0, "internal": 1, "untrusted": 2}


def join(*labels: str) -> str:
    return max(labels, key=lambda l: TAINT_ORDER[l])


@dataclass
class Envelope:
    capability: str
    max_taint: str
    taint: str = "trusted"
    lineage: list = field(default_factory=list)


def delegate(parent: Envelope, child_cap: str, child_max_taint: str,
             consumed_tool_taint: str = "trusted",
             peer_msg_taint: str = "trusted") -> Envelope:
    effective = join(parent.taint, consumed_tool_taint, peer_msg_taint)
    if TAINT_ORDER[effective] > TAINT_ORDER[child_max_taint]:
        raise TaintBoundaryViolation(
            f"delegating {child_cap} at taint={effective} exceeds "
            f"max_taint={child_max_taint}; refuse rather than narrow silently"
        )
    child = Envelope(
        capability=child_cap,
        max_taint=child_max_taint,
        taint=effective,
        lineage=parent.lineage + [parent.capability],
    )
    # Invariant: taint is monotone non-decreasing across spawn.
    if TAINT_ORDER[child.taint] < TAINT_ORDER[parent.taint]:
        raise TaintResetError("spawn reset taint; cold-start amnesia laundering")
    return child


def invoke(env: Envelope, arg_taint: str) -> None:
    effective = join(env.taint, arg_taint)
    if TAINT_ORDER[effective] > TAINT_ORDER[env.max_taint]:
        raise TaintBoundaryViolation(
            f"call on {env.capability} with arg taint={effective} "
            f"> max_taint={env.max_taint}; lineage={env.lineage}"
        )
    # admitted: proceed with the joined label attached to the call
