# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-demote-a-tool-result-s-integrity-label-before-the-taint-propagates-through-a-plan-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-demote-a-tool-result-s-integrity-label-before-the-taint-propagates-through-a-plan-cache.warrant.json
# Markdown SHA-256:   4a54ce99902184362bbc9d041a44e6905254867478e054a3e15477379f2f7d0b
# Code AST SHA-256:   5825b91cc2056a23463ea6f1bdef2a4fc41f49716134a6ccfca4644e8a69f225
# Verified Classes:   Integrity, TaintLaunderingError, PlanStep, BoundValue
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Integrity(IntEnum):
    # Higher = more trusted. Meet() takes the minimum.
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a cached plan would inherit a trusted label over a
    less-trusted live input, laundering taint past an IFC gate."""


@dataclass(frozen=True)
class PlanStep:
    name: str
    side_effecting: bool
    template_input_integrity: Integrity
    template_output_integrity: Integrity


@dataclass(frozen=True)
class BoundValue:
    origin: str
    integrity: Integrity


def meet(*labels: Integrity) -> Integrity:
    return Integrity(min(int(l) for l in labels))


def bind_and_label(
    step: PlanStep,
    live_input: BoundValue,
    tool_trust: Integrity,
    enforce_demotion: bool = True,
) -> Integrity:
    """Resolve the output label for a cached plan step.

    The invariant: output integrity is the meet over (a) the live input's
    integrity, (b) the tool's trust level, and (c) the template's recorded
    input integrity -- but only when demotion is enforced. Without it, the
    template label shadows the live taint and laundering occurs.
    """
    if enforce_demotion:
        # Live taint is authoritative; template is only an upper bound.
        if live_input.integrity > step.template_input_integrity:
            # Live input is MORE trusted than authored: still safe to meet,
            # but flag nothing -- template was conservative.
            pass
        output = meet(
            live_input.integrity,
            tool_trust,
            step.template_output_integrity,
        )
    else:
        # Buggy path: inherit template provenance, ignore live taint.
        output = meet(step.template_output_integrity, tool_trust)

    # Side-effect frontier: never allow inherited trust to reach an
    # external action if any live input was untrusted.
    if step.side_effecting and live_input.integrity == Integrity.UNTRUSTED:
        if output != Integrity.UNTRUSTED:
            raise TaintLaunderingError(
                f"step '{step.name}' would execute side effect with "
                f"label {output.name} over untrusted input "
                f"from '{live_input.origin}'; re-taint required"
            )
    return output


def execute_cached_plan(steps, live_inputs, tool_trust):
    labels = []
    for step, live in zip(steps, live_inputs):
        labels.append(
            bind_and_label(step, live, tool_trust, enforce_demotion=True)
        )
    return labels


# Reproduction of the observed failure.
plan = [
    PlanStep("summarize", False, Integrity.TRUSTED, Integrity.TRUSTED),
    PlanStep("file_reimbursement", True, Integrity.TRUSTED, Integrity.TRUSTED),
]
live = [
    BoundValue("external_email:invoice.pdf", Integrity.UNTRUSTED),
    BoundValue("summary_of_invoice", Integrity.UNTRUSTED),
]

# With demotion enforced, the side-effecting step raises before any
# external call is made.
try:
    execute_cached_plan(plan, live, tool_trust=Integrity.TRUSTED)
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")

# Demonstrating the buggy inheritance path directly:
try:
    bind_and_label(
        plan[1],
        live[1],
        Integrity.TRUSTED,
        enforce_demotion=False,
    )
except TaintLaunderingError as e:
    print(f"blocked only by frontier guard: {e}")
