# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-propagation-across-a-re-signed-capability-token-during-multi-hop-tool-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-propagation-across-a-re-signed-capability-token-during-multi-hop-tool-delegation.warrant.json
# Markdown SHA-256:   8c9aac7fc9fe9e79010ed90bd9ab384f528cab49627dfc3588e3bbd589dadfbc
# Code AST SHA-256:   38a6a27b97b0aeebd640ae67e7cbfa7f2a4b781ff8b6dc5eb9b1b267cbe8c4af
# Verified Classes:   TaintLattice, TaintLaunderingError, LabeledValue
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Dict


class TaintLattice(IntEnum):
    TRUSTED = 0
    USER = 1
    MODEL_GENERATED = 2
    TOOL_OUTPUT = 3
    UNTRUSTED_WEB = 4


class TaintLaunderingError(RuntimeError):
    """Raised when a delegation re-mint would produce a label less restrictive
    than the incoming label for the same logical value."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    label: TaintLattice


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


def remint_for_delegation(
    incoming: Dict[str, LabeledValue],
    outgoing_raw: Dict[str, str],
    default_if_unattributed: TaintLattice = TaintLattice.MODEL_GENERATED,
) -> Dict[str, LabeledValue]:
    """Re-mint labels for a delegation edge.

    Invariant: for every key present in both maps, out.label >= in.label.
    Unattributed outgoing args get the conservative default, never USER.
    """
    if default_if_unattributed < TaintLattice.MODEL_GENERATED:
        # A default of USER or TRUSTED is unsound: model output is a function
        # of the full context, including any untrusted content it read.
        raise TaintLaunderingError(
            f"unsound default {default_if_unattributed.name}; "
            "unattributed args must default to MODEL_GENERATED or stricter"
        )

    out: Dict[str, LabeledValue] = {}
    for key, raw in outgoing_raw.items():
        if key in incoming:
            in_label = incoming[key].label
            # Even if the delegating agent claims the value is "clean",
            # the runtime joins with the incoming label. No narrowing.
            out_label = join(in_label, TaintLattice.MODEL_GENERATED)
            if out_label < in_label:
                raise TaintLaunderingError(
                    f"delegation edge narrowed taint on {key!r}: "
                    f"{in_label.name} -> {out_label.name}"
                )
            out[key] = LabeledValue(raw, out_label)
        else:
            out[key] = LabeledValue(raw, default_if_unattributed)
    return out


def authorize_sink(tool: str, args: Dict[str, LabeledValue],
                   clearance: Dict[str, TaintLattice]) -> None:
    if tool not in clearance:
        raise TaintLaunderingError(f"no clearance declared for sink {tool!r}")
    cap = clearance[tool]
    for key, lv in args.items():
        if lv.label > cap:
            raise TaintLaunderingError(
                f"sink {tool!r} rejected arg {key!r}: "
                f"label {lv.label.name} exceeds clearance {cap.name}"
            )
