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.
1. Philosophy
- blue is a small library. A package defines its own steps, wiring and launcher; blue supplies DAG execution, subworkflow composition, advice and configuration helpers. Its only runtime dependency is PyYAML.
- Steps call tools directly. A step calls
gcloud,oci,doctl,hcloudor an HTTP API itself, in Python a coding agent writes and maintains. There is no OpenTofu or Ansible integration: it was removed on 2026-10-29 together with template scaffolding, schema gates, Kubernetes controllers, resource scopes and the subprocess runner. - Everything is one dict. Desired state is YAML loaded into
opts; every step reads that dict and returns a new one, enriched with what it observed. - Application-owned behavior. Packages implement idempotence, validation, command names, plans, reporting and durable state. The engine does not persist runs.
- Errors are values. Steps report outcome in
"blue/exit". Exceptions are caught at the step boundary and converted, so failures route throughnext_fnand joins like any other result. - One model, three languages. Green is canonical; the SDKs share workflow semantics, while application code uses each language’s tools.
2. Naming & the opts contract
| green | red | blue |
|---|---|---|
:green/exit | "red/exit" | "blue/exit" |
green.workflow | red/workflow | blue.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".
| Key | Meaning |
|---|---|
"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. |
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.
- A returned dict without
"blue/exit"is success and is stamped0. - Returning a non-dict is a step failure.
- Raising is allowed: the boundary returns
"blue/exit": 1with"blue/err"and"blue/trace". RaiseStepError(message, exit=n)to choose the code. - Async steps must await everything they start; application entrypoints own event-loop setup and process exit handling.
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
- Return nothing to end the branch, one pair to continue, many to fan out in parallel.
- It sees the step result, including
"blue/exit", so it can route failures to cleanup or retries. - Without
next_fn, a positive exit stops the path; otherwise the default successors run.
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
- Static fork:
wire_fnlists several successors. - Dynamic fan-out:
next_fnreturns several pairs. Independent successors run as concurrent asyncio tasks. - Join: branches from different origins converging on one step run it once, with the deepest shared fork's opts plus
"blue/branches". - Same-origin fan-out: entries from one fan-out parent at the same step run independently; that is how N-way item processing works.
- Failure: a failed branch lets siblings finish their current step, collapses the fork, skips the join and propagates the worst exit with every branch result under
"blue/branches". On equal codes the first incoming branch's diagnostics win.
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
| How | Effect |
|---|---|
around | advice(base, opts); may call the base zero, one or many times. |
override | advice(opts); the base never runs. |
before / after | Side effect before or after the base; the base's result flows out. |
before-while | Continue inward only while advice returns truthy (gates). |
before-until | Use the advice result when truthy, otherwise the base (fast paths). |
after-while | Run advice only when the inward result succeeded. |
after-until | Keep a successful inward result, otherwise use the advice fallback. |
filter-args / filter-return | Transform 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}
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.
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:
hello/systemrunsuname -s; a failed command stops the run.next_fnfans out onehello/personbranch per name. Each embeds a two-step subworkflow:hello/greetwrites/removes a file andhello/verifyverifies it.- The parent joins at
hello/report, which reads"blue/branches"and runscaton create, or removes the empty directory on delete. - Application-defined around advice reports every stage, including inherited advice inside each subworkflow.
- Paths resolve against the selected input file. The application applies
COLORS_PAR_WORKDIRoverrides and validates names before running.
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_workflow.pyandtest_advice.pypin the engine: routing, freezing, joins, failed forks, composition, combinators, depth and inheritance.test_cli.pypins the YAML 1.2 scalar table and theCOLORS_PAR_*overlay.test_package_conventions.pycovers the public export list.test_example_hello.pyrunsexamples/helloin-process and as a script: create, delete, configuration validation, the overlay, inherited advice, child failure and process exit codes.
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
| Module | Public names |
|---|---|
blue.workflow | workflow, run, step, failed, advice_add, advice_add_all, advice_remove, advice_remove_all, advice_plan, Workflow, Opts, StepError |
blue.cli | load_yaml, read_pars, par_name |
blue.advice | The 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.