@baizor/pipeline
v0.24.2
Published
Unified local CLI for the Claude-Pipeline plugin: deterministic planning (and, in later phases, matching / routing / event emission / UI) computed OUTSIDE the LLM context so agents pay near-zero tokens for control-flow work. Runs directly with Bun; a Node
Readme
pipeline CLI
A single local CLI that holds the deterministic, LLM-free work of the
Claude-Pipeline plugin. Agents shell out to it (or import it) so control-flow
work — enumerating steps, resolving models, building/validating the DAG, matching
tasks to pipelines, routing graph pipelines, driving the whole run loop, and
emitting journal events — costs near-zero LLM tokens instead of being done
in an agent's context.
Install
bun add -g @baizor/pipeline # or: npm i -g @baizor/pipeline
pipeline --helpThe Pipeline plugin for Claude Code
requires this package: since plugin v0.93.0 the plugin ships no code of its
own, and its skills, agents and hooks all run pipeline subcommands.
Runtime
Written in TypeScript and run directly with Bun — the published bin points
at src/cli.ts, so there is no build step and no dependency to install. From a
checkout:
bun src/cli.ts <command> [options]For embedding in another local project you can either import the library API or produce a Node-targeted bundle:
bun run build # → dist/cli.mjs (Node-compatible ESM)Supported Bun versions: >= 1.3.14 (engines.bun), tested on 1.3.14 and
1.4.0. Because the published bin is source, this CLI runs on your Bun,
not one we ship — so CI pins both ends of that range explicitly and crosses them
with Linux and Windows. 1.3.14 is a hard floor rather than a preference: v2
pipeline.yml parsing uses Bun's built-in Bun.YAML, which older releases do
not have. Nothing in CI tracks latest; a new Bun release becomes supported
when it is added to that matrix in a reviewed change.
Documentation
docs/cli.md— telemetry (pipeline stats telemetry), the opt-out switches, where the CLI writes on disk, and the uploader's lifecycle; plus the fullpipeline worktreereference (JSON shapes, the built-in provisioner/teardown, ports, the standalone hook context).- Privacy tiers — field by field, what leaves your machine.
- Connecting to the cloud
—
pipeline cloud connect, history upload, retention and deletion.
The four runner modes
A pipeline's runner: — the top-level key in pipeline.yml, or the same key
in a v1 PIPELINE.md's frontmatter — picks two things at once: who turns
the crank (the loop) and what executes each step. Only four
combinations are supported:
| runner: | Loop | Step executor | For |
| --- | --- | --- | --- |
| session | the main Claude Code session | the Agent tool (a subagent) | short pipelines — fewest layers |
| manager (default) | a pipeline-manager subagent | the Agent tool (a subagent) | long chains — keeps the main session's context clean |
| driver | pipeline drive, a process we own | a claude -p / codex exec subprocess (--executor claude-cli / codex-cli) | CI and scripts — zero LLM in the loop |
| standalone | pipeline drive, the same process | the Agent SDK, with your own API key (--executor claude-sdk) | no Claude Code install required; first-class per-step metrics |
driver and standalone are the same command and the same loop —
pipeline drive (below) — and differ in exactly one thing: which
--executor runs a step. A manifest's runner: standalone is what selects
--executor claude-sdk by default; passing --executor explicitly on the
command line always wins.
The guarantee, stated once because it holds in every one of the four: what
runs next is decided by pipeline next — always, in every mode. session and
manager call it from inside a live Claude Code session; driver and
standalone call the identical engine directly from pipeline drive's own
process. No mode ever has a model decide control flow — only how faithfully a
model calls into the engine differs between modes, which is exactly why the
mode you pick is a reliability decision, not a behavioural one.
Hosting is a location, not a mode. All four modes above are things you can
run locally. On a machine we host, only standalone is possible: there is no
user subscription and no local Claude Code install for session, manager or
driver's subprocess to run against.
type: script steps sit outside this table entirely. The command layer
executes them in-process, identically, in all four modes — the mode question
does not apply to them.
v1 → v2 naming. A v1 PIPELINE.md's runner: frontmatter carried only
two values, and the CLI still reads both: manager is unchanged, and
runner: headless is read as driver — the same mode under its new name,
not a different one. Both spellings still parse in a v1 pipeline; only
headless as the mode's name is retired.
Commands
clone — scaffold a ready-made pipeline into your project
bun src/cli.ts clone <name> [--force] [--dir <path>] [--list] [--json]Copies a bundled, ready-made pipeline template into
./.pipeline/<name>/ (relative to the current directory, or --dir
<path>) — the local-first onboarding entry point: install @baizor/pipeline,
then pipeline clone <name> drops a working pipeline you can run and adapt.
Templates ship inside this package (apps/pipeline-cli/templates/<name>/)
and are resolved relative to the CLI's own source, so clone behaves the same
from a plugin checkout and an npm/bun install. --list shows what's available;
an unknown name errors and lists the choices. The command refuses to
overwrite an existing ./.pipeline/<name>/ unless --force is passed
(which replaces the folder entirely — no stale files survive).
Exit codes: 0 cloned (or --list) · 1 target exists without --force, or
the copy failed · 2 usage (no name, unknown template, bad flag).
Adding a template: drop a folder under
templates/<name>/(a validPIPELINE.md+ asteps/folder — mirrorexample-minimal) and register it insrc/lib/templates.ts. The test suite validates that every registered template plans cleanly and ships in the npm tarball.
plan — compute the execution plan
bun src/cli.ts plan --root <abs-path-to-pipeline-root> [--default-model <m>]Reads PIPELINE.md + every steps/**/*.md frontmatter (never bodies) and prints
a compact JSON plan: mode (sequential | parallel), isolation, resolved
default_model, the ordered steps (each with step_id, effective model,
depends_on), the DAG layers (parallel only), plus errors and warnings.
Exit code is 1 when errors is non-empty (caller should halt), 0 otherwise.
A --root with no pipeline in it is refused rather than planned: a path that
does not exist, and a directory holding no pipeline.yml, no PIPELINE.md and
no steps/*.md, each print a plan carrying that single error and nothing else —
never a default-populated plan for a pipeline that is not there.
Mode gate: a pipeline runs in parallel/DAG mode only when PIPELINE.md
declares execution: parallel. Steps that declare depends-on without that flag
run sequentially and emit a warning. This keeps the common (sequential) case at
O(1) reads on a run start.
migrate --to-manifest — turn a v1 pipeline into a pipeline.yml
bun src/cli.ts migrate --to-manifest [--root <dir>] [--dry-run] [--json] [--force]Generates the v2 manifest for a v1 pipeline: ONE file that says everything,
replacing PIPELINE.md frontmatter + every step's frontmatter + a ## Graph
section + the filename order. Prints the old→new step-name map — a v1 step id
that was only a filename stem loses its ordering prefix (01-implement →
implement), because the manifest's step list now carries the order.
It is generated from the computed plan, not from the source files: the plan is what the v1 walk actually decided, so emitting from it is the only way to be sure the manifest says what the pipeline already does. The gate before writing is therefore equivalence, not lint — the manifest is parsed back, re-planned, and every field that decides what runs must match. A migration that produces a valid pipeline which is not this pipeline writes nothing.
It refuses rather than guess:
- an existing
pipeline.ymlis never overwritten (pass--force), - a v1 pipeline that does not plan cleanly is not translated,
- anything a v2 manifest cannot express — a script step's inline
command:, a(required)variable,finalize:,delete_branches:— is named, and aborts the write, runner: driver(v1'srunner: headless— see the fourrunnermodes) is a line this migration does not emit yet, even though the v2 manifest itself can say it: the write still aborts, namingrunner: driveras the line to add by hand afterwards.
--dry-run still shows what the rest becomes.
PIPELINE.md is left in place: it is prose for humans afterwards and is no
longer parsed. The ## Next sections in the step files are dead too — the
manifest decides the order.
drive — run the driver / standalone modes (EXPERIMENTAL)
bun src/cli.ts drive --root <pipeline_root> --run-id <id> --start <step-name>
[--default-model <m>] [--model <step_id>=<m> ...]
[--default-effort <level>] [--effort <step_id>=<level> ...]
[--var NAME=value ...] [--vars-file <path>]
[--answer <text> | --answer-file <path>]
[--task <text> | --task-file <path>]
[--executor <claude-cli|claude-sdk|codex-cli>] [--executor-cmd <template>]
[--json] [--resume]An EXPERIMENTAL single-process runner that replaces the pipeline-manager
LLM: it loops over the exact engine pipeline next uses, executing an entire
pipeline run with deterministic control flow — no agent spawns for the loop
itself — ideal for automation and testing.
pipeline drive is the one command for two of
the four runner modes — driver and standalone
share this exact loop end to end, and differ only in --executor, which picks
what runs each step:
| --executor | Mode | What runs each step |
| --- | --- | --- |
| claude-cli (default) | driver | a fresh claude -p subprocess |
| codex-cli | driver | a fresh codex exec subprocess |
| claude-sdk | standalone | the Agent SDK, your own API key |
Omit --executor and the manifest decides: a pipeline.yml declaring
runner: standalone implies claude-sdk; every other (or absent) runner:
value keeps today's default, claude-cli. An explicit --executor always
wins over the manifest, and a disagreement between the two is reported once,
at selection time — never per step, never silently.
--executor-cmd <template> (or PIPELINE_DRIVE_EXECUTOR_CMD) is a different
axis: it overrides the exact subprocess command for whichever --executor you
picked; it never changes which implementation runs.
Executor retry environment (08.4):
- Sets
CLAUDE_CODE_RETRY_WATCHDOG=1(lifts retry cap for transient errors) - Sets
CLAUDE_CODE_MAX_RETRIES=15(hard cap for transient retries) - Overridable by explicitly setting these env vars before the spawn
- Documented mechanism for unattended sessions (Claude Code 2.1.199+)
Exit codes:
0completed1halted (includes provider-limit error info when present)2usage/argument error3blocked (awaiting nested blocker resolution)4awaiting-input (parked on a needs-input question)
Needs-input (park/resume):
- Each question carries a correlatable
question_id(06.2.1) for cloud-dispatcher alignment - Parks with
exit 4and includes the question in the final JSON - Resume with
--resume --answer <text>to deliver the answer and continue the SAME session
Provider limits (06.7):
- Detects usage/rate-limit errors from the executor envelope
- Includes
provider_limit: {reason, retry_after_ms?}in the exit-1 (halted) JSON - Reason:
rate_limit_exceeded|overloaded
Library use
import { computePlan } from '@baizor/pipeline/plan';
const plan = computePlan('/abs/path/to/.pipeline/my-pipeline');match — find the best-matching pipeline
bun src/cli.ts match --pipelines-dir <dir> (--task "<text>" | --issue <ref>) [--top N] [--neg-threshold N]The BM25 pipeline matcher. Scores every PIPELINE.md under --pipelines-dir with
Okapi BM25 over the positive corpus (name + End State + Scope.In + Glossary) and
hard-filters on the negative corpus (Scope.Out) by keyword overlap. Prints
{task, candidates, excluded} JSON. Used by /pipeline:find and
/pipeline:dispatch tier 1.
event — write a journal event / liveness / mirror binding
bun src/cli.ts event <type|write-liveness|clear-liveness|register-mirror-binding> [--project-root=/abs] [k=v ...]The journal event writer. Appends one event envelope to
<project>/.pipeline/.runtime/events.jsonl (or writes the per-run liveness
lockfile / mirror binding for the subcommands). /pipeline:run (lifecycle + liveness
- mirror binding) and
pipeline-manager(per-iteration events) call it. Always exits 0 (best-effort — never blocks the caller).
route — decide the next step for a graph (Variant-A) pipeline
bun src/cli.ts route --root <pipeline_root> --run-id <id> --from <step_id> --flags '<json>' [--default-model <m>]For a pipeline that opts into declarative routing — a ## Graph JSON block in
PIPELINE.md mapping each step_id to conditional edges { when, goto | done,
max } — this evaluates the graph + the result --flags the just-finished
--from step emitted + this run's per-edge counters (persisted at
<pipeline_root>/.runtime/<run-id>/route.json, gitignored) and prints the next
action: { action: "run", step_id, path, model } / { action: "done" } /
{ action: "halt", reason }. Exit 1 on halt.
This makes bounded-retry loops declarative — e.g. a review step that loops
back to implement up to max: 3 times, then falls through to package:
{
"implement": { "goto": "review" },
"review": [
{ "when": "changes_needed", "goto": "implement", "max": 3 },
{ "goto": "package" }
]
}The counter/skip logic lives ONCE here, never duplicated across step bodies. A
pipeline with no ## Graph section is untouched (legacy sequential/DAG).
next — drive a whole run as a mechanical state machine
bun src/cli.ts next --root <pipeline_root> --run-id <id> [--start <step-name>] \
[--default-model <m>] [--record '<json>'] [--resume]The orchestration engine the pipeline-manager drives. Every
runner mode ultimately calls this same engine —
session/manager from inside a live session, driver/standalone directly
from pipeline drive's own process — so what runs next is always decided
here, never by a model. Each call returns the next action to perform,
given the run's persisted state + the --record of the action just
performed. The manager loop is just:
action ← pipeline next --start <first-step> # init (no --record)
loop: perform(action); action ← pipeline next --record '<outcome>'It folds every deterministic control-flow decision — sequential advancement,
graph routing (reusing route's counters), DAG-layer stepping, improver &
script-creator gating, and the end-of-run retrospective gate — into code, so the
manager only spawns, parses reports, merges worktrees, and emits events. Actions:
{ "action": "run-step", "concurrent": <bool>, "steps": [ { step_id, path, model, isolation, index }, … ] }— run one step (concurrent:false, sequential/graph) or a whole DAG layer (concurrent:true, parallel).{ "action": "merge", "branches": [ { step_id, branch, path }, … ] }— merge parallel worktree branches (worktree isolation only).{ "action": "run-improver", "iteration_path" }— dispatchpipeline-improverfor a step that emitted a brief.{ "action": "run-script-creator", "iteration_path", "number", "of" }— dispatchpipeline-script-creatorfor the i-th of the improver'sscript_creation_briefs.{ "action": "retrospective" }— run the Tier-2 end-of-run retrospective (only when<root>/.feedback/<run-id>/has files — the CLI counts them).{ "action": "done" }/{ "action": "halt", "reason", "status" }/{ "action": "blocked" }— terminate.
Records the manager sends back (--record '<json>'): {kind:"step",…},
{kind:"layer",results:[…]}, {kind:"merge",conflict,…},
{kind:"improver",script_briefs:N}, {kind:"script",outcome},
{kind:"retro",done:true}. State persists at
<pipeline_root>/.runtime/<run-id>/next.json (gitignored). --resume (or any
no-record call on an existing run) re-enters at --start — used for nested-blocker
resumes and crashed-manager re-spawns. Exit code: 1 on a halt action, 0
otherwise.
submodule bump — record + push a guarded submodule-pointer change
bun src/cli.ts submodule bump --project-root <superproject> [--submodules a,b] \
[--base <branch>] [--source-worktree <path>] [--dry-run] [--json] \
[--no-fetch] [--no-admin]A guarded git primitive: it records superproject submodule-pointer change(s)
on the base branch and pushes them, isolation-safely — the shared checkout is
NEVER checkout/reset/switched; its only mutation is fetch + merge
--ff-only. All branch/commit work happens in a throwaway worktree off
origin/<base>. This replaces AI-improvised "land a pointer bump" recipes with a
deterministic, tested command that refuses unsafe requests.
Args
--project-root <path>(required) — the superproject checkout.--submodules a,b(optional) — the subset to consider; when omitted, drifted pointers are auto-detected from<project-root>/.gitmodules.--base <branch>(defaultmain) — the branch to land onto.--source-worktree <path>(optional) — where the run's merged submodule state lives; when given, the run's intended pointer is read from that worktree (its submodule checkout HEAD, or the gitlink its HEAD records) rather than the superproject's live checkout.--dry-run— stage + capture the diff in the throwaway worktree, then STOP before push/PR/merge (mutates nothing on the base branch).--json/--no-fetch— JSON is always emitted;--no-fetchtrusts the present remote-tracking refs (skips the read-only reachability fetch).--no-admin— do not retry a refusedgh pr mergewith--admin. The fallback is ON by default and bypasses branch protection on the target repository; with--no-admin, a refused merge is reported (merge_outcome: "refused", halted, exit 1) andghis never invoked with--admin. An automated orchestrator is expected to pass it — seedocs/cli.md.
Guards (each maps to an incident it prevents):
- fork-diff safety (#132) — a pointer whose value differs only because the base advanced past the run's fork is NOT bumped/reverted.
- conflict — a pointer the base changed since the fork is skipped + surfaced, never clobbered.
- reachability — only bump to a commit reachable from the submodule's
origin/<default>and strictly ahead of the recorded pointer. - pre-flight self-clean — orphaned
land-*throwaway worktrees + stale scratch branches from prior KILLED runs are reaped BEFORE anything is created (correctness never depends on afinally; idempotent under a mid-run kill). - STOP-on-error — halts at the first error with a structured
halt_reasonand the exact manual recovery command; the post-merge reconcile of the shared checkout retries the transient index.lock / propagation-lag race, then halts.
Output — one JSON object:
{
"status": "committed|noop|dry-run|halted",
"bumped": [{ "path": "sub", "from": "<sha>", "to": "<sha>" }],
"skipped": [{ "path": "sub", "reason": "<why>", "status": "unchanged-by-run|base-advanced-conflict|unreachable|…" }],
"pr": "<url|null>", "infra_sha": "<sha|null>", "reconcile_status": "ff|skipped|failed|na",
"merged_via_admin": false, "merge_outcome": "plain|admin|refused|null", "halt_reason": null
}merge_outcome distinguishes the three merge outcomes — "plain" (merged as
is), "admin" (merged by bypassing branch protection), "refused" (not merged;
reported, never forced) — and is null when the merge step was never reached
(noop / dry-run / an earlier halt).
Exit code: 0 (committed / noop / dry-run) · 1 (halted) · 2 (usage / env —
bad args, not a git repo, or gh missing for a non-dry-run landing).
GENERIC. The command knows nothing about any specific project; config/args
drive everything. A project with no submodules resolves an empty candidate set →
noop. Assumes git + gh on PATH (like the pipeline's other git work); a missing
gh is a clean exit-2 env error.
worktree — the worktree-hook lifecycle without a run
pipeline worktree create [--name <slot>] [--base <branch>] [--submodules a,b] \
[--hook-dir <path>] [--ports <n>] [--json]
pipeline worktree finalize --name <slot> [--base <branch>] [--submodules a,b] \
[--hook-dir <path>] [--json]
pipeline worktree destroy --name <slot> [--outcome completed|halted] \
[--hook-dir <path>] [--json]
pipeline worktree list [--json]For an orchestrator that needs a slot — a worktree, its branch, its env file
— but has no pipeline run to hang it on. It executes the consumer's
worktree-create / worktree-finalize / worktree-destroy hooks (see the
plugin's docs/worktree-hook-contract.md) through the same code path
pipeline next uses (src/lib/worktree-hooks.ts), never a second copy of the
PIPELINE_WT_* assembly — the contract is frozen, so it is single-homed and an
anti-drift test compares the two callers' environments byte for byte.
No worktree-create.* / worktree-destroy.* hook? create and destroy
fall back to a built-in provisioner and teardown — a plain git worktree
outside the repository, one worktree per --submodules entry, an env file, and
a block of free ports — so a repository with no hooks at all still runs
create → finalize → destroy end to end (finalize's built-in half is a
no-op that reports ok). That fallback is reachable from this command only
— a pipeline run with no worktree-create.*/worktree-destroy.* still
halts / reports a failed teardown, exactly as it always has (D9). A hook,
where one exists, always wins, including over a slot the built-in provisioner
made. Full reference, JSON shapes, the port-precedence rule for hook authors
(D14), which command reaps a built-in slot (worktree destroy while you can
still name it, pipeline gc once nothing can), and one documented limitation
(a project path with a space or shell metacharacter is refused):
docs/cli.md.
Standalone context (stated because the contract is frozen):
PIPELINE_WT_PIPELINE_ROOTandPIPELINE_WT_PIPELINE_NAMEare the empty string — there is no pipeline. They are present-and-empty, never absent.PIPELINE_WT_NAMEis the slot name (it is the slot identity the create hook is idempotent per), andPIPELINE_WT_RUN_IDcarries the same value: there is no run id, and on the run path the two have always been equal.- No run-scoped journal event is written. A standalone invocation must not
fabricate
worktree.createdhistory for a run that does not exist. PIPELINE_WT_PROJECT_ROOTis the current directory, exactly as on the run path — run the command from the project root.
Notes
--namedefaults to a fresh UUIDv7 (whatpipeline idmints) and must match[A-Za-z0-9][A-Za-z0-9._-]*, max 64 characters. The name reaches a filesystem path and a git branch name, so anything else — a path separator,.., whitespace, a shell metacharacter, a leading-, a Windows device name — is refused with exit 2 before any path, branch, or hook is touched.- Creation is idempotent per name by frozen contract: a second
createreuses the slot and reportsstatus: "reused"(plusreused_evidence) rather than failing. An orchestrator should read a reuse as a duplicate dispatch. destroy --outcome completed(default) reaps —PIPELINE_WT_DELETE_BRANCHES=1and the slot record is dropped;--outcome haltedpreserves —DELETE_BRANCHES=0and the record is kept for post-mortem.submodule_slotsnames the directory a worker actually works in, oncreate --jsonandlist --jsonalike, whichever side provisioned the slot —{ path, name, dir, base, source, exists }, and[](nevernull) when no submodules were declared. A dispatched worker commits in the submodule slot, so the parentworktree_pathis empty and clean by design: a reconciliation that inspects onlyworktree_pathsees an empty shell and is wrong about it. Aworktree-create.*hook is not required to enumerate its submodule slots (the frozen contract has no field for them), so the directory is derived — from the slot record, then the slot's env file (SUBMODULE_<n>_DIR), then the layout convention the built-in teardown already reaps by — andsourcesays which of the three answered.listreports the slots this command provisioned (recorded under.pipeline/.runtime/worktrees/) and whether each is still on disk. Finding and reaping leaked worktrees and branches ispipeline gc's job — both the hook-provisioned convention (.claude/worktrees/) and the built-in slot root outside the repository, where it reaps a slot no record names (a run that died beforedestroy) and leaves everything a command can still reach; seedocs/cli.mdfor the full table of what it reaps, keeps and refuses.--ports <n>sizes a contiguous block of free ports (default4;0for none), allocated and published into the slot's env file. Aworktree-create.*hook that reports no ports of its own still gets the block appended to the env file it named (D14) — only a hook that reports non-empty ports overrides it.
Exit code: 0 success · 1 the hook failed (soft-fail {"ok":false,"detail"}
or hard-fail — detail says which) · 2 usage / invalid --name / invalid
--outcome.
hook — the Claude Code hook relays
pipeline hook <analytics-relay|stats-relay|session-relay|department-notifier-relay|prompt-match-relay>Not meant to be run by hand. The Pipeline plugin for Claude Code registers
these five relays in its hooks/hooks.json and invokes them through
hooks/run-hook.sh, a POSIX-sh shim that resolves an absolute pipeline binary
before exec'ing — Claude Code runs hooks through a non-interactive /bin/sh
which never sources ~/.zshrc, so a Dock- or Start-menu-launched session cannot
otherwise see ~/.bun/bin.
Each relay reads its hook JSON payload on stdin, writes any hook output
(hookSpecificOutput.additionalContext) on stdout, and always exits 0 — a
non-zero exit from PreToolUse blocks the tool call and from UserPromptSubmit
blocks the prompt, and nothing a best-effort journal writer can fail at is worth
that. Exit 2 is reserved for an unknown or missing name, which means a
malformed hooks.json rather than a runtime condition.
They live here, rather than in the plugin, so the hook's version is the CLI's
version by construction. While the plugin shipped both a copy of this CLI and
the relays, a user who had also installed @baizor/pipeline globally had two
copies at potentially different versions and the hooks always ran the plugin's,
with nothing detecting the divergence.
Tests
bun test tests/CI runs exactly that, sequentially, across four legs — {ubuntu, windows} ×
{bun 1.3.14, bun 1.4.0} — plus a --version and bun run build smoke on each.
Some suites only fail on one of those combinations (the write-containment guard
in pipeline fix --scope-guard failed open on Windows under Bun 1.4 alone), so
a green run on one leg is not evidence about the others.
