Python / uv workflow SDK

blue specification · 2026-10-31

Coding agents write deployment code directly; Terraform and Ansible are no longer the layer in between. The colors are the foundation for that code: three workflow SDKs, Green, Red and Blue, sharing one model in Clojure, TypeScript and Python. Blue supplies DAG execution, reusable subworkflows and layered advice. Applications own their CLI, validation, planning, reporting and durable state. PocketDeploy is the starter package built on it.

greenClojure / Babashka · canonical
redTypeScript / Bun
bluePython / uv · this page
Contents
  1. Philosophy
  2. Naming & the opts contract
  3. Steps and errors
  4. Workflows: wire_fn and next_fn
  5. Parallelism, fan-out & joins
  6. Subworkflows
  7. Advice
  8. YAML desired state & COLORS_PAR_*
  9. Application boundaries
  10. The example
  11. Testing
  12. API index

1. Philosophy

2. Naming & the opts contract

greenredblue
:green/exit"red/exit""blue/exit"
green.workflowred/workflowblue.workflow
:hello/file"hello/file""hello/file"

Opts is an open dict. blue reserves blue/* and blue.*/*; project state lives under namespace-like keys such as "hello/file".

KeyMeaning
"blue/exit"Integer outcome. Missing means success and is normalised to 0 after a step.
"blue/err"Error message when "blue/exit" is positive.
"blue/trace"Stack trace when a raised exception is converted.
"blue/step"Current step name, stamped before each step runs.
"blue/branches"Per-branch results at a join or collapsed failed fork.
"blue.workflow/inherited"Private advice-inheritance payload, stripped from public results.
Step input is frozen. The engine deep-freezes opts at each step boundary (FrozenDict, FrozenList; tuple and frozenset members recursively). Unsupported mutable values and custom instances fail before the step runs; callables stay usable. Return new dicts with {**opts, ...}. If a step raises, the failure is built from the frozen input, so partial mutation cannot leak.

3. Steps and errors

A step is a plain sync or async function (opts) -> opts, named by a namespaced string such as "hello/greet". The name anchors wiring, reporting, engine slices, joins and advice.

import asyncio
from blue.workflow import Opts, StepError


async def system(opts: Opts) -> Opts:
    proc = await asyncio.create_subprocess_exec(
        "uname", "-s", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    out, err = await proc.communicate()
    if proc.returncode:
        return {**opts, "blue/exit": proc.returncode, "blue/err": err.decode().strip()}
    return {**opts, "hello/system": out.decode().strip()}


def check(opts: Opts) -> Opts:
    if not opts.get("names"):
        raise StepError("names is required", exit=2)
    return opts

failed(opts) is true when (opts.get("blue/exit") or 0) > 0. Without a next_fn, a failed step has no successors and its branch halts.

4. Workflows: wire_fn and next_fn

from blue.workflow import run, step, workflow

wf = workflow(
    start="hello/system",  # required
    wire_fn=wire_fn,       # required static graph
    next_fn=next_fn,       # optional dynamic router
    end=None,              # optional inclusive slice boundary
)
result = await run(wf, {"hello/event": "create", "names": ["alice"]})

wire_fn — the static graph

wire_fn(step, run_opts) returns the step function followed by its default successors, or None for an unknown step. run_opts is the initial opts of the run, so the graph can depend on stable inputs such as "hello/event" but never on values produced during the run.

def wire_fn(step: str, run_opts: Opts):
    return {
        "hello/system": (system_step, "hello/greet"),
        "hello/greet": (greet_step, "hello/report"),
        "hello/report": (report_step,),
    }.get(step)

Several successors form a static fork. The same graph drives join scheduling, so keep the happy path visible in it.

next_fn — the dynamic router

next_fn(step, default_next, opts)  # -> iterable of (next_step, opts) pairs
def next_fn(step, default_next, opts):
    if (opts.get("blue/exit") or 0) > 0:
        return []
    if step == "hello/system":
        return [("hello/greet", {**opts, "hello/name": n}) for n in opts["names"]]
    return [(s, opts) for s in (default_next or [])]

Slices

end is inclusive: it runs, then the workflow stops. Set start and end when constructing the workflow; exposing them as CLI flags is an application decision.

5. Parallelism, fan-out & joins

Join detection. Convergence is by flat step name. The scheduler waits while another live branch can still reach the step through this run's static graph; dynamic detours invisible to wire_fn need explicit routing care. For a multi-step pipeline per fanned-out item, wrap it in step(sub_workflow) so the items do not join early.

6. Subworkflows

step(sub_workflow)
step(sub_workflow,
     in_fn=lambda opts: sub_opts,
     out_fn=lambda opts, sub_result: parent_result)

By default the child result becomes the parent step result, including its exit/error. An explicit out_fn must preserve or deliberately handle child failures. Application keys flow through the default input adapter. Advice inheritance survives an in_fn that rebuilds opts from scratch. Composition adds no persistent state or recovery journal.

7. Advice

Advice wraps step functions without changing the graph. Registries are immutable workflow values: adding or removing advice returns a new workflow.

from blue.workflow import advice_add, advice_add_all, advice_remove, advice_remove_all, advice_plan

wf2 = advice_add(wf, "hello/greet", "before-while", "hello/policy", allowed)
wf3 = advice_add_all(wf2, "around", "hello/timing", timing, {"depth": -50})
advice_plan(wf3, "hello/greet")   # the composed stack, outermost first
HowEffect
aroundadvice(base, opts); may call the base zero, one or many times.
overrideadvice(opts); the base never runs.
before / afterSide effect before or after the base; the base's result flows out.
before-whileContinue inward only while advice returns truthy (gates).
before-untilUse the advice result when truthy, otherwise the base (fast paths).
after-whileRun advice only when the inward result succeeded.
after-untilKeep a successful inward result, otherwise use the advice fallback.
filter-args / filter-returnTransform opts before the base, or its result after.

Advice may be sync or async. While/until use Clojure truthiness (only None and False are falsy); a step-result dict counts as true when its exit is missing or zero. At equal depth the newest advice is outermost; depth (-100..100, default 0) overrides add order, lower being farther out. Re-adding an id replaces the entry. Through step embeds, the parent's advice is inherited by flat step name, outermost, and a same-id ancestor entry replaces the child's.

8. YAML desired state & COLORS_PAR_*

load_yaml(text) parses desired state with YAML 1.2 core-schema scalars, matching green and red: only true/false variants are booleans (no, on stay strings); 012 is decimal, 0o12 octal, 0x1f hex; scientific notation is numeric; dates and sexagesimal values such as 1:30 stay strings. Empty input loads as {}.

workdir: work
names:
  - alice
  - bob
# Quote version-like values; YAML reads 3.10 as a number.
python-version: "3.10"

Credentials and one-run overrides come from the environment, never from the YAML file. read_pars(opts, env=None) overlays every COLORS_PAR_<KEY> variable onto the flat key <key> (lower-cased, _ to -), coercing to the existing value's type when it was a bool or int. par_name(key) is the inverse. The prefix is shared by all three colors.

from blue.cli import load_yaml, par_name, read_pars

par_name("api-token")                       # "COLORS_PAR_API_TOKEN"
read_pars({"port": 80}, {"COLORS_PAR_PORT": "8080"})  # {"port": 8080}
Keep desired-state keys flat and kebab-case so the overlay can reach them; use namespaced keys for state that steps add.

9. Application boundaries

Applications select and read configuration, optionally apply read_pars, validate inputs, and call await run(wf, opts). There is no SDK argument parser, file discovery, lifecycle preflight, progress logger or dry-run policy. Application-defined advice can implement reporting, guards or planned skipping; a skipped step is not a deployment plan.

blue.cli retains its historical import path for configuration helpers only. PocketDeploy owns its CLI, SQLite journal and recovery; Blue executes its workflows.

Pin by commit. Blue is not published to PyPI. Consumers pin a published git commit and move the pin with their own procedure (for example uv lock); the in-repo example uses a relative [tool.uv.sources] path.

10. The example

examples/hello is an offline application with its own argparse CLI and blue.yml input:

cd examples/hello
./blue create
./blue delete

The script name is this example’s choice, not an SDK launcher contract.

11. Testing

uv run pytest runs the suite under tests/ with pytest-asyncio in auto mode; CI runs it on Python 3.11, 3.12 and 3.13.

Test a package's own steps by calling them with plain dicts, or stub the CLI they call by putting a fake executable first on PATH.

12. API index

ModulePublic names
blue.workflowworkflow, run, step, failed, advice_add, advice_add_all, advice_remove, advice_remove_all, advice_plan, Workflow, Opts, StepError
blue.cliload_yaml, read_pars, par_name
blue.adviceThe combinators and registry operations behind the workflow functions.

The top-level blue package re-exports the workflow and configuration names plus the advice module. PocketDeploy, dotfiles and the controllers built on PocketDeploy keep their existing blue.workflow and blue.cli imports; their used signatures and exit/error keys stay stable.