@juicesharp/rpiv-workflow 1.20.0 → 2.1.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.
Files changed (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
@@ -0,0 +1,341 @@
1
+ # Embedding the Workflow Runtime
2
+
3
+ How to drive `@juicesharp/rpiv-workflow` from code instead of `/wf`: the host ports you implement, the registrars siblings call at extension load, the programmatic runner, and the lifecycle stream.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Entry points](#entry-points)
8
+ - [Host boundary](#host-boundary)
9
+ - [Contributing built-in workflows](#contributing-built-in-workflows)
10
+ - [The execution-host seam](#the-execution-host-seam)
11
+ - [Programmatic runner](#programmatic-runner)
12
+ - [Resuming a run](#resuming-a-run)
13
+ - [Cancellation](#cancellation)
14
+ - [Cross-package lifecycle](#cross-package-lifecycle)
15
+ - [Trigger metadata](#trigger-metadata)
16
+ - [Inspecting past runs](#inspecting-past-runs)
17
+
18
+ ## Entry points
19
+
20
+ The package publishes five entry points. Per-module deep imports
21
+ (`from "@juicesharp/rpiv-workflow/api.js"`) are **not** supported across the
22
+ package boundary.
23
+
24
+ | Entry | Contents | When to import it |
25
+ | --- | --- | --- |
26
+ | `@juicesharp/rpiv-workflow` | Everything in `/registration` plus the runner (`runWorkflow`, `runWorkflowByName`, `resumeWorkflow`, `resumeWorkflowByRunId`) | Embedders that execute runs |
27
+ | `@juicesharp/rpiv-workflow/registration` | The runner-free surface: DSL, loader, outcomes, handles, validators, host port types. The single canonical enumeration of the public API | Authoring, loading, validating — skips the ~530 ms engine graph |
28
+ | `@juicesharp/rpiv-workflow/startup` | Only the registrars a sibling wires at extension load (~9 ms) | Extension `default` exports |
29
+ | `@juicesharp/rpiv-workflow/runner` | The runner surface on its own, plus `StagePreflightError` and `MAX_BACKWARD_JUMPS` | Callers that already hold the DSL elsewhere |
30
+ | `@juicesharp/rpiv-workflow/internal` | Test-only seams (`recordStage`, registry resets) | Tests |
31
+
32
+ The Pi extension `default` entry is `./extension.ts`, not the barrel — loading
33
+ the extension registers `/wf` and the docs-protocol hook without evaluating the
34
+ runtime re-exports.
35
+
36
+ ## Host boundary
37
+
38
+ The package's public type surface names **zero** `@earendil-works/pi-coding-agent`
39
+ types, and imports no value from it. Every host capability the runtime needs is a
40
+ workflow-owned port declared in `./host.js`:
41
+
42
+ | Port | What it is | Members the runtime touches |
43
+ | --- | --- | --- |
44
+ | `WorkflowHost` | Registry-level host — the value a Pi extension's `default` receives | `registerCommand`, `getCommands` |
45
+ | `WorkflowHostContext` | The per-run **executor** ctx handed to `runWorkflow` | `cwd`, `hasUI`, `ui.notify`, `sessionManager.{getBranch,getSessionId,getSessionFile}`, `waitForIdle`, `signal?`, `maxConcurrency`, `spawnChild` |
46
+ | `WorkflowLauncherContext` | `Omit<WorkflowHostContext, "spawnChild" \| "maxConcurrency">` — the **observer** surface the `/wf` handler receives | everything above minus the two executor members |
47
+ | `WorkflowSessionContext` | The child ctx delivered to `spawnChild`'s `withSession` callback; adds a guaranteed sender | `sendUserMessage`, optional `toolTimeout()` |
48
+
49
+ Pi's `ExtensionAPI` structurally satisfies `WorkflowHost` and its
50
+ `ExtensionCommandContext` satisfies the observer surface — embedders pass their
51
+ existing Pi handles through unchanged. The full executor port
52
+ (`spawnChild` + `maxConcurrency`) is satisfied by `SdkWorkflowHost` in
53
+ [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi). A
54
+ compile-time tripwire (`host.test.ts`) fails immediately if Pi's types ever drift
55
+ below the observer port; the executor-satisfaction assertion lives in rpiv-pi,
56
+ because rpiv-workflow must not import rpiv-pi.
57
+
58
+ ### `spawnChild`
59
+
60
+ ```ts
61
+ spawnChild<T>(options: {
62
+ prompt: string;
63
+ model?: ModelSelection; // { model?: string; thinking?: "off" | … | "xhigh" }
64
+ signal?: AbortSignal; // abort THIS child mid-flight
65
+ reattach?: { sessionFile: string }; // open the persisted session in place
66
+ fork?: { sessionFile: string }; // fork it into a new child (sessionPolicy: "continue")
67
+ unitIndex?: number; // fan-out unit hint for lane-aware hosts
68
+ withSession: (child: WorkflowSessionContext) => Promise<T>;
69
+ }): Promise<T>;
70
+ ```
71
+
72
+ The parent ctx stays valid — there is no session swap. The runner may have up to
73
+ `maxConcurrency` calls in flight at once (`1` ⇒ sequential). `model` is applied by
74
+ the host at session creation, not via global mutation; the key is host-opaque and
75
+ resolved through the host's own registry. At most one of `reattach` / `fork` is
76
+ set, and both suppress the initial `prompt` send.
77
+
78
+ A non-Pi host implements these ports and drives the runtime with no
79
+ pi-coding-agent dependency at all.
80
+
81
+ ## Contributing built-in workflows
82
+
83
+ Sibling packages contribute workflows into the lowest merge layer at extension
84
+ load. User and project overlays still override them by workflow name.
85
+
86
+ ```ts
87
+ import { registerBuiltIns } from "@juicesharp/rpiv-workflow/startup";
88
+ import type { WorkflowHost } from "@juicesharp/rpiv-workflow/registration";
89
+ import { myWorkflows } from "./my-workflows.js";
90
+
91
+ export default function (host: WorkflowHost): void {
92
+ registerBuiltIns(myWorkflows);
93
+ }
94
+ ```
95
+
96
+ Building the workflow objects eagerly costs startup time. Prefer the provider
97
+ form with a dynamic import, so definitions are built on the first `/wf` rather
98
+ than on every session start:
99
+
100
+ ```ts
101
+ import { registerBuiltIns, registerBuiltInsProvider } from "@juicesharp/rpiv-workflow/startup";
102
+
103
+ export default function (): void {
104
+ registerBuiltInsProvider(async () => {
105
+ const { myWorkflows } = await import("./my-workflows.js");
106
+ registerBuiltIns(myWorkflows);
107
+ });
108
+ }
109
+ ```
110
+
111
+ Providers flush once and are memoised. A provider that throws is reported as a
112
+ load **warning** — the loader never throws.
113
+
114
+ `/startup` also carries the other registrars a sibling wires at load time:
115
+ `registerLifecycle`, `registerWorkflowExecutionHost`, `registerBucketKindMapping`,
116
+ `getBucketKindMappings`, `registerCompositionComparator`, `registerOutcomeDeriver`,
117
+ `registerSkillContracts`, `registerSkillContractsProvider`.
118
+
119
+ ## The execution-host seam
120
+
121
+ `registerWorkflowExecutionHost(provider)` injects the detached executor. The
122
+ provider's `createHost(observer, { runId, childSessionsDir, name?, workflow?, input? })`
123
+ returns `{ host, signal?, dispose? }`: the executor ctx that actually spawns child
124
+ sessions, an optional run-level abort signal, and a teardown the runner calls in
125
+ `finally`. An optional `resolveModel({ stage, skill })` on the provider fills each
126
+ child's `ModelSelection`.
127
+
128
+ The slot is anchored on `Symbol.for("@juicesharp/rpiv-workflow:executionHostProvider")`,
129
+ so a duplicated module instance still resolves to the same registration. **When no
130
+ provider is registered, the live ctx executes stages directly** — the runtime
131
+ degrades gracefully for non-Pi embedders and tests.
132
+
133
+ ## Programmatic runner
134
+
135
+ ```ts
136
+ import { runWorkflow } from "@juicesharp/rpiv-workflow";
137
+
138
+ const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
139
+ workflow: myFlow,
140
+ input: "task description",
141
+ host: piHost, // any WorkflowHost-shaped value
142
+ });
143
+ ```
144
+
145
+ `RunWorkflowOptions`:
146
+
147
+ | Option | Type | Default |
148
+ | --- | --- | --- |
149
+ | `workflow` | `Workflow` | required |
150
+ | `input` | `string` | required — passed to the start stage as its argument |
151
+ | `host` | `WorkflowHost` | none; used for the skill-registration preflight snapshot |
152
+ | `maxIterations` | `number` | `32` — run-wide cap on loop units of every kind |
153
+ | `maxBackwardJumps` | `number` | `2` per destination stage |
154
+ | `trigger` | `RunTrigger` | `{ kind: "programmatic" }` |
155
+ | `lifecycle` | `LifecycleListeners` | none |
156
+ | `signal` | `AbortSignal` | none |
157
+ | `resolveModel` | `(id: { stage, skill }) => ModelSelection \| undefined` | none ⇒ host default |
158
+ | `name` | `string` | none — human-readable run alias, rejected if already in use |
159
+
160
+ `RunWorkflowResult` comes back as `{ runId?, stagesCompleted, success, lastArtifact?, error?, termination? }`.
161
+ `termination` is the full-fidelity discriminated outcome —
162
+ `"running" | "completed" | "failed" | "aborted" | "cancelled"` — behind the
163
+ `success` / `error` projections, which cannot tell an abort from a cancellation.
164
+ `runId` and `termination` are undefined **only** for pre-flight rejections where no
165
+ JSONL file was ever created.
166
+
167
+ ### By name
168
+
169
+ `runWorkflowByName` folds `loadWorkflows` → `findWorkflow` → `runWorkflow` into
170
+ one call:
171
+
172
+ ```ts
173
+ import { runWorkflowByName } from "@juicesharp/rpiv-workflow";
174
+
175
+ const result = await runWorkflowByName(ctx, "research", "add dark mode", { host: piHost });
176
+ if (!result.success) ctx.ui.notify(result.error ?? "workflow failed", "error");
177
+ ```
178
+
179
+ It never throws — every expected failure returns the same `RunWorkflowResult`
180
+ envelope. Error-severity load issues refuse the run, and an unknown name returns a
181
+ failure envelope listing the available workflows. The fourth argument is
182
+ `RunWorkflowByNameOptions` = `Omit<RunWorkflowOptions, "workflow" | "input">`, so
183
+ `host`, `trigger`, `lifecycle`, `name`, and the caps thread through unchanged.
184
+
185
+ ## Resuming a run
186
+
187
+ `resumeWorkflowByRunId` is the resume-side counterpart, keyed on the run-id — the
188
+ `<run-id>` slug `listRuns()` returns on `RunSummary.runId`. The run's JSONL header
189
+ already names its workflow, so you supply only the id:
190
+
191
+ ```ts
192
+ import { resumeWorkflowByRunId, listRuns, readLastStage } from "@juicesharp/rpiv-workflow";
193
+
194
+ // listRuns returns filesystem order and carries no outcome — sort by `ts`, then
195
+ // ask the trail's last stage row whether the run actually finished.
196
+ const [latest] = listRuns(ctx.cwd).sort((a, b) => b.ts.localeCompare(a.ts));
197
+ const last = latest && readLastStage(ctx.cwd, latest.runId);
198
+ if (latest && last?.status !== "completed") {
199
+ const result = await resumeWorkflowByRunId(ctx, latest.runId, { host: piHost });
200
+ if (!result.success) ctx.ui.notify(result.error ?? "resume failed", "error");
201
+ }
202
+ ```
203
+
204
+ `RunSummary` is a header projection — `runId`, `workflow`, `input`, `ts`, and the
205
+ optional `trigger` / `name`. Whether a run succeeded is a property of its stage
206
+ rows, so read it with `readLastStage`, or pass an explicit run-id you already hold.
207
+
208
+ The suffix is `ByRunId`, not `ByName`, on purpose: you resume one specific past
209
+ *run*, and a workflow has many. The third argument is
210
+ `ResumeWorkflowByRunIdOptions` = `Omit<ResumeWorkflowOptions, "workflow" | "header" | "ref">`.
211
+ The lower-level `resumeWorkflow` takes the resolved `workflow`, `header`, and the
212
+ user's `ref` explicitly.
213
+
214
+ Like `runWorkflowByName`, neither throws: an unresolvable run-id, error-severity
215
+ load issues, a workflow that is no longer registered, or an unreconstructable trail
216
+ each come back as a failure envelope.
217
+
218
+ Run trails carry a schema version (`STATE_SCHEMA_VERSION = 2`). Resuming a run
219
+ recorded under a different version is **refused** with a version mismatch — there
220
+ is no in-place migration.
221
+
222
+ > **Notify contract.** `resumeWorkflow` and `resumeWorkflowByRunId` are pure — they
223
+ > return envelopes and never notify, matching `runWorkflow` / `runWorkflowByName`.
224
+ > A no-JSONL refusal (bad run-id, load error, workflow gone) carries **no `runId`**;
225
+ > an in-run failure carries one and was already surfaced by the stage machinery's
226
+ > JSONL failure row. `/wf` uses exactly that `!result.runId` discriminator to notify
227
+ > the former once without double-notifying the latter.
228
+
229
+ ## Cancellation
230
+
231
+ Pass an `AbortSignal` to cancel a long run:
232
+
233
+ ```ts
234
+ const controller = new AbortController();
235
+ const p = runWorkflow(ctx, { workflow, input, host: piHost, signal: controller.signal });
236
+ // …later, from a timeout / webhook / user action:
237
+ controller.abort();
238
+ ```
239
+
240
+ The signal is checked at the between-stage seam — before the start stage and
241
+ before every routed next stage — and is **also threaded into every `spawnChild`
242
+ call**, so an aborted run interrupts in-flight children rather than waiting for the
243
+ next stage boundary. The runner records an `"aborted"` terminal row for the stage
244
+ about to run and resolves with `{ success: false }`. It threads through
245
+ `runWorkflowByName` / `resumeWorkflowByRunId` unchanged.
246
+
247
+ When an execution-host provider supplies its own `signal`, the runner prefers the
248
+ caller's `options.signal` and falls back to the provider's.
249
+
250
+ ## Cross-package lifecycle
251
+
252
+ When another extension needs to observe every workflow run in the process — an
253
+ overlay widget, a metrics emitter, a side-effect bridge — register a listener
254
+ bundle at extension load:
255
+
256
+ ```ts
257
+ import { registerLifecycle } from "@juicesharp/rpiv-workflow/startup";
258
+ import type { WorkflowHost } from "@juicesharp/rpiv-workflow/registration";
259
+
260
+ export default function (host: WorkflowHost): void {
261
+ const dispose = registerLifecycle({
262
+ onWorkflowStart: (ctx) => widget.open(ctx.runId, ctx.workflow, ctx.totalStages),
263
+ onStageStart: (stage, ctx) => widget.markActive(ctx.runId, stage.name),
264
+ onStageEnd: (stage, _o, ctx) => widget.markDone(ctx.runId, stage.name),
265
+ onStageError: (stage, err, ctx) => widget.markFailed(ctx.runId, stage.name, err),
266
+ onWorkflowEnd: (result, ctx) => widget.close(ctx.runId, result.success),
267
+ });
268
+ // dispose() removes the bundle if the extension ever unloads.
269
+ }
270
+ ```
271
+
272
+ The same bundle shape is accepted per-call as `RunWorkflowOptions.lifecycle`.
273
+
274
+ ### Events
275
+
276
+ | Event | Fires |
277
+ | --- | --- |
278
+ | `onWorkflowStart(ctx)` | After the JSONL header lands, before the start stage's preflight |
279
+ | `onStageStart(stage, ctx)` | After preflight + skill check, before the session opens (or `run()` is called for script stages) |
280
+ | `onStageEnd(stage, output, ctx)` | After the stage's success row lands; `output` is the validated envelope |
281
+ | `onStageRetry(stage, attempt, ctx)` | After an `outputSchema` rejection, before the re-prompt; `attempt` is 1-based |
282
+ | `onStageError(stage, error, ctx)` | After a `"failed"` / `"aborted"` row lands. Terminal for the run |
283
+ | `onRoute(from, to, ctx, bypassed?)` | After an `EdgeFn` picks and its routing row lands. `to` may be the `"stop"` sentinel; `bypassed` lists not-taken recovery arms |
284
+ | `onLoopStart(stage, info, ctx)` | After `onStageStart`, before unit 1 (after the unit list is computed for fan-out) |
285
+ | `onUnitStart(stage, unit, ctx)` | Per unit, before the unit's session opens — produce **and** judge units |
286
+ | `onUnitEnd(stage, unit, output, ctx)` | Per unit, after the unit's row lands. Loop units never fire `onStageEnd` |
287
+ | `onUnitHalt(stage, unit, reason, ctx)` | Per unit, after a collect-all fan-out unit's non-terminal failed row lands — the unit halted, the run survives |
288
+ | `onLoopCap(stage, info, ctx)` | After an `onCap: "advance"` trip |
289
+ | `onWorkflowEnd(result, ctx)` | Last call; `result` is the same envelope `runWorkflow` returns |
290
+
291
+ Every callback receives a `LifecycleContext` with `cwd`, `runId`, `workflow`,
292
+ `totalStages`, the `trigger` metadata, a deep-readonly `RunView` snapshot, and — on
293
+ run-level events — `visited`, the distinct stage names already executed
294
+ (reconstructed from the trail on a resume, so a progress bridge can seed its
295
+ counter instead of restarting from zero).
296
+
297
+ Events fire **after** their JSONL row lands on disk, so a listener that calls
298
+ `readLastStage(cwd, ctx.runId)` is guaranteed to see the just-recorded row.
299
+ Callbacks may be async — the runner awaits them before advancing, which gives
300
+ back-pressure for free. Throws are caught and surfaced via
301
+ `ctx.ui.notify(..., "warning")`; they never halt the run.
302
+
303
+ Every fired event walks the global registry in registration order, then the
304
+ per-call bundle. Multiple bundles coexist and one throwing does not affect
305
+ siblings. The registry is anchored on
306
+ `Symbol.for("@juicesharp/rpiv-workflow:lifecycle")`, mirroring the built-in
307
+ registry, so cross-package module resolution shares one slot. Snapshot semantics:
308
+ each event observes the registry as it stands at that instant — a registration made
309
+ mid-event applies to subsequent events, not the in-flight one.
310
+
311
+ ## Trigger metadata
312
+
313
+ `trigger` defaults to `{ kind: "programmatic" }`. Set it explicitly when spawning a
314
+ run from a cron job, webhook handler, or sibling extension — the value lands in the
315
+ JSONL header (`WorkflowHeader.trigger`), surfaces on `RunSummary.trigger` for
316
+ past-run readers, and is threaded into every `LifecycleContext`:
317
+
318
+ ```ts
319
+ type RunTrigger =
320
+ | { kind: "command"; name: string; meta?: Record<string, unknown> }
321
+ | { kind: "programmatic"; source?: string; meta?: Record<string, unknown> }
322
+ | { kind: "external"; source: string; ref?: string; meta?: Record<string, unknown> };
323
+ ```
324
+
325
+ `/wf` sets `{ kind: "command", name: "wf" }` itself — embedders set this field only
326
+ for non-`/wf` entry points. Pi is single-active-session: external trigger sources
327
+ must gate their own spawning if a run is already in flight; the runtime does not
328
+ enforce a process-wide mutex.
329
+
330
+ ## Inspecting past runs
331
+
332
+ Row **writes** are runner-owned. Readers are public:
333
+
334
+ | Helper | Returns |
335
+ | --- | --- |
336
+ | `listRuns(cwd)` | `RunSummary[]` for every recorded run — `runId`, `workflow`, `input`, `ts`, `trigger?`, `name?`. Headers only: run outcome lives on stage rows, so there is no `success` field here |
337
+ | `resolveRun(cwd, ref)` | The `WorkflowHeader` for a run-id, run name, or `.jsonl` path |
338
+ | `readHeader(cwd, runId)` | The run's header row |
339
+ | `readLastStage(cwd, runId)` | The most recent stage row |
340
+ | `listArtifacts(cwd, runId)` | Every artifact the run recorded |
341
+ | `runFileFor(cwd, run)` | The absolute path of the run's JSONL file. `run` is anything carrying `runId` — a `RunSummary` or `WorkflowHeader` |
@@ -47,6 +47,12 @@ export default defineWorkflow({
47
47
  });
48
48
  ```
49
49
 
50
+ ### Typing model
51
+
52
+ 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.
53
+
54
+ 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.
55
+
50
56
  ## Stage factories
51
57
 
52
58
  Three factories for two stage kinds. Each factory returns a `StageDef` — pass overrides as needed.
@@ -57,7 +63,7 @@ Three factories for two stage kinds. Each factory returns a `StageDef` — pass
57
63
 
58
64
  ```typescript
59
65
  import { produces, typeboxSchema } from "@juicesharp/rpiv-workflow";
60
- import { Type } from "@sinclair/typebox";
66
+ import { Type } from "typebox";
61
67
 
62
68
  // Basic — just declare the outcome
63
69
  produces({ outcome: myOutcome })
@@ -92,7 +98,7 @@ produces({
92
98
  | `outcome` | (required) | `OutputSpec` — how the runtime collects + parses the artifact. |
93
99
  | `outputSchema` | none | Standard Schema v1 validator for `output.data`. Enables gate routing. |
94
100
  | `inputSchema` | none | Standard Schema v1 validator for inherited upstream `output.data`. Rejection halts immediately. |
95
- | `reads` | none | `ReadonlyArray<string>` — names this stage consumes from `state.named`. Switches the prompt to the labelled-flag form. See [Multi-input stages](#multi-input-stages). |
101
+ | `reads` | none | `ReadonlyArray<StageRead>` (`string` \| `fanin(name)`) — names this stage consumes from `state.named`. Switches the prompt to the labelled-flag form. See [Multi-input stages](#multi-input-stages). |
96
102
  | `onInvalid` | `"retry"` | `"retry"` (re-invoke up to `maxRetries`) or `"halt"` (fail fast). |
97
103
  | `maxRetries` | — | Max retries on schema rejection. |
98
104
  | `validateTimeoutMs` | — | Timeout for async schemas. |
@@ -138,7 +144,9 @@ const FRONTMATTER_PHASE_FANOUT = fanout({
138
144
  acts({ loop: FRONTMATTER_PHASE_FANOUT, reads: ["plans"] })
139
145
  ```
140
146
 
141
- A **`Unit`** is `{ prompt, label, id? }`: `prompt` is the body sent to the skill, `label` is the human display tag woven into the status line / per-unit toast / decorated audit row, and `id` is the stable audit identity (falls back to `label`). Set `id` when `label` may be reworded — the resume drift guard and post-hoc tooling join on `id ?? label`.
147
+ A **`Unit`** is `{ prompt, label, id?, deps? }`: `prompt` is the body sent to the skill, `label` is the human display tag woven into the status line / per-unit toast / decorated audit row, and `id` is the stable audit identity (falls back to `label`). Set `id` when `label` may be reworded — the resume drift guard and post-hoc tooling join on `id ?? label`.
148
+
149
+ **`deps` (fanout only)** lists the `id ?? label` identities this unit depends on. The wave scheduler assigns Kahn levels over those directed edges and dispatches level by level: a unit starts only once every unit it names has completed. Absent or empty ⇒ a root (wave 0). A dep matching no unit's `id ?? label`, or any cycle, halts the stage at the live entry. The sequential kinds ignore `deps` — `iterate`/`assess` consume the prior unit, so ordering is already implicit.
142
150
 
143
151
  **`FanoutContext` (what `units()` receives):** `{ cwd, artifact, state }` — `artifact` is the primary inherited from upstream (undefined when the loop stage is the entry point); `state` is the read-only `RunState`. A thrown error halts the stage attributed to it.
144
152
 
@@ -214,7 +222,7 @@ A `Judge` names a dispatchable grading session. Author it with `judge({ ... })`,
214
222
  - **Dispatch is `skill` XOR `prompt`** (exactly one): `skill` dispatches `/skill:<skill> <producerHandle>` with the latest producer artifact auto-injected as the input handle; `prompt` sends raw text (the author embeds the handle/output themselves). Setting both is ambiguous; setting neither has nothing to dispatch — both throw.
215
223
  - **`outcome` is required** — it validates the verdict and names its own dedicated `state.named` channel. That channel's `.name` MUST differ from the producer outcome's name (a workflow-level check, since it needs the producer's identity).
216
224
  - **≥1-artifact constraint**: the judge's collector MUST materialize at least one artifact (e.g. a JSON verdict file whose parser yields `{ done, feedback }`). A judge session that collects zero artifacts is a **fatal halt** — no retry, no soft-stop.
217
- - **Skill label for per-unit consumers**: a `skill` judge's units carry that skill name in `onUnitStart`/`onUnitEnd` and the JSONL rows; a `prompt` judge dispatches under the synthetic label **`<stageName>-judge`**. Per-unit listeners that key on the dispatched skill (e.g. rpiv-pi's `models.json` `skills.<name>` model-override rung) can target a prompt-judge by adding an entry under that synthetic name; with no entry, judge units run on the baseline model.
225
+ - **Skill label for per-unit consumers**: a `skill` judge's units carry that skill name in `onUnitStart`/`onUnitEnd` and the JSONL rows; a `prompt` judge dispatches under a synthetic label — **`<stageName>-judge`** on an `assess` site, **`<stageName>-verify`** on a `verify` site. Per-unit listeners that key on the dispatched skill (e.g. rpiv-pi's `models.json` `skills.<name>` model-override rung) can target a prompt-judge by adding an entry under that synthetic name; with no entry, judge units run on the baseline model.
218
226
 
219
227
  Keeping the termination predicate OFF `Judge` is what makes it reusable: both `assess()` and the per-stage `verify` field add their own `done(verdict)` predicate over the same opaque verdict `Output` (they share the `JudgedRepetition` vocabulary — `done` + `max`); [`panel()`](#adversarial-verification-panel) composes N judges into one verdict the same `done` reads. A panel therefore slots into any of them with zero per-site code.
220
228
 
@@ -230,6 +238,14 @@ Every constructor accepts the shared introspectable facet and policy knobs:
230
238
  | `onCap` | fanout/iterate `"halt"` · assess `"advance"` | What happens at the effective cap (`min(max, run.maxIterations)`). `"halt"` — terminal failure (mirrors the backward-jump guard). `"advance"` — soft-stop: warn, land a `{type:"loop-cap"}` telemetry row, fire `onLoopCap`, keep the projected result, advance downstream. |
231
239
  | `result` | fanout `"entry"` · iterate/assess `"last"` | What the loop leaves in `{state.output, state.primaryArtifact}` (the pair is governed as one). `"entry"` restores the pair captured at loop entry (reproduces routing-sees-upstream); `"last"` uses the last completed produce unit's pair (zero produce units degrades to entry). |
232
240
 
241
+ `fanout()` adds three knobs the sequential kinds have no use for:
242
+
243
+ | Knob (fanout only) | Default | Meaning |
244
+ |---|---|---|
245
+ | `concurrency` | host cap | Per-fanout in-flight ceiling, applied as `min(concurrency, host maxConcurrency)`. `1` **serializes** the loop — the safe model for units mutating shared state (e.g. applying a plan to one working tree). Integer ≥ 1, validated at construction and load. |
246
+ | `failFast` | absent (collect-all) | Opt out of collect-all: the first failing unit halts the run terminally and cancels in-flight siblings. Cancelled siblings leave unfilled slots, so a later resume re-dispatches them. |
247
+ | `depArtifactFlag` | none | Injects each completed dependency's artifact path into the dependent unit's prompt as `<flag> <path>`, one per direct `deps` entry whose slot holds a non-failed output. Pairs with `Unit.deps` — `deps` orders the waves, this hands the dependent something to read. Failed dep slots are skipped. |
248
+
233
249
  #### The resume contract (all loop kinds)
234
250
 
235
251
  A unit source must be **deterministic w.r.t. the fold-replayed `RunState` at the unit boundary plus this generation's accumulated outputs**. On resume, the fold re-calls your `units()` / `next()` at every folded boundary and compares each recomputed unit against what the run recorded. If they diverge — a non-deterministic generator recomputed a different unit — resume **refuses** with a terminal failure rather than re-run the wrong units. Set a stable `id` on each unit so the join survives a reworded `label`. The same contract covers the model-judged predicates: `assess`'s and `verify`'s `done` / `feedForward` are recomputed on resume (never persisted), so each must be deterministic w.r.t. the verdict `Output`. Runs recorded before this redesign carry no `parent` field on their unit rows and cannot be resumed (`stage-gone` refusal — no migration).
@@ -241,7 +257,7 @@ Loops are observed through unit-generic lifecycle hooks (register via `registerL
241
257
  | Hook | Payload | When |
242
258
  |---|---|---|
243
259
  | `onLoopStart(stage, info)` | `{ kind, units? }` — `units` only for fanout (push precomputes them) | after `onStageStart`, before unit 1's session |
244
- | `onUnitStart(stage, unit)` | `UnitEvent` `{ role, index, unitId?, label, skill }` | before each unit's session opens — fired for **produce AND judge** units; the seam a model-override listener flips the model on (units run strictly sequentially, so the flip is race-free) |
260
+ | `onUnitStart(stage, unit)` | `UnitEvent` `{ role, index, unitId?, label, skill }` | before each unit's session opens — fired for **produce AND judge** units; the seam a model-override listener resolves the model on. `iterate`/`assess`/`verify` units run strictly sequentially; **fanout units run in bounded parallel**, so a fanout listener must resolve per-unit from the `UnitEvent` payload rather than flipping global state |
245
261
  | `onUnitEnd(stage, unit, output)` | `UnitEvent` + the unit's validated `Output` | after the unit's JSONL row lands (loop units never fire `onStageEnd`) |
246
262
  | `onLoopCap(stage, info)` | `LoopCapInfo` `{ kind, count, max, policy }` | after an `onCap: "advance"` trip (after the `{type:"loop-cap"}` row append attempt) |
247
263
 
@@ -482,6 +498,10 @@ const notifySlack = terminal.script({
482
498
  - `produces.script` may declare `outputSchema`, `maxRetries`, `onInvalid`.
483
499
  - `acts.script` / `terminal.script` may declare `inputSchema`.
484
500
 
501
+ **Lifecycle parity.** 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`. A thrown `run()` body records a terminal failure attributed to the stage (`FAIL_SCRIPT_THREW`); the run halts and `onStageError` fires.
502
+
503
+ The runner stamps `meta` (`stage`, `stageNumber`, `ts`, `runId`) on a `produces.script` envelope — authors fill only `kind` + `artifacts` + `data`. For `acts.script` it synthesises `{ kind: "side-effect", artifacts: [], data: {} }` for the audit row and preserves the rolling primary artifact, so a downstream stage still inherits whatever the upstream `produces` stage set.
504
+
485
505
  ### Prompt stages (raw-text dispatch)
486
506
 
487
507
  A stage has three **dispatch** options — orthogonal to its `kind`:
@@ -566,7 +586,7 @@ edges: { research: "implement" }
566
586
  edges: { commit: "stop" }
567
587
 
568
588
  // 3. A predicate function (via gate or defineRoute)
569
- edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }) }
589
+ edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) }, "commit") }
570
590
  ```
571
591
 
572
592
  **`STOP`** (or `"stop"`) is the terminal edge sentinel. Every workflow path should eventually reach `"stop"`.
@@ -576,12 +596,12 @@ edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) })
576
596
  A conditional edge is an **`EdgeFn`**: a `(ctx) => string` predicate carrying a `.targets` array of every stage it can return. `.targets` is required — the validator and reachability BFS enumerate it — so you wrap a TS predicate rather than dropping a bare arrow into `edges`. Two wrappers:
577
597
 
578
598
  - **`defineRoute(targets, fn)`** — general. Arbitrary TS body, explicit `targets`. Use for strings, enums, multiple fields, ranges — anything.
579
- - **`gate(field, branches)`** — terse convenience for one **numeric** field with threshold predicates; derives `.targets` from the branch keys. Not more powerful than `defineRoute`, just shorter for the numeric case.
599
+ - **`gate(field, branches, otherwise)`** — terse convenience for one **numeric** field with threshold predicates; derives `.targets` from the branch keys plus `otherwise`. Not more powerful than `defineRoute`, just shorter for the numeric case.
580
600
  - **`match(field, branches, opts?)`** — the string/boolean companion to `gate`: classify on a discrete (enum) field by strict `===`. Derives `.targets` from the branch keys; shorter than `defineRoute` for the enum case.
581
601
 
582
602
  ### gate (numeric field)
583
603
 
584
- Branches evaluated against `Number(output.data[field])` in declaration order; first match wins, last branch is the fallback. Helpers (`gt`/`gte`/`lt`/`lte`/`eq`) take a `number` — non-numeric fields route with `defineRoute` instead.
604
+ Branches evaluated against `Number(output.data[field])` in declaration order; first match wins. The third argument, `otherwise`, is **required** — the no-match fallback must be deliberate, and omitting it throws at construction. Helpers (`gt`/`gte`/`lt`/`lte`/`eq`) take a `number` — non-numeric fields route with `defineRoute` instead.
585
605
 
586
606
  ```typescript
587
607
  import { gate, gt, eq } from "@juicesharp/rpiv-workflow";
@@ -589,11 +609,13 @@ import { gate, gt, eq } from "@juicesharp/rpiv-workflow";
589
609
  edges: {
590
610
  "code-review": gate("blockers_count", {
591
611
  revise: gt(0), // > 0 → "revise"
592
- commit: eq(0), // = 0 → "commit"; missing/NaN/< 0 falls to last
593
- })
612
+ commit: eq(0), // = 0 → "commit"
613
+ }, "commit") // missing/NaN/< 0 → "commit", with a routing-audit note
594
614
  }
595
615
  ```
596
616
 
617
+ **No-match is explicit, never silent.** A value no branch matches routes to `otherwise` and lands a `note` on the routing-audit row naming the field, the value, and the fallback taken. Branch keys must not be integer-like (`"2"`) — JS object literals hoist array-index keys ahead of declaration order, which would silently reorder match priority, so those are rejected at construction.
618
+
597
619
  ### match (enum field)
598
620
 
599
621
  `match(field, branches, opts?)` maps each target stage to the **discrete value** that routes to it. The field is compared by strict `===` in declaration order; first match wins. Where `gate` keys on a `Number(...)` threshold, `match` keys on a string/number/boolean equal — the enum classifier `gate` can't express.
@@ -858,6 +880,38 @@ When `reads:` is set the runner replaces the default prompt with a labelled-flag
858
880
 
859
881
  Multi-artifact stages get flag repetition: an upstream with two `fs` artifacts expands to `--plans <a> --plans <b>` so skill arg-parsers collect repeated flags into arrays the same way `argparse`/`clap`/shell utilities do.
860
882
 
883
+ ### Fan-in: reading every entry (`fanin` — fanout-and-synthesize)
884
+
885
+ A bare-string read resolves to the channel's **latest** entry (`array.at(-1)`). That is the wrong default for the fan-in half of *fanout-and-synthesize*: a `fanout` produces N per-unit `Output`s on one channel, and the synthesize stage's whole job is to **merge all N into one**. Latest-wins would hand it only the last unit.
886
+
887
+ Wrap a name in `fanin(name)` to read **every accumulated entry** of the channel, in run order:
888
+
889
+ ```typescript
890
+ import { acts, fanin, fanout, produces } from "@juicesharp/rpiv-workflow";
891
+
892
+ // fan-out: one collecting unit per plan phase → each appends to state.named["drafts"]
893
+ draft: produces({
894
+ outcome: draftOutcome, // outcome.name === "drafts"
895
+ loop: fanout({ source: "plans", unit: { by: "frontmatter-array", pattern: "phases" } }),
896
+ }),
897
+
898
+ // fan-in (the barrier): read ALL drafts, synthesize one result
899
+ synthesize: produces({
900
+ outcome: summaryOutcome,
901
+ reads: [fanin("drafts")], // every unit's artifacts, not just the last
902
+ }),
903
+ ```
904
+
905
+ The synthesize prompt flag-repeats across the whole channel (× each entry's artifacts):
906
+
907
+ ```
908
+ /skill:synthesize --drafts <unit1> --drafts <unit2> --drafts <unit3> …
909
+ ```
910
+
911
+ `fanin()` is the consumer-side mirror of `fanout()` — fan-out on the producer, fan-in on the consumer. It composes with non-fanout channels too (e.g. reading every `iterate` accumulation), and one `reads:` list may mix forms: `reads: [fanin("drafts"), "spec"]` reads all drafts but only the latest spec. The `reads:` element type is `string | { name; all? }`; `fanin(name)` builds `{ name, all: true }`.
912
+
913
+ A lint backs the idiom: a **bare-string** read of a channel that a `fanout` fills emits the `reads-latest-from-fanout` warning ("wrap it in `fanin(...)`"). It only warns — latest-only is legal — and `fanin()` reads are already opted in, so they're never flagged. `/wf` preview marks a fan-in consumer with `⇉ <names>`, mirroring the `panel(N, fold)` fan-in surfacing.
914
+
861
915
  ### The named-publish registry — `state.named`
862
916
 
863
917
  Every `produces` stage APPENDS its full `Output` envelope onto `state.named[key]` after each successful run. The key is computed once at write time:
@@ -871,7 +925,7 @@ Two layers, no override knob:
871
925
  - **Outcome carries a name.** Multiple stages wiring the same outcome converge — both stages append onto the same slot, latest-wins on read. This is how a workflow expresses "two stages both produce the canonical plan" without restating the name on each stage.
872
926
  - **Outcome has no name.** Stages publish under their record key. Downstream `reads: ["blueprint", "code-review"]` references stage record keys directly.
873
927
 
874
- Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)`. Side-effect stages don't write to the registry. The slot is never cleared by `terminal()` either: it's an additive channel orthogonal to the rolling primary.
928
+ Slots are **arrays** — iteration history is preserved across backward-jump loops; the default read resolves to `array.at(-1)` (latest-wins), while a `fanin(name)` read consumes the whole slot (see [Fan-in](#fan-in-reading-every-entry-fanin--fanout-and-synthesize)). Side-effect stages don't write to the registry. The slot is never cleared by `terminal()` either: it's an additive channel orthogonal to the rolling primary.
875
929
 
876
930
  ### Validation + preflight
877
931
 
@@ -892,7 +946,7 @@ A fresh-session stage starts a clean Pi conversation. It only sees (1) the rolli
892
946
  | 2 | `workspaceDiffCollector` outcome on the upstream stage | Every file the stage touched, as `fs` artifacts | Free when the work IS files on disk. Captures *what*, not *why*. |
893
947
  | 3 | `transcriptPathCollector` outcome on the upstream stage | The last regex-matched chunk of assistant text, written to disk | Captures narrative knowledge. Needs the skill to emit a recognizable marker. |
894
948
  | 4 | Custom collector / parser (+ optional `outputSchema`) | Author-defined typed shape | Most precise; most authoring effort. Enables gate routing. |
895
- | 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name, woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. See [Multi-input stages](#multi-input-stages). |
949
+ | 5 | `reads:` on the downstream stage referencing named-publish slots | Latest `Output` per declared name (or **all** entries via `fanin(name)`), woven into a labelled-flag prompt | Reaches further back than the rolling primary; survives intermediate produces stages overwriting the chain. `fanin()` is the fanout-and-synthesize barrier. See [Multi-input stages](#multi-input-stages). |
896
950
 
897
951
  **Picking between them — where does the knowledge live after the stage finishes?**
898
952
 
@@ -919,7 +973,7 @@ acts({
919
973
 
920
974
  The fresh downstream session now receives the touched files *and* a notes file capturing the rationale.
921
975
 
922
- **What `acts` without an outcome actually does.** The rolling primary slot from the last upstream `produces` is passed through unchanged — downstream still receives that prior artifact, it just learns nothing about what this stage did. If no `produces` stage has run yet upstream, `ensureUpstreamArtifact` halts the next non-terminal stage with `MSG_MISSING_ARTIFACT`. Use `terminal()` for stages that should explicitly carry nothing forward.
976
+ **What `acts` without an outcome actually does.** The rolling primary slot from the last upstream `produces` is passed through unchanged — downstream still receives that prior artifact, it just learns nothing about what this stage did. If no `produces` stage has run yet upstream, `ensureUpstreamArtifact` halts the next non-terminal stage with `FAIL_MISSING_ARTIFACT`. Use `terminal()` for stages that should explicitly carry nothing forward.
923
977
 
924
978
  ## Validators
925
979
 
@@ -929,7 +983,7 @@ The fresh downstream session now receives the touched files *and* a notes file c
929
983
 
930
984
  ```typescript
931
985
  import { typeboxSchema } from "@juicesharp/rpiv-workflow";
932
- import { Type } from "@sinclair/typebox";
986
+ import { Type } from "typebox";
933
987
 
934
988
  outputSchema: typeboxSchema(Type.Object({
935
989
  blockers_count: Type.Integer({ minimum: 0 }),
@@ -949,7 +1003,7 @@ import {
949
1003
  directoryPathCollector, jsonBodyParser, transcriptPathCollector,
950
1004
  toolCallCollector, fs,
951
1005
  } from "@juicesharp/rpiv-workflow";
952
- import { Type } from "@sinclair/typebox";
1006
+ import { Type } from "typebox";
953
1007
 
954
1008
  // Custom outcome: detect a markdown file the agent writes to a plans directory
955
1009
  const planOutcome = {
@@ -993,7 +1047,7 @@ export default defineWorkflow({
993
1047
  "code-review": gate("blockers_count", {
994
1048
  revise: gt(0),
995
1049
  commit: eq(0),
996
- }),
1050
+ }, "commit"),
997
1051
  revise: "implement-after-revise",
998
1052
  "implement-after-revise": "commit",
999
1053
  commit: "stop",