@juicesharp/rpiv-workflow 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,583 +1,136 @@
1
1
  # @juicesharp/rpiv-workflow
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@juicesharp/rpiv-workflow.svg)](https://www.npmjs.com/package/@juicesharp/rpiv-workflow)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
3
6
  <div align="center">
4
7
  <a href="https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-workflow">
5
- <picture>
6
- <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-workflow/docs/cover.png" alt="rpiv-workflow cover" width="50%">
7
- </picture>
8
+ <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-workflow/docs/cover.png" alt="rpiv-workflow cover art — a five-node stage diagram running research to plan to review to a blockers gate to commit, with a dashed revise edge looping back to plan" width="50%">
8
9
  </a>
9
10
  </div>
10
11
 
11
- Pi extension. Chain Pi skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation.
12
-
13
- **Skill-agnostic.** The runner sends `/skill:<name>` via Pi's native dispatch — it doesn't know or care who shipped the skill. Install on its own and write workflows over your own `~/.pi/agent/skills/`, or pair with [`@juicesharp/rpiv-pi`](../rpiv-pi) to use rpiv-pi's bundled `ship`, `build`, `arch`, and `vet` workflows over rpiv-pi's bundled skills.
14
-
15
- ## Pick your lane
16
-
17
- This package serves four overlapping audiences. Find yours, then jump to the matching section:
18
-
19
- - **I want to run workflows over my own Pi skills.** → [Install](#install) → [Use](#use) → [Configure](#configure).
20
- - **I'm shipping a workflow pack others install.** → [Configure](#configure) (the "config vs pack" split is what makes packs safe) → [Authoring DSL](#authoring-dsl).
21
- - **I'm bundling workflows inside my own Pi extension.** → [Programmatic registration](#programmatic-registration).
22
- - **I'm embedding the runtime in a non-Pi host.** → [Host boundary](#host-boundary) + [`runWorkflow`](#programmatic-runner).
23
-
24
- Whatever the lane, the [Glossary](#glossary) at the bottom pins one name per concept.
12
+ Chain the Pi skills you already have into multi-stage pipelines. `rpiv-workflow`
13
+ adds a `/wf` command to [Pi Agent](https://github.com/badlogic/pi-mono) that runs
14
+ each stage in its own detached session, validates its output against a schema,
15
+ routes between stages on predicates over the previous stage's data, and appends
16
+ each step to a resumable JSONL trail. It ships **zero** workflows — write your own
17
+ in `.rpiv/workflows/config.ts`, or install
18
+ [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi) for five.
25
19
 
26
20
  ## Install
27
21
 
28
22
  ```sh
29
- pi install @juicesharp/rpiv-workflow
30
- ```
31
-
32
- ## Use
33
-
34
- ```
35
- /wf # preview every loaded workflow
36
- /wf <name> # preview one workflow's stage graph
37
- /wf <name> <input> # run a workflow with <input> piped to the start stage
38
- ```
39
-
40
- ## Configure
41
-
42
- The loader merges workflows from three layers (each later layer overrides earlier by workflow name):
43
-
44
- ```
45
- built-in (programmatic — registered by sibling packages like rpiv-pi)
46
- ← user packs (~/.config/rpiv-workflow/packs/*.ts, alpha-sorted)
47
- ← user config (~/.config/rpiv-workflow/config.ts)
48
- ← project packs (<cwd>/.rpiv/workflows/packs/*.ts, alpha-sorted)
49
- ← project config (<cwd>/.rpiv/workflows/config.ts)
50
- ```
51
-
52
- Run state for each `/wf` invocation lands under `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl` — the third subfolder of the same domain dir.
53
-
54
- Two file roles per layer:
55
-
56
- - **Config file** — the one TypeScript file you hand-edit. Accepts three default-export shapes:
57
-
58
- ```ts
59
- // 1. A single Workflow
60
- import { defineWorkflow, produces, acts } from "@juicesharp/rpiv-workflow";
61
- export default defineWorkflow({
62
- name: "ship",
63
- start: "implement",
64
- stages: { implement: acts(), commit: acts() },
65
- edges: { implement: "commit", commit: "stop" },
66
- });
67
-
68
- // 2. A Workflow[] with a single entry
69
- export default [ /* one workflow */ ];
70
-
71
- // 3. The envelope form — required when shipping multiple workflows
72
- export default {
73
- workflows: [ /* many */ ],
74
- default: "ship", // which one `/wf <input>` runs without a name
75
- };
76
- ```
77
-
78
- - **Pack files** (`packs/*.ts`) — installable bundles others can drop in. Accept only `Workflow | Workflow[]`. Packs **cannot** set `default` — that lives in the config file. This is what makes installable workflow packs safe: a pack contributes new workflows without overriding the user's default.
79
-
80
- ### Skill aliases
81
-
82
- `skillAliases` remaps a skill name across **every** loaded workflow (built-in + user + project) with one declarative config entry — no workflow redeclaration. It's a config-file-only envelope field (packs reject it), applied at load time so preview, the JSONL audit, and the runtime skill preflight all see the final skill; the runner is untouched.
83
-
84
- ```ts
85
- // config.ts — alias-only is valid (no `workflows` needed)
86
- export default { skillAliases: { commit: "attributed-commit" } };
87
-
88
- // or alongside workflows + default
89
- export default {
90
- workflows: [ /* … */ ],
91
- default: "ship",
92
- skillAliases: { commit: "attributed-commit", "code-review": "strict-review" },
93
- };
94
- ```
95
-
96
- The key is the **skill** name (`stage.skill ?? <stage key>`), not the stage id. One hop only (no transitive chains); `run`/`prompt` stages are skipped; aliases merge project-over-user per key. `/wf` shows a `Skill aliases in effect: …` banner; an alias matching no dispatched skill warns at load time (no-op); a bad target reuses the existing runtime "skill not found" preflight. Use it to point a bundled skill (say `commit`) at your own variant (`attributed-commit`) everywhere, upgrade-safe.
97
-
98
- ## Authoring DSL
99
-
100
- A workflow is a typed graph: named entry point, a `stages` record, and an `edges` table that maps each stage to another stage name, the sentinel `"stop"`, or a predicate function that chooses at runtime.
101
-
102
- > **Typing model.** Inter-stage data typing is **runtime-contract-based**: `outputSchema` / `inputSchema` (Standard Schema v1) validate `output.data` when stages run, and skill contracts adjudicate composition at load time. The `StageDef<TIn, TOut>` type parameters are local inference helpers for a single factory call — they are erased at the `Workflow.stages` boundary (every stage collapses to `StageDef`), so they do **not** propagate types across edges. Don't lean on them for cross-stage safety; lean on schemas and contracts. A typed builder API that carries types through the graph is on the roadmap, not in this release.
103
-
104
- Three factories for the two stage kinds:
105
-
106
- - `produces(overrides?)` — `kind: "produces"`. The skill writes a file the next stage reads. Halts the chain if the path doesn't appear in the transcript. Without a Pi session, use [`produces.script`](#script-stages-no-pi-session).
107
- - `acts(overrides?)` — `kind: "side-effect"`. The skill's side effect IS the work (commit, implement). The next stage inherits the prior artifact list forward — the stage's prompt receives the upstream primary artifact's handle. Without a Pi session, use [`acts.script`](#script-stages-no-pi-session).
108
- - `terminal(overrides?)` — `kind: "side-effect"` with `inheritsArtifacts: false`. A side-effect stage that does NOT inherit the upstream artifact: its prompt receives `originalInput` (the run's brief), the upstream-artifact preflight is bypassed, and the rolling primary slot is cleared on success so anything downstream also starts without an inherited handle. The right answer for a final cleanup / summary / post-run notification stage that shouldn't be coupled to the upstream chain. Without a Pi session, use [`terminal.script`](#script-stages-no-pi-session).
109
-
110
- ### Multi-input stages — `reads:` and the named-publish registry
111
-
112
- A stage that needs more than one upstream artifact (the canonical example: a "revise plan based on review" step that consumes both the plan and the review) declares `reads:` against names it expects in the registry:
113
-
114
- ```ts
115
- revise: produces({ outcome: planOutcome, reads: ["plans", "reviews"] })
116
- ```
117
-
118
- When set, the runner builds a labelled-flag prompt — `/skill:revise --plans <plan-path> --reviews <review-path>` — replacing the default single-artifact form. Multi-artifact stages get flag repetition (`--plans <a> --plans <b>`).
119
-
120
- Names address `state.named`, an accumulating registry every `produces` stage appends onto on each successful run. The slot key is `outcome.name ?? stage.<record-key>`:
121
-
122
- - **Outcome carries a name.** Multiple stages wiring the same outcome converge — both stages append onto the same `state.named[name]` slot, latest-wins on read. This is how to express "two stages both produce the canonical plan" without restating the name on each stage.
123
- - **Outcome carries no name.** Stages publish under their record key. Downstream `reads: ["blueprint", "code-review"]` references stage names directly.
124
-
125
- Slots are arrays — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)`. Load-time validation rejects `reads:` references whose name no produces stage publishes; the `ensureNamedReads` preflight halts at runtime when a name's slot is empty (the producer hasn't fired yet on this path).
126
-
127
- Conditional routing uses `gate(field, branches, otherwise)` with the bundled predicate helpers (`gt` / `gte` / `lt` / `lte` / `eq`):
128
-
129
- ```ts
130
- import { gate, gt, eq } from "@juicesharp/rpiv-workflow";
131
- edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }, "commit") }
132
- ```
133
-
134
- Branches are evaluated against `Number(output.data[field])` in declaration order; the first matching predicate wins. When no predicate matches (including a missing or non-numeric field, which coerces to `NaN`), the explicit `otherwise` branch is taken and the run's routing-audit row carries a note saying the fallback fired — silent fallthrough is not a thing. Branch keys must not be integer-like (`"2"`): JS object literals reorder such keys ahead of declaration order, so `gate` rejects them at construction.
135
-
136
- `gate` is the numeric convenience only. String/enum, multi-field, or computed routing uses `defineRoute(targets, fn, opts?)` — the body is plain TS (e.g. `output.data.verdict === "approve" ? "commit" : "revise"`), so there's no separate string helper. By default `opts.readsData` is `true` (reads `output.data`, requires the source stage to declare an `outputSchema`); pass `{ readsData: false }` for a route that consults only `state` / `output.meta`.
137
-
138
- ### Model-judged loops — `assess`
139
-
140
- `assess` is the third loop primitive, alongside `fanout` (breadth) and `iterate` (TS-judged depth). It's a **depth loop whose termination is decided by a separate model judge** — for when "are we done yet?" needs a model to read the work, not a synchronous TS predicate. Set it on a `produces()` stage.
141
-
142
- Each round runs **two** sessions:
143
-
144
- 1. a **producer** — this stage's skill/outcome, emitting the work artifact;
145
- 2. a **judge** — a separate session emitting a validated verdict `{ done, feedback }`.
146
-
147
- If `judge.done(verdict)` is `true`, the loop stops and the **producer** output (never the verdict) is the stage result. Otherwise `feedForward` builds the next producer prompt from the verdict's feedback, and the loop continues.
148
-
149
- ```ts
150
- import { produces, directoryPathCollector, jsonBodyParser } from "@juicesharp/rpiv-workflow";
151
-
152
- // The judge's verdict outcome. The collector MUST materialize ≥1 artifact —
153
- // here a JSON file the parser reads into { done, feedback }. (See the
154
- // ≥1-artifact constraint below.) Its `name` is its OWN channel, distinct
155
- // from the producer outcome's name.
156
- const verdictSpec = {
157
- name: "verdicts",
158
- collector: directoryPathCollector({ dir: ".rpiv/artifacts/verdicts", ext: "json" }),
159
- parser: jsonBodyParser, // output.data = { done: boolean, feedback?: string }
160
- };
161
-
162
- breakdown: produces({
163
- outcome: taskListOutcome, // producer outcome (the task list)
164
- assess: {
165
- judge: {
166
- skill: "grade-breakdown", // skill judge — producer handle auto-injected
167
- outcome: verdictSpec,
168
- done: (v) => Boolean(v.data.done), // sync TS reading the model-made verdict
169
- },
170
- feedForward: ({ verdict }) => `Decompose further. Notes: ${verdict.data.feedback}`,
171
- max: 8, // default 8, clamped by run.maxIterations
172
- },
173
- }),
174
- ```
175
-
176
- **Skill vs. prompt judge.** Exactly one of `judge.skill` / `judge.prompt` is the dispatch discriminator (validated at load — both or neither is an error):
177
-
178
- - **Skill judge** (`judge.skill` set): dispatched as `/skill:<judge.skill> <producerHandle>` — the latest producer artifact's handle is auto-injected as the input, exactly like any skill stage. `judge.prompt` is optional.
179
- - **Prompt judge** (`judge.skill` absent): the resolved `judge.prompt` text is sent verbatim, so `judge.prompt` is **required** — the author embeds the producer handle/output (and the frozen `entryArtifact`, if wanted) into the prompt themselves, since a dispatched session delivers only the prompt text.
180
-
181
- **≥1-artifact judge constraint.** The judge runs as a `produces`-kind session, so `enforceCompletionContract` makes a judge whose collector returns **zero** artifacts a **fatal halt** — no retry, no soft-stop. A judge that replies "not done" inline without writing anything *kills the run*. Always have the judge materialize its verdict (e.g. write a JSON file the collector enumerates and the parser reads), as `verdictSpec` does above.
182
-
183
- **Soft-stop at `max`.** When the round cap is hit without `done`, the loop **soft-stops**: it emits a warning, keeps the **last producer output** as the stage result, and advances downstream. No terminal failure, no new error code. `max` defaults to 8 and is clamped by `run.maxIterations`.
184
-
185
- **Judge sessions use framework defaults.** The judge runs on a synthetic `produces` def, so it does **not** inherit the parent stage's `onInvalid` / `maxRetries` / `outputSchema` / `validateTimeoutMs` — those apply to the **producer** sessions only; the judge gets framework defaults. (A skill judge still picks up its own declared skill-contract.) The producer and judge publish into **distinct** `state.named` channels (producer's `outcome.name` vs. `judge.outcome.name`), so verdicts never collide with producer outputs.
186
-
187
- **Determinism contract (for resume).** Like `iterate`, `feedForward` and `judge.done` must be **deterministic** w.r.t. their inputs. Each round persists two audit rows (`r{n}·produce`, `r{n}·judge`); the judge's verdict is recorded specifically so resume **trusts** it rather than re-grading a non-deterministic model. On resume only the pending sub-step re-runs; a boundary guard catches drift in `feedForward` / `judge.done` and fails terminally rather than re-running wrong work.
188
-
189
- `assess` is mutually exclusive with `fanout` / `iterate` / `run` / `prompt` / `reads`, requires `kind: "produces"`, and rejects `sessionPolicy: "continue"` (all enforced at load).
190
-
191
- ## Script stages (no Pi session)
192
-
193
- Some stages don't need an LLM — they merge two upstream artifacts, bump a version field, or fire a post-run notification. The `.script` accessor on each factory runs a pure TS function in place of a Pi skill body. No `/skill:<name>` dispatch, no session, no transcript scan: the function gets a `ScriptContext` (`cwd`, `input` — upstream `Output` envelope, `state` — the deep-readonly `RunView`) and either returns the new envelope (`produces.script`) or returns `void` (`acts.script` / `terminal.script`).
194
-
195
- Stages with `.run` set CANNOT also declare `skill`, `outcome`, `fanout`, or `sessionPolicy: "continue"` — load-time validation rejects the combination. `produces.script` may declare `outputSchema` + `maxRetries` + `onInvalid` (same retry semantics as skill stages); `acts.script` / `terminal.script` may declare `inputSchema` for the upstream-data contract.
196
-
197
- ### `produces.script` — merge two upstream artifacts into a new Output
198
-
199
- ```ts
200
- import { produces, fs, type ScriptContext } from "@juicesharp/rpiv-workflow";
201
- import { readFile, writeFile } from "node:fs/promises";
202
- import { join } from "node:path";
203
-
204
- const merge = produces.script({
205
- outputSchema: typeboxSchema(Type.Object({ planPath: Type.String() })),
206
- run: async (ctx: ScriptContext) => {
207
- const upstream = ctx.input?.artifacts ?? [];
208
- const bodies = await Promise.all(
209
- upstream
210
- .filter((a) => a.handle.kind === "fs")
211
- .map((a) => readFile(join(ctx.cwd, (a.handle as { path: string }).path), "utf-8")),
212
- );
213
- const planPath = `.rpiv/artifacts/plans/${Date.now()}.md`;
214
- await writeFile(join(ctx.cwd, planPath), bodies.join("\n\n---\n\n"));
215
- return {
216
- kind: "plan",
217
- artifacts: [{ handle: fs(planPath), role: "primary" }],
218
- data: { planPath },
219
- };
220
- },
221
- });
222
- ```
223
-
224
- The runner stamps `meta` (`stage`, `stageNumber`, `ts`, `runId`) on the returned envelope — authors only fill `kind` + `artifacts` + `data`. The first artifact (if any) becomes the rolling primary so downstream stages inherit it via `ctx.input.artifacts[0]` and `ctx.state.primaryArtifact`.
225
-
226
- ### `acts.script` — bump a file's version field
227
-
228
- ```ts
229
- import { acts, type ScriptContext } from "@juicesharp/rpiv-workflow";
230
- import { readFile, writeFile } from "node:fs/promises";
231
- import { join } from "node:path";
232
-
233
- const bumpVersion = acts.script({
234
- run: async (ctx: ScriptContext) => {
235
- const path = join(ctx.cwd, "package.json");
236
- const pkg = JSON.parse(await readFile(path, "utf-8")) as { version: string };
237
- const [major, minor, patch] = pkg.version.split(".").map(Number);
238
- pkg.version = `${major}.${minor}.${(patch ?? 0) + 1}`;
239
- await writeFile(path, `${JSON.stringify(pkg, null, 2)}\n`);
240
- },
241
- });
242
- ```
243
-
244
- The runner synthesises a `{ kind: "side-effect", artifacts: [], data: {} }` envelope for the audit row. The rolling primary artifact slot is preserved — a downstream stage still inherits whatever the upstream `produces` stage set, same posture as a skill-based `acts(...)`.
245
-
246
- ### `terminal.script` — post-run cleanup that doesn't see the artifact
247
-
248
- ```ts
249
- import { terminal, type ScriptContext } from "@juicesharp/rpiv-workflow";
250
-
251
- const notifySlack = terminal.script({
252
- run: async (ctx: ScriptContext) => {
253
- // ctx.input is the upstream row's envelope — `ctx.state.primaryArtifact`
254
- // is NOT consulted (terminal.* opts out of inheritance). Any stage that
255
- // runs after also starts without an inherited handle.
256
- await fetch(process.env.SLACK_WEBHOOK!, {
257
- method: "POST",
258
- body: JSON.stringify({ text: `Run ${ctx.state.originalInput} complete.` }),
259
- });
260
- },
261
- });
262
- ```
263
-
264
- Like `terminal()`, the script variant desugars to `acts.script({ ...opts, inheritsArtifacts: false })`: the rolling primary slot is cleared on success so downstream stages start from a clean inheritance state. The right answer for a final cleanup / summary / post-run notification stage that shouldn't be coupled to the upstream chain.
265
-
266
- ### Lifecycle parity
267
-
268
- Script stages fire the same lifecycle events as skill stages — `onStageStart` → (`onStageRetry`?) → `onStageEnd` | `onStageError` — with a `StageRef` discriminator of `kind: "script"` (vs `kind: "skill"`). The JSONL audit row carries the stage's record key in `stage` and omits the `skill` field entirely, so post-hoc readers distinguish the two paths by `row.skill === undefined`.
269
-
270
- A thrown `run()` body records a terminal failure attributed to the stage via `MSG_SCRIPT_THREW`; the run halts and `onStageError` fires.
271
-
272
- ## Programmatic registration
273
-
274
- Sibling packages contribute workflows at extension load:
275
-
276
- ```ts
277
- import { registerBuiltIns, type WorkflowHost } from "@juicesharp/rpiv-workflow";
278
- import { myWorkflows } from "./my-workflows.js";
279
-
280
- export default function (host: WorkflowHost): void {
281
- registerBuiltIns(myWorkflows);
282
- }
283
- ```
284
-
285
- You can keep using `ExtensionAPI` from `@earendil-works/pi-coding-agent` in the
286
- signature instead — it structurally satisfies `WorkflowHost`. Either choice
287
- works; the published types name only the workflow-owned port.
288
-
289
- These workflows are merged into the lowest layer (`built-in`); user/project overlays still override by name.
290
-
291
- ### Cross-package lifecycle (`registerLifecycle`)
292
-
293
- When another extension needs to observe every workflow run in the process — typically an overlay widget that visualises in-flight stages, a metrics emitter, or a side-effect bridge — register a listener bundle at extension load:
294
-
295
- ```ts
296
- import { registerLifecycle, type WorkflowHost } from "@juicesharp/rpiv-workflow";
297
-
298
- export default function (host: WorkflowHost): void {
299
- const dispose = registerLifecycle({
300
- onWorkflowStart: (ctx) => widget.open(ctx.runId, ctx.workflow, ctx.totalStages),
301
- onStageStart: (stage, ctx) => widget.markActive(ctx.runId, stage.name),
302
- onStageEnd: (stage, _o, ctx) => widget.markDone(ctx.runId, stage.name),
303
- onStageError: (stage, err, ctx)=> widget.markFailed(ctx.runId, stage.name, err),
304
- onWorkflowEnd: (result, ctx) => widget.close(ctx.runId, result.success),
305
- });
306
- // dispose() removes the bundle if the extension ever unloads.
307
- }
308
- ```
309
-
310
- Every fired event walks the registry in registration order, then the per-call bundle (if any) the embedder passed to `runWorkflow(ctx, { lifecycle })`. Multiple bundles coexist; one bundle throwing does not affect siblings or halt the run (throws are caught and logged via `ctx.ui.notify(..., "warning")`).
311
-
312
- The registry is anchored on `Symbol.for("@juicesharp/rpiv-workflow:lifecycle")`, mirroring the `registerBuiltIns` pattern, so cross-package module resolution still shares one slot. Snapshot semantics: each event observes the registry as it stands at that instant — a registration made mid-event applies to subsequent events, not the in-flight one.
313
-
314
- `@juicesharp/rpiv-pi` is the reference consumer (overlay widget that visualises in-flight runs).
315
-
316
- ## Host boundary
317
-
318
- `rpiv-workflow`'s public type surface names **zero** `@earendil-works/pi-coding-agent`
319
- types. The runtime declares three workflow-owned port interfaces in
320
- `./host.js`:
321
-
322
- - `WorkflowHost` — registry-level host (default export, continue-policy
323
- sends, skill-registration preflight).
324
- - `WorkflowHostContext` — per-command ctx passed to `runWorkflow`; also the
325
- base shape for the replacement ctx delivered to `newSession`'s
326
- `withSession` callback. `sendUserMessage` is optional at this level (the
327
- outer command ctx Pi delivers to `/wf` doesn't carry one).
328
- - `WorkflowSessionContext` — the narrower subtype delivered inside
329
- `withSession`, where `sendUserMessage` is guaranteed present.
330
-
331
- Pi's `ExtensionAPI` / `ExtensionCommandContext` / `ReplacedSessionContext`
332
- structurally satisfy these ports, so existing embedders pass their Pi
333
- handles through unchanged. A
334
- compile-time tripwire (`host.test.ts`) fails immediately if Pi's API ever
335
- drifts below the port shapes. A future non-Pi host implements the three
336
- port interfaces and drives the runtime without any pi-coding-agent
337
- dependency.
338
-
339
- ## Programmatic runner
340
-
341
- Embedders drive workflows from outside `/wf`:
342
-
343
- ```ts
344
- import { runWorkflow } from "@juicesharp/rpiv-workflow";
345
-
346
- const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
347
- workflow: myFlow,
348
- input: "task description",
349
- host: piHost, // any WorkflowHost-shaped value
350
- });
351
- ```
352
-
353
- Returns `{ runId, stagesCompleted, success }`. Past-run inspection uses `listRuns(cwd)` / `readHeader` / `readLastStage` / `listArtifacts`.
354
-
355
- ### By name
356
-
357
- For the common "just run this workflow by name" case, `runWorkflowByName` folds the `loadWorkflows` → `findWorkflow` → `runWorkflow` dance into one call:
358
-
359
- ```ts
360
- import { runWorkflowByName } from "@juicesharp/rpiv-workflow";
361
-
362
- const result = await runWorkflowByName(ctx, "research", "add dark mode", { host: piHost });
363
- if (!result.success) ctx.ui.notify(result.error ?? "workflow failed", "error");
23
+ pi install npm:@juicesharp/rpiv-workflow
364
24
  ```
365
25
 
366
- It never throws — every expected failure comes back in the same `RunWorkflowResult` envelope: error-severity load issues refuse the run, and an unknown name returns a failure envelope listing the available workflows. The fourth argument is `RunWorkflowByNameOptions` (`RunWorkflowOptions` minus `workflow`/`input`), so `host`, `trigger`, `lifecycle`, and the iteration caps thread through unchanged.
367
-
368
- ### Resume by run-id
369
-
370
- `resumeWorkflowByRunId` is the resume-side counterpart — it folds the `resolveRun` → `loadWorkflows` → `findWorkflow` → `resumeWorkflow` dance into one call keyed on the run-id (the `<run-id>` slug, exactly what `listRuns()` returns on `RunSummary.runId`). The run's header already names its workflow, so you supply only the id:
371
-
372
- ```ts
373
- import { resumeWorkflowByRunId, listRuns } from "@juicesharp/rpiv-workflow";
374
-
375
- const [latest] = listRuns(ctx.cwd).filter((r) => !r.success); // e.g. a past failed run
376
- if (latest) {
377
- const result = await resumeWorkflowByRunId(ctx, latest.runId, { host: piHost });
378
- if (!result.success) ctx.ui.notify(result.error ?? "resume failed", "error");
379
- }
380
- ```
26
+ Restart your Pi session.
381
27
 
382
- Like `runWorkflowByName` it never throws: an unresolvable run-id, error-severity load issues, or a workflow that's no longer registered each come back as a failure envelope. The suffix is `ByRunId`, not `ByName`, on purpose — you resume one specific past *run* (a workflow has many), so the key is the run-id, not a workflow name. The third argument is `ResumeWorkflowByRunIdOptions` (`ResumeWorkflowOptions` minus `workflow`/`header`/`ref`).
28
+ ## Quick start
383
29
 
384
- > **Notify contract.** `resumeWorkflow` and `resumeWorkflowByRunId` are pure — they return envelopes and never notify, matching `runWorkflow`/`runWorkflowByName`. A no-JSONL refusal (bad run-id, load error, workflow gone, unreconstructable trail) carries **no `runId`** on the envelope; an in-run failure carries one and was already surfaced by the stage machinery's JSONL failure row. The `/wf` command uses exactly that `!result.runId` discriminator to notify the former once without double-notifying the latter.
30
+ `/wf` runs skills you already have installed — this package ships none of its
31
+ own. The fastest way to see a real run is the sibling that bundles both skills
32
+ and workflows:
385
33
 
386
- ### Cancellation
387
-
388
- Pass an `AbortSignal` to cancel a long run cooperatively:
389
-
390
- ```ts
391
- const controller = new AbortController();
392
- const p = runWorkflow(ctx, { workflow, input, host: piHost, signal: controller.signal });
393
- // …later, from a timeout / webhook / user action:
394
- controller.abort();
395
- ```
396
-
397
- The runner checks the signal at the **between-stage** seam — before the start stage and before every routed next stage. On abort it records an `"aborted"` terminal row for the stage about to run and resolves with `{ success: false }`. It does **not** interrupt a stage already streaming (Pi owns the live session), so cancellation lands at the next stage boundary, not mid-stage. Threads through `runWorkflowByName` / `resumeWorkflowByRunId` unchanged.
398
-
399
- ### Lifecycle
400
-
401
- Pass `lifecycle` to observe stage progress in-process without re-reading the JSONL:
402
-
403
- ```ts
404
- import { runWorkflow } from "@juicesharp/rpiv-workflow";
405
-
406
- const result = await runWorkflow(ctx, {
407
- workflow: myFlow,
408
- input: "task description",
409
- host: piHost,
410
- trigger: { kind: "external", source: "webhook", ref: "evt_42" },
411
- lifecycle: {
412
- onStageStart: (stage, ctx) => console.log("→", stage.name, ctx.runId),
413
- onStageEnd: (stage, output) => console.log("✓", stage.name, output.kind),
414
- onWorkflowEnd: (result) => console.log("done:", result.success),
415
- },
416
- });
34
+ ```sh
35
+ pi install npm:@juicesharp/rpiv-pi
417
36
  ```
418
37
 
419
- Every callback receives a `LifecycleContext` with `runId`, `workflow`, `totalStages`, the `trigger` metadata, and a deep-readonly `RunView` snapshot of the run's data channels. Events fire AFTER their JSONL row lands on disk, so a listener that calls `readLastStage(cwd, ctx.runId)` is guaranteed to see the just-recorded row. Callbacks may be async — the runner awaits them before advancing, giving back-pressure for free. Throws are caught + surfaced through `ctx.ui.notify(..., "warning")`; they never halt the run.
420
-
421
- Available callbacks: `onWorkflowStart`, `onStageStart`, `onStageEnd`, `onStageRetry`, `onStageError`, `onRoute`, `onLoopStart`, `onUnitStart`, `onUnitEnd`, `onLoopCap`, `onWorkflowEnd`. See the `LifecycleListeners` JSDoc for the per-event payload.
422
-
423
- ### Trigger
424
-
425
- `trigger` defaults to `{ kind: "programmatic" }`. Set it explicitly when spawning a run from a cron job, webhook handler, or sibling extension — the value lands in the JSONL header (`WorkflowHeader.trigger`), surfaces on `RunSummary.trigger` for past-run readers, and is threaded into every `LifecycleContext`:
426
-
427
- ```ts
428
- type RunTrigger =
429
- | { kind: "command"; name: string; meta?: Record<string, unknown> }
430
- | { kind: "programmatic"; source?: string; meta?: Record<string, unknown> }
431
- | { kind: "external"; source: string; ref?: string; meta?: Record<string, unknown> };
432
38
  ```
433
-
434
- `/wf` sets `{ kind: "command", name: "wf" }` itself — embedders only set this field for non-`/wf` entry points. Pi is single-active-session: external trigger sources MUST gate their own spawning if a run is already in flight; the runtime does not enforce a process-wide mutex.
435
-
436
- ## Outcomes — collectors and parsers
437
-
438
- Each `produces` stage wires an `Outcome` (formerly `OutputSpec` — the old name remains as a deprecated alias for one release) that tells the runtime three things:
439
-
440
- ```ts
441
- interface Outcome<Snapshot, Kind, Data> {
442
- name?: string; // CATEGORISE — the publish slot in state.named (optional)
443
- collector: ArtifactCollector<Snapshot>; // ENUMERATE — what did the stage produce?
444
- parser?: ArtifactParser<Snapshot, Kind, Data>; // INTERPRET — what's the typed data channel?
445
- }
39
+ /wf ship "add a --json flag to the export command"
446
40
  ```
447
41
 
448
- `collector.collect(ctx)` returns the artifacts the stage emitted. `parser.parse(ctx)` (optional) turns them into the typed `output.data` downstream stages narrow on. With no parser, `output.data` is the artifact list itself (`kind = "artifacts"`). When `name` is set, every stage wired with this outcome publishes onto `state.named[name]` — the convergence mechanism behind [`reads:`](#multi-input-stages--reads-and-the-named-publish-registry); when omitted, stages publish under their record key.
449
-
450
- There is no framework default for `produces` — load-time validation rejects a stage without an outcome. The `.rpiv/artifacts/<bucket>/<file>.md` layout is an rpiv convention, not a framework truth; pair with [`@juicesharp/rpiv-pi`](../rpiv-pi) for `rpivArtifactMdOutcome`, or wire your own.
451
-
452
- ### Authoring a collector
42
+ The run starts detached and your prompt comes straight back. Every step appends
43
+ to `.rpiv/workflows/runs/<run-id>.jsonl`, so you can walk away and resume later.
453
44
 
454
- The collector is the user-supplyable primitive — one method, one return type:
45
+ To write your own instead, put a workflow at `.rpiv/workflows/config.ts` naming
46
+ skills already on your machine (check `~/.pi/agent/skills/`):
455
47
 
456
48
  ```ts
457
- import { defineCollector, opaque, type Artifact } from "@juicesharp/rpiv-workflow";
49
+ import { defineWorkflow, acts, terminal } from "@juicesharp/rpiv-workflow";
458
50
 
459
- export const linearTicketCollector = defineCollector((ctx) => {
460
- const id = parseLinearIdFromBranch(ctx.branch);
461
- if (!id) return { kind: "fatal", message: "stage did not emit a Linear ticket id" };
462
- return { kind: "ok", artifacts: [{ handle: opaque(id), role: "ticket" }] };
463
- });
464
- ```
465
-
466
- Collectors that need a pre-stage snapshot declare a `snapshot` hook — its return value lands on `ctx.snapshot` for the matching `collect` call. Compose the bundled `gitHeadSnapshot` into any snapshot:
467
-
468
- ```ts
469
- import { defineCollector, fs, gitHeadSnapshot, type GitHeadSnapshot } from "@juicesharp/rpiv-workflow";
470
-
471
- const codegenCollector = defineCollector<GitHeadSnapshot | undefined>({
472
- snapshot: gitHeadSnapshot,
473
- collect: async (ctx) => {
474
- if (!ctx.snapshot) return { kind: "ok", artifacts: [] };
475
- const files = await diffWorkspace(ctx.cwd, ctx.snapshot.baselineSha);
476
- return { kind: "ok", artifacts: files.map((p) => ({ handle: fs(p), role: "generated" })) };
477
- },
51
+ export default defineWorkflow({
52
+ name: "review-and-ship",
53
+ start: "code-review",
54
+ stages: { "code-review": acts(), commit: terminal() },
55
+ edges: { "code-review": "commit", commit: "stop" },
478
56
  });
479
57
  ```
480
58
 
481
- ### Bundled collector catalog
482
-
483
- The framework ships only host-agnostic primitives — no Pi tool-name defaults, no `.rpiv/artifacts/` defaults, no domain helpers. Wrap them or compose with `unionCollectors` to build your own conventions. Grouped by discovery model:
484
-
485
- **Scan the agent's text**
486
-
487
- | Collector | Signature | What it does |
488
- | --- | --- | --- |
489
- | `transcriptPathCollector` | `({ pattern: RegExp })` | Scans assistant text for the last regex match; emits one `fs` artifact. Pattern is required — no framework default. |
490
- | `directoryPathCollector` | `({ dir, ext? })` | Ergonomic wrapper over `transcriptPathCollector` for the `<dir>/<file>.<ext>` shape. |
491
- | `urlCollector` | `({ pattern? })` | Scans for `https?://…`; emits a `url` handle. Default pattern is RFC-3986-flavoured; override for narrower hosts. |
492
-
493
- **Observe tool use**
494
-
495
- | Collector | Signature | What it does |
496
- | --- | --- | --- |
497
- | `toolCallCollector` | `({ match, toArtifact })` | Walks every `tool_use` part; emits N artifacts via the author's mappers. Universal across any Pi tool name. |
498
-
499
- **Diff the filesystem**
500
-
501
- | Collector | Signature | What it does |
502
- | --- | --- | --- |
503
- | `workspaceDiffCollector` | `({ filter? })` | Captures `git status --porcelain` pre-stage, diffs post-stage. One `fs` artifact per file the stage touched. Fail-soft when not a git repo. |
504
-
505
- **Git**
506
-
507
- | Collector | Signature | What it does |
508
- | --- | --- | --- |
509
- | `gitCommitCollector` | — | Detects a new HEAD commit vs. the pre-stage snapshot; emits an `opaque(sha)` artifact tagged `role: "commit"`. |
510
-
511
- **Composition + empty**
512
-
513
- | Collector | Signature | What it does |
59
+ Each stage key is the skill name; `acts()` runs a skill for its side effects,
60
+ `terminal()` does the same for a stage that carries nothing forward. Schemas,
61
+ artifact outcomes, and predicate routing are in the
62
+ [authoring reference](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-workflow/docs/workflow-authoring.md).
63
+
64
+ | Command | What it does |
65
+ | --- | --- |
66
+ | `/wf` | Preview every loaded workflow |
67
+ | `/wf <name>` | Preview one workflow's stage graph |
68
+ | `/wf <name> "<input>"` | Run it detached — your prompt returns immediately |
69
+ | `/wf @<ref>` | Resume a past run by run-id, `--name` alias, or `.jsonl` path |
70
+
71
+ Add `--name <slug>` as the first or last token to give a run an alias you can
72
+ resume by. With no workflows registered anywhere, `/wf` says so and stops.
73
+
74
+ ## What you get
75
+
76
+ - **Chain skills you already have** — the runner dispatches `/skill:<name>`
77
+ through Pi's native loader, so anything in `~/.pi/agent/skills/`,
78
+ `<cwd>/.pi/skills/`, or a settings-declared `skillPaths[]` is fair game.
79
+ - **Every run resumes from disk** — each step appends to
80
+ `.rpiv/workflows/runs/<run-id>.jsonl`, and `/wf @<ref>` re-enters at the
81
+ pending step, replaying already-finished branches from the trail rather than
82
+ re-running them.
83
+ - **Stages run detached and in parallel** — each stage, and each parallel
84
+ branch, gets its own child session, up to the host's `maxConcurrency`.
85
+ - **Bad stage output never reaches the next stage** — `outputSchema` /
86
+ `inputSchema` are [Standard Schema v1](https://standardschema.dev) values (Zod,
87
+ Valibot, ArkType, TypeBox), checked at both seams with bounded retries.
88
+ - **Routing is data-driven and auditable** — `gate()` on numeric fields,
89
+ `match()` on enums, `defineRoute()` for arbitrary TypeScript, and every
90
+ no-match writes a note on the audit row instead of falling through silently.
91
+ - **Loops without hand-rolled state machines** — repeat a stage across many
92
+ items at once, or re-run it until a TypeScript or model check says it is done.
93
+ - **Team-wide skill swaps in one line** — `skillAliases: { commit: "attributed-commit" }`
94
+ rewrites the skill across every loaded workflow, built-ins included.
95
+
96
+ ## Configuration
97
+
98
+ Workflows are TypeScript, loaded with `jiti` — no build step. Project config
99
+ lives at `<cwd>/.rpiv/workflows/config.ts`, user config at
100
+ `~/.config/rpiv-workflow/config.ts`; project config wins where both define the
101
+ same workflow name.
102
+
103
+ The stage knobs most people touch:
104
+
105
+ | Key | What it does | Default |
514
106
  | --- | --- | --- |
515
- | `unionCollectors(...cs)` | — | Run N collectors, concatenate artifacts. Fatal only when every sub-collector fataled. |
516
- | `noopCollector` | — | Always returns `{ kind: "ok", artifacts: [] }`. The primitive `sideEffectOutcome` is built directly from it: `sideEffectOutcome = { collector: noopCollector }`. |
517
-
518
- Handle constructors: `fs(path)`, `url(href)`, `opaque(id)`, `inline(bytes, mime?)` — replace the verbose `{ kind: …, … }` literal at call sites. Serialise any handle to its canonical string with `handleToString`.
519
-
520
- ### Bundled parser catalog
521
-
522
- | Parser | Output `kind` | Output `data` |
523
- | --- | --- | --- |
524
- | `jsonBodyParser` | `"json"` | `JSON.parse` of the primary `fs` artifact's body (`unknown` — narrow via `outputSchema`). |
525
- | `gitCommitParser` | `"git-commit"` | `GitCommitData` (sha, prevSha, subject, filesChanged) parsed from `git`. |
526
-
527
- Format-specific parsers (markdown frontmatter, YAML, TOML, …) live in the convention layer that owns them — rpiv-pi ships its own `frontmatterParser`.
528
-
529
- ### Wiring an outcome onto a stage
530
-
531
- ```ts
532
- import {
533
- produces, defineWorkflow,
534
- toolCallCollector, jsonBodyParser, fs,
535
- } from "@juicesharp/rpiv-workflow";
536
-
537
- const writeFileCollector = toolCallCollector({
538
- match: (tc) => tc.name === "write_file" || tc.name === "edit",
539
- toArtifact: (tc) => ({ handle: fs(String(tc.input.path ?? tc.input.target_file)) }),
540
- });
541
-
542
- export default defineWorkflow({
543
- name: "scaffold",
544
- start: "generate",
545
- stages: {
546
- generate: produces({
547
- outcome: { collector: writeFileCollector, parser: jsonBodyParser },
548
- }),
549
- },
550
- edges: { generate: "stop" },
551
- });
552
- ```
107
+ | `sessionPolicy` | `"fresh"` starts a clean session; `"continue"` forks the predecessor's | `"fresh"` |
108
+ | `onInvalid` | What to do when `outputSchema` rejects: `"retry"` or `"halt"` | `"retry"` |
109
+ | `maxRetries` | Validation retries per stage, clamped to 1–3 | `1` |
110
+ | `validateTimeoutMs` | Ceiling on one validate call, clamped to 1 s–30 min | `300000` |
111
+ | `outcome` | How the stage's artifacts are collected and parsed — required on `produces()` | none |
553
112
 
554
- ## Validators: sync vs async
113
+ > Config and pack files are TypeScript modules whose top-level code is evaluated
114
+ > on load — the same trust boundary as an npm post-install script. Diff them
115
+ > before running `/wf` in a repository you do not control.
555
116
 
556
- `inputSchema` and `outputSchema` are [Standard Schema v1](https://standardschema.dev) values — Zod, Valibot, ArkType, TypeBox (via `typeboxSchema`), or hand-rolled `{ "~standard": { validate } }` objects. The runner awaits the schema's `~standard.validate` at both seams, so it works with sync and async schemas alike.
117
+ ## Reference
557
118
 
558
- **Default to sync.** Pure shape contracts (`Type.Object({ … })`, `z.object({ … })`) resolve in one microtask, give the agent precise retry diagnostics, and have no failure mode beyond "this isn't the shape you said." For 95% of stages this is the right answer.
119
+ - [Workflow basics](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-workflow/docs/workflow-basics.md) — `/wf` invocation forms, `--name` and `@resume`, where every file resolves, layer merging, config vs pack files, skill aliases, run state, and the glossary.
120
+ - [Authoring reference](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-workflow/docs/workflow-authoring.md) — the full DSL: stage factories, loops, `verify` / `panel`, script and prompt stages, edge targets, routing, outcomes with the collector and parser catalogs, multi-input stages, validators, and the load-time validation rules.
121
+ - [Embedding](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-workflow/docs/embedding.md) — host ports, the entry-point map, `registerBuiltIns` / `registerLifecycle`, the programmatic runner and resume API, cancellation, triggers, and past-run inspection.
559
122
 
560
- **Reach for async when correctness needs I/O.** Examples that don't fit the sync model:
561
- - "the path in the output must actually exist on disk" — `fs.access` is async.
562
- - "the spec the agent emitted must validate against a live endpoint" — `fetch` is async.
563
- - you're already on an async-by-default schema lib (ArkType's deeply-async paths).
123
+ ## Requirements
564
124
 
565
- The contract is identical — author an async `~standard.validate` and the runner awaits it. A schema whose Promise never settles is bounded by the stage's `validateTimeoutMs` (default 5 min); a rejected Promise surfaces as a clean stage halt, attributed to the stage, with the same error class as a shape-failure halt. No opt-in flag, no parallel code path.
125
+ Node ≥ 22. No native modules, no API key, and no model selection of its own —
126
+ stages dispatch through your host's session.
566
127
 
567
- > Keep validation separate from the collector + parser. The collector's job is "what did the agent produce?" (enumerate); the parser's job is "parse it into typed data" (shape). The validator's job is "is the result correct?" (check + verify). With async validators available you don't have to push I/O verification into a custom collector/parser — keep them pure and put correctness checks on `outputSchema`.
128
+ ## Related
568
129
 
569
- ## Glossary
130
+ - [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi) —
131
+ supplies the detached SDK executor, the terminal-keystroke abort, and five
132
+ bundled workflows (`ship`, `arch`, `vet`, `polish`, `build`).
570
133
 
571
- One canonical name per concept. Where two words exist for the same thing, the split is deliberate: one is the **authoring surface** (what you type in a workflow file), the other is the **data vocabulary** (what lands in rows, envelopes, and types).
134
+ ## License
572
135
 
573
- | Term | Meaning |
574
- |------|---------|
575
- | **Workflow** | The typed graph: a name, a `start` stage, a `stages` record, an `edges` table. Built with `defineWorkflow`, loaded from config layers or registered programmatically. |
576
- | **Stage** | One node of the graph — a unit of dispatch (skill session, prompt, or script). Two kinds: `"produces"` and `"side-effect"`. |
577
- | **Kind vs. factory** | `kind` is the persisted data discriminator (`"produces"` \| `"side-effect"`); the factories are authoring verbs: `produces()` → `"produces"`, `acts()` → `"side-effect"`, `terminal()` → `"side-effect"` + `inheritsArtifacts: false`. `acts` is a verb because it reads naturally in a stage record (`commit: acts()`); `"side-effect"` is descriptive because it reads naturally in rows and output envelopes. `terminal` is **not** a third kind — it's `acts` plus an artifact-isolation flag. |
578
- | **Run** | One execution of a workflow: a `runId`, an append-only JSONL run file (the system of record for resume), and the in-memory state the runner threads. |
579
- | **Chain** | The path a run walks through the graph — stage activations following `edges` from `start` until `"stop"` or a halt. Loops add generations *within* one chain position. |
580
- | **Output** | The envelope one stage activation hands downstream: `{ kind, data, meta, artifacts }` (`Output<K, D>`, `output.ts`). What predicates, routes, downstream prompts, and the audit log see. |
581
- | **Outcome** | The producer-side declaration of *how* a stage's Output gets built from a session: `{ collector, parser? }` (`Outcome`, `output-spec.ts`). The collector enumerates artifacts; the parser interprets them into `data`. |
582
- | **Verdict** | A judge's Output (`type Verdict = Output`). In `assess` / `verify` loops the judge emits a verdict that `done` reads; verdicts are recorded for resume but never become the stage result. |
583
- | **Contract** | A skill contract — what a skill `consumes` / `produces`. Declared by the skill's owner or harvested from stage declarations; adjudicated at load time (`canCompose`, the validator) to check composition. |
136
+ MIT — see [LICENSE](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-workflow/LICENSE).