@juicesharp/rpiv-workflow 1.19.1 → 2.0.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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
package/api.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Public authoring surface for rpiv workflows. Canonical entry point — users
3
- * import everything they need (`defineWorkflow`, `produces`, `acts`,
2
+ * Public authoring surface for rpiv workflows — a BARREL.
3
+ * Users import everything they need (`defineWorkflow`, `produces`, `acts`,
4
4
  * `defineRoute`, `gate`, `STOP`, `marksReadsData`, schema adapters, plus the
5
5
  * type vocabulary `Workflow` / `StageDef` / `EdgeFn` / `EdgeTarget` /
6
6
  * `EdgeContext`) from `@juicesharp/rpiv-workflow`.
@@ -10,704 +10,19 @@
10
10
  * `STOP`, or an `EdgeFn` that picks at runtime. Edges live INSIDE each
11
11
  * workflow.
12
12
  *
13
- * Factories are pure passthroughs that apply sane defaults. Same idiom as
14
- * `defineConfig` in Vite/Astro/Tailwind: zero runtime cost, exists solely
15
- * for type inference + uniform shape at the call site.
16
- */
17
-
18
- import type { StandardSchemaV1 } from "@standard-schema/spec";
19
- import type { Output, OutputSpec } from "./output.js";
20
- import type { Predicate } from "./predicates.js";
21
- import type { RunState } from "./types.js";
22
-
23
- export type { OutputSpec } from "./output.js";
24
-
25
- /**
26
- * Schema attached to a stage's `outputSchema` / `inputSchema`. Structurally
27
- * a Standard Schema v1 (the converged interface implemented by Zod, Valibot,
28
- * ArkType, TypeBox, et al.) — re-exported under a name that doesn't leak the
29
- * spec version into our public surface. When the spec versions, this alias
30
- * picks the right one in a single line.
31
- *
32
- * Sync schemas are the default and the recommended shape for the 95% case
33
- * (pure shape contracts: `Type.Object({ … })`, `z.object({ … })`). Async
34
- * schemas are supported at both seams — the runner awaits `~standard.validate`
35
- * — and are the right answer when correctness needs I/O (filesystem probes,
36
- * registry lookups, async-by-default libs like ArkType). A hanging async
37
- * schema is bounded by the stage's `validateTimeoutMs`. See the
38
- * "Validators: sync vs async" section of the package README for the full
39
- * rationale.
40
- */
41
- export type StageSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output>;
42
-
43
- // ===========================================================================
44
- // Stage-shape primitives
45
- // ===========================================================================
46
-
47
- /**
48
- * - `"produces"` — protocol skills that write `.rpiv/artifacts/<bucket>/<file>.md`.
49
- * The runner halts the chain if the path doesn't appear in the transcript.
50
- * - `"side-effect"` — action skills (commit, implement) where the side effect IS
51
- * the work; the chain inherits the prior `currentPrimaryArtifact(state)`.
52
- *
53
- * The `as const` array is the single source of truth: the literal-union type
54
- * is derived via `(typeof ARRAY)[number]`, and `validate-workflow.ts` consumes
55
- * the same array for the runtime enum check. Adding a variant updates both
56
- * type-level and runtime arms in one edit.
57
- */
58
- export const STAGE_KINDS = ["produces", "side-effect"] as const;
59
- export type StageKind = (typeof STAGE_KINDS)[number];
60
-
61
- /**
62
- * - `"fresh"` — wraps the stage in `ctx.newSession({ withSession })`.
63
- * - `"continue"` — reuses the prior session via `host.sendUserMessage()` +
64
- * `ctx.waitForIdle()`; branch sliced by `branchOffset`.
65
- */
66
- export const SESSION_POLICIES = ["fresh", "continue"] as const;
67
- export type SessionPolicy = (typeof SESSION_POLICIES)[number];
68
-
69
- /**
70
- * What happens when a stage's `outputSchema` rejects the extracted output:
71
- * - `"retry"` — re-invoke the stage up to `maxRetries`, threading the
72
- * schema's issues back to the agent via a retry prompt.
73
- * - `"halt"` — record a terminal failure on the first rejection.
74
- */
75
- export const ON_INVALID_VALUES = ["retry", "halt"] as const;
76
- export type OnInvalid = (typeof ON_INVALID_VALUES)[number];
77
-
78
- /**
79
- * Opt-in fanout — a user-supplied function that decomposes a stage's work
80
- * into N units, one Pi session per unit. The runner owns iteration +
81
- * audit; the FanoutFn owns the convention (how units are detected, what
82
- * each session's prompt body says, how each is labelled).
83
- *
84
- * rpiv-workflow ships ZERO fanout conventions: no markdown regex, no
85
- * phase counter, no schema. A consumer wanting markdown-heading fanout
86
- * writes the ~10 lines themselves and reuses one constant across stages.
87
- *
88
- * Invariants enforced by the runner:
89
- * - Empty return ⇒ no fanout (fall through to the single-stage path).
90
- * - Throws ⇒ stage halts, attributed to this stage.
91
- * - `stage.sessionPolicy === "continue"` is incompatible with fanout
92
- * (validated at load + at preflight).
93
- *
94
- * Cap policy: the runner does not bound `units.length`. Authors of bespoke
95
- * FanoutFns own their own safety bounds — same posture as
96
- * `maxBackwardJumps` (the only run-wide cap the runner enforces).
97
- */
98
- export type FanoutFn = (ctx: FanoutContext) => readonly FanoutUnit[] | Promise<readonly FanoutUnit[]>;
99
-
100
- export interface FanoutContext {
101
- cwd: string;
102
- /**
103
- * Primary artifact inherited from the upstream stage (or undefined when
104
- * the fanout stage is the entry point). FanoutFns that need to read an
105
- * upstream artifact short-circuit to `[]` when undefined — the runner
106
- * treats that as "no fanout" and runs the single-stage path. The
107
- * handle's serialized form (path / URL / opaque id) is what most
108
- * FanoutFns weave into their per-unit prompt body.
109
- */
110
- artifact: import("./handle.js").Artifact | undefined;
111
- state: Readonly<RunState>;
112
- }
113
-
114
- export interface FanoutUnit {
115
- /**
116
- * Body sent to the skill: the runner dispatches `/skill:<stage.skill>
117
- * <prompt>` once per unit. The unit owns artifact-path threading + any
118
- * per-unit cue — the runner adds nothing implicit.
119
- */
120
- prompt: string;
121
- /**
122
- * Short label woven into the status line + JSONL audit row.
123
- * The audit `skill` field becomes `<stage.skill> (<id ?? label>)`;
124
- * the status line shows `rpiv: stage X/Y — <stage.skill> (<label>)`.
125
- * Keep it short and disambiguating (`"phase 2/5"`, `"task 3/8"`).
126
- */
127
- label: string;
128
- /**
129
- * Optional stable identifier used in the JSONL audit row in place of
130
- * `label`. Set this when `label` is a human-facing display string that
131
- * may be reworded — `id` keeps the audit projection stable across
132
- * label edits and matches the pattern post-hoc tooling joins on
133
- * (`"phase-2"`, `"task-3"`). Omit to fall back to `label`.
134
- */
135
- id?: string;
136
- }
137
-
138
- /**
139
- * Opt-in iteration — the sequential, accumulating counterpart to `FanoutFn`.
140
- * Where `fanout` computes all units up front and runs them blind to one
141
- * another, `iterate` is invoked once per unit (pull model), each call
142
- * receiving the validated `Output`s of every prior unit in this stage. Return
143
- * the next unit, or `null`/`undefined` to terminate the stage.
144
- *
145
- * Each unit runs the stage's `outcome` collector like a one-shot `produces`
146
- * stage: it validates against `outputSchema`, appends its `Output` to
147
- * `state.named[outcome.name]`, and rolls the primary artifact forward.
148
- *
149
- * Invariants enforced by the runner:
150
- * - First call returns null ⇒ stage completes as a zero-unit no-op (advances).
151
- * - Throws ⇒ stage halts, attributed to this stage.
152
- * - `accumulated.length` reaching the run-wide `maxIterations` cap ⇒ stage
153
- * halts with a terminal failure (the backstop for a generator that never
154
- * returns null).
155
- * - Requires `kind: "produces"` + an `outcome` with a `name`; incompatible
156
- * with `sessionPolicy: "continue"` and with `fanout`/`run` (validated at
157
- * load + at preflight).
158
- */
159
- export type IterateFn = (ctx: IterateContext) => IterateUnit | null | Promise<IterateUnit | null>;
160
-
161
- export interface IterateContext {
162
- cwd: string;
163
- /**
164
- * Stage-entry primary artifact, FROZEN across every unit. Does not roll
165
- * forward to the prior unit's output — use `accumulated` (or `state.named`)
166
- * for that. Undefined when the iterate stage is the entry point.
167
- *
168
- * On a corrective back-edge re-entry the rolling primary may be a
169
- * downstream doc; generators that must re-read their true source should
170
- * read it from `state.named` rather than relying on this slot.
171
- */
172
- artifact: import("./handle.js").Artifact | undefined;
173
- state: Readonly<RunState>;
174
- /** Validated Outputs of this stage's already-completed units, in order. */
175
- accumulated: readonly import("./output.js").Output[];
176
- /** 0-based index of the unit about to run (== accumulated.length). */
177
- index: number;
178
- }
179
-
180
- /** Same shape as `FanoutUnit` (prompt + label + optional stable id). */
181
- export type IterateUnit = FanoutUnit;
182
-
183
- // ===========================================================================
184
- // Script-stage primitives — skillless TS functions in place of `/skill:<x>`
185
- // ===========================================================================
186
-
187
- /**
188
- * Context handed to a script stage's `run` function. Shape mirrors
189
- * `EdgeContext` / `FanoutContext`: frozen identity (`cwd`) + the chain
190
- * data the function needs (`input` — upstream Output envelope) + a
191
- * read-only state snapshot.
192
- *
193
- * Script stages cannot fanout, cannot use `sessionPolicy: "continue"`,
194
- * and do not receive a Pi `WorkflowHostContext` — they're pure TS calls.
195
- */
196
- export interface ScriptContext {
197
- cwd: string;
198
- /**
199
- * Inherited upstream `Output` envelope. `undefined` when the script
200
- * stage is the entry point, or when the upstream stage cleared the
201
- * rolling primary slot (a `terminal()` ahead of it).
202
- */
203
- input: Output | undefined;
204
- state: Readonly<RunState>;
205
- }
206
-
207
- /**
208
- * Script `produces` stage body — returns the `Output` envelope's
209
- * value-channel fields (`kind` + `artifacts` + `data`) directly. The
210
- * runner stamps `meta` (stage, stageNumber, ts, runId) — same posture
211
- * as how `ArtifactParser`s return `{ kind, data }` and `finalizeOutput`
212
- * fills the meta in.
213
- */
214
- export type ProducesScriptFn<K extends string = string, D = unknown> = (
215
- ctx: ScriptContext,
216
- ) => Omit<Output<K, D>, "meta"> | Promise<Omit<Output<K, D>, "meta">>;
217
-
218
- /**
219
- * Script `acts` / `terminal` stage body — returns nothing. The runner
220
- * builds a `SideEffectOutput`-shaped envelope (kind `"side-effect"`,
221
- * empty `data`) so audit + downstream chain wiring still uniform.
222
- */
223
- export type ActsScriptFn = (ctx: ScriptContext) => void | Promise<void>;
224
-
225
- /**
226
- * Raw-prompt dispatch body — the third dispatch alongside `skill`
227
- * (`/skill:<name> <args>`) and script `run` (pure TS, no model). Returns the
228
- * COMPLETE user message sent into the stage's session: no `/skill:` prefix and
229
- * no implicit upstream-artifact arg appended. The dynamic form receives the
230
- * same `ScriptContext` script stages get, so a prompt can weave in the upstream
231
- * `Output` (`ctx.input`) or the named registry (`ctx.state.named`):
232
- *
233
- * acts({ prompt: "Implement the design spec discussed above.", sessionPolicy: "continue" })
234
- * produces({ prompt: ({ input }) =>
235
- * `Summarise ${handleToString(input!.artifacts[0]!.handle)} in 3 bullets.`, outcome })
236
- *
237
- * A plain `string` is sugar for `() => string`. Unlike a skill stage, a prompt
238
- * stage skips the skill-registry preflight (there is no skill to register).
239
- * Mutually exclusive with `skill` (explicit), `run`, `reads`, and — in v1 —
240
- * `fanout`/`iterate`. Composes with `kind` (a `produces` prompt stage runs the
241
- * `outcome` collector and publishes; a `side-effect` prompt stage just talks)
242
- * and `sessionPolicy` (`continue` = a follow-up turn on a session a prior stage
243
- * populated). (validated at load + preflight.)
244
- */
245
- export type PromptFn = (ctx: ScriptContext) => string | Promise<string>;
246
-
247
- // ===========================================================================
248
- // Types
249
- // ===========================================================================
250
-
251
- /**
252
- * Runtime context handed to an `EdgeFn`. The sole context shape for both
253
- * data-reading and state-only routes (the single `defineRoute` path covers
254
- * both via `opts.readsData`).
255
- */
256
- export interface EdgeContext {
257
- output: import("./output.js").Output | undefined;
258
- state: Readonly<RunState>;
259
- }
260
-
261
- /**
262
- * Body-type alias for hand-rolled route picks. Internal — users wrap via
263
- * `defineRoute`, which returns an `EdgeFn` (this alias plus a `.targets`
264
- * field).
265
- */
266
- type EdgePredicate = (ctx: EdgeContext) => string;
267
-
268
- /**
269
- * A function that picks the next stage name given current state + output.
270
- * Optional `targets` field lets graph introspectors enumerate possible
271
- * returns — `gate` and other built-in route builders populate it.
272
- */
273
- export type EdgeFn = EdgePredicate & { targets?: readonly string[] };
274
-
275
- /**
276
- * Terminal edge sentinel. Single source of truth for the `"stop"` literal
277
- * embedded in `EdgeTarget`; `validate-workflow.ts` + `routing.ts` import this rather
278
- * than re-declaring the string.
279
- */
280
- export const STOP = "stop" as const;
281
-
282
- /**
283
- * What an `edges` entry resolves to: another stage name (auto-edge), the
284
- * terminal sentinel `STOP`, or a function chosen at run-time.
285
- */
286
- export type EdgeTarget = string | typeof STOP | EdgeFn;
287
-
288
- /**
289
- * A stage in the workflow graph. The stage's identity is the surrounding
290
- * `Workflow.stages` record key. `skill` is the Pi skill body to invoke —
291
- * defaulted to the record key by the runner when omitted, so the
292
- * authoring-time call site usually doesn't restate the name. Set `skill`
293
- * explicitly only when the stage id and the Pi skill differ (aliased
294
- * stages like `implement-after-revise` invoking the `implement` skill).
295
- *
296
- * Pi resolves the skill at run time; there's no allowlist gate. If Pi
297
- * can't load the skill, the runner halts with a clear error pointing
298
- * at this stage.
299
- */
300
- export interface StageDef<TIn = unknown, TOut = unknown> {
301
- skill?: string;
302
- kind: StageKind;
303
- sessionPolicy: SessionPolicy;
304
- outcome?: OutputSpec;
305
- /**
306
- * Standard Schema v1 validator run against `output.data` after the
307
- * stage's `OutputSpec` produces it (the typed record parsed out of the
308
- * agent's emitted artifact). On rejection the runner honours
309
- * `onInvalid` ("retry" by default, up to `maxRetries`; "halt" to fail
310
- * fast).
311
- */
312
- outputSchema?: StageSchema<unknown, TOut>;
313
- /**
314
- * Standard Schema v1 validator run against the inherited upstream
315
- * `output.data` before the stage runs. A rejection halts the
316
- * chain immediately (no retry path — the upstream stage is already
317
- * frozen).
318
- */
319
- inputSchema?: StageSchema<unknown, TIn>;
320
- onInvalid?: OnInvalid;
321
- maxRetries?: number;
322
- validateTimeoutMs?: number;
323
- /**
324
- * Opt-in fanout. When set, the runner invokes the function with a
325
- * `FanoutContext`, awaits the returned units, and runs one Pi session
326
- * per unit (single-stage path when the array is empty). Incompatible
327
- * with `sessionPolicy: "continue"` — fanout requires per-unit session
328
- * isolation.
329
- */
330
- fanout?: FanoutFn;
331
- /**
332
- * Opt-in sequential accumulation — the dual of `fanout`. When set, the
333
- * runner pulls units one at a time, feeding each generator call the prior
334
- * units' `Output`s; every unit runs the stage's `outcome` like a one-shot
335
- * `produces` stage and accumulates into `state.named[outcome.name]`.
336
- *
337
- * Mutually exclusive with `fanout` and `run`. Requires `kind: "produces"`,
338
- * an `outcome` with a `name`, and `sessionPolicy` other than `"continue"`.
339
- * (validated at load + at preflight.)
340
- */
341
- iterate?: IterateFn;
342
- /**
343
- * Whether the stage inherits the chain's primary artifact from
344
- * upstream `produces` stages. Default `true`. Set to `false` on a
345
- * terminal side-effect — the stage's prompt receives `originalInput`
346
- * instead of the upstream artifact handle, the `ensureUpstreamArtifact`
347
- * preflight is bypassed, and the rolling primary slot is cleared on
348
- * success so any stage following also starts without an inherited
349
- * artifact.
350
- *
351
- * Authored via the `terminal()` factory; the flag is the underlying
352
- * mechanism. Meaningless on `kind: "produces"` stages (they emit their
353
- * own outcome) — `validateWorkflow` warns when set there.
354
- */
355
- inheritsArtifacts?: boolean;
356
- /**
357
- * Skillless script stage: when present, the runner calls this
358
- * function instead of dispatching `/skill:<skill>`. Presence of
359
- * `run` is the skill-vs-script discriminator. Authored via
360
- * `produces.script(...)`, `acts.script(...)`, or
361
- * `terminal.script(...)`.
362
- *
363
- * Stages with `run` set CANNOT also set `skill`, `outcome`,
364
- * `fanout`, or `sessionPolicy: "continue"` — rejected at load time
365
- * by `validateWorkflow`.
366
- */
367
- run?: ProducesScriptFn<string, TOut> | ActsScriptFn;
368
- /**
369
- * Raw-prompt dispatch: when set, the runner sends this text (resolved per
370
- * the `PromptFn`, or the literal string) into the stage's session instead
371
- * of `/skill:<skill>`. The stage runs the model with no skill body and no
372
- * skill-registry check. Presence of `prompt` is the third dispatch
373
- * discriminator alongside `run`.
374
- *
375
- * Mutually exclusive with `skill` (explicit), `run`, `reads`, and — in v1 —
376
- * `fanout`/`iterate`. Composes with `kind` and `sessionPolicy`. (validated
377
- * at load + preflight.)
378
- */
379
- prompt?: string | PromptFn;
380
- /**
381
- * Names this stage consumes from `state.named` to build its prompt.
382
- * When set, the runner replaces the default single-artifact prompt
383
- * (`/skill:<name> <handle>`) with a labelled-flag form
384
- * (`/skill:<name> --<n1> <h1> --<n2> <h2> …`), reading the most recent
385
- * `Output` each name has accumulated and iterating its `artifacts` list.
386
- * Empty (or unset) → default prompt behaviour preserved.
387
- *
388
- * Names address `state.named` slots, which are keyed by
389
- * `stage.outcome?.name ?? stage.<record-key>`. Every name in `reads:`
390
- * must be filled by some upstream stage's produces success (validated
391
- * at load time by `validateWorkflow`; the `ensureNamedReads` preflight
392
- * catches the "haven't reached the producer yet" case at runtime).
393
- */
394
- reads?: ReadonlyArray<string>;
395
- }
396
-
397
- /**
398
- * A complete workflow. `name` is what users type as `/wf <name>`; `start`
399
- * is the entry stage; `stages` is the lexicon; `edges` is the wiring. Every
400
- * key in `edges` must exist in `stages`; every string value must exist in
401
- * `stages` or be `"stop"`. Validated at load time by `validate-workflow.ts`.
402
- */
403
- export interface Workflow {
404
- name: string;
405
- description?: string;
406
- start: string;
407
- stages: Record<string, StageDef>;
408
- edges: Record<string, EdgeTarget>;
409
- }
410
-
411
- // ===========================================================================
412
- // Factories — passthroughs with defaults
413
- // ===========================================================================
414
-
415
- /** Identity passthrough; reserved for future normalization / metadata hooks. */
416
- export function defineWorkflow(spec: Workflow): Workflow {
417
- return spec;
418
- }
419
-
420
- /**
421
- * Options accepted by `produces.script({ run, ... })`. Subset of the
422
- * skill-stage `StageDef` knobs that semantically apply to a pure TS
423
- * function: validation (`inputSchema` / `outputSchema` + retry knobs)
424
- * and artifact-inheritance opt-out. `kind` and `sessionPolicy` are not
425
- * configurable — script stages are always `"produces"` + `"fresh"`.
426
- * `skill`, `outcome`, and `fanout` are unauthorisable here.
427
- */
428
- interface ProducesScriptOptions<TIn = unknown, TOut = unknown> {
429
- run: ProducesScriptFn<string, TOut>;
430
- outputSchema?: StageSchema<unknown, TOut>;
431
- inputSchema?: StageSchema<unknown, TIn>;
432
- onInvalid?: OnInvalid;
433
- maxRetries?: number;
434
- validateTimeoutMs?: number;
435
- inheritsArtifacts?: boolean;
436
- reads?: ReadonlyArray<string>;
437
- }
438
-
439
- /**
440
- * Options accepted by `acts.script({ run, ... })` and
441
- * `terminal.script({ run, ... })`. Validation surface is narrower than
442
- * the produces variant: side-effect stages have no `outputSchema`
443
- * (they emit no data envelope), so the retry knobs don't apply.
444
- */
445
- interface ActsScriptOptions<TIn = unknown> {
446
- run: ActsScriptFn;
447
- inputSchema?: StageSchema<unknown, TIn>;
448
- inheritsArtifacts?: boolean;
449
- reads?: ReadonlyArray<string>;
450
- }
451
-
452
- /**
453
- * Options accepted by `produces.prompt({ prompt, outcome, ... })` — the typed
454
- * builder for a raw-prompt `produces` stage. The dispatch-conflicting fields
455
- * (`skill`, `run`, `fanout`, `iterate`, `reads`) are STRUCTURALLY ABSENT, so an
456
- * object-literal call site that sets one fails TypeScript's excess-property
457
- * check — the load-time exclusion becomes compile-time for the idiomatic path.
458
- * `outcome` is required (a `produces` stage always needs one).
459
- */
460
- interface ProducesPromptOptions<TIn = unknown, TOut = unknown> {
461
- prompt: string | PromptFn;
462
- outcome: OutputSpec;
463
- outputSchema?: StageSchema<unknown, TOut>;
464
- inputSchema?: StageSchema<unknown, TIn>;
465
- onInvalid?: OnInvalid;
466
- maxRetries?: number;
467
- validateTimeoutMs?: number;
468
- /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
469
- sessionPolicy?: SessionPolicy;
470
- }
471
-
472
- /**
473
- * Options accepted by `acts.prompt({ prompt, ... })` — the typed builder for a
474
- * raw-prompt side-effect stage (a pure chat turn). Narrower than the produces
475
- * variant: no `outcome` (nothing collected). Dispatch-conflicting fields are
476
- * structurally absent. For a collecting side-effect prompt stage, use the bare
477
- * `acts({ prompt, outcome })` field form instead.
478
- */
479
- interface ActsPromptOptions<TIn = unknown> {
480
- prompt: string | PromptFn;
481
- inputSchema?: StageSchema<unknown, TIn>;
482
- /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
483
- sessionPolicy?: SessionPolicy;
484
- }
485
-
486
- function producesFn(overrides: Partial<StageDef> = {}): StageDef {
487
- return {
488
- kind: "produces",
489
- sessionPolicy: "fresh",
490
- ...overrides,
491
- };
492
- }
493
-
494
- function producesScript<TIn = unknown, TOut = unknown>(opts: ProducesScriptOptions<TIn, TOut>): StageDef<TIn, TOut> {
495
- return {
496
- kind: "produces",
497
- sessionPolicy: "fresh",
498
- run: opts.run as ProducesScriptFn<string, TOut>,
499
- outputSchema: opts.outputSchema,
500
- inputSchema: opts.inputSchema,
501
- onInvalid: opts.onInvalid,
502
- maxRetries: opts.maxRetries,
503
- validateTimeoutMs: opts.validateTimeoutMs,
504
- inheritsArtifacts: opts.inheritsArtifacts,
505
- reads: opts.reads,
506
- };
507
- }
508
-
509
- function producesPrompt<TIn = unknown, TOut = unknown>(opts: ProducesPromptOptions<TIn, TOut>): StageDef<TIn, TOut> {
510
- return {
511
- kind: "produces",
512
- sessionPolicy: opts.sessionPolicy ?? "fresh",
513
- prompt: opts.prompt,
514
- outcome: opts.outcome,
515
- outputSchema: opts.outputSchema,
516
- inputSchema: opts.inputSchema,
517
- onInvalid: opts.onInvalid,
518
- maxRetries: opts.maxRetries,
519
- validateTimeoutMs: opts.validateTimeoutMs,
520
- };
521
- }
522
-
523
- function actsFn(overrides: Partial<StageDef> = {}): StageDef {
524
- return {
525
- kind: "side-effect",
526
- sessionPolicy: "fresh",
527
- ...overrides,
528
- };
529
- }
530
-
531
- function actsPrompt<TIn = unknown>(opts: ActsPromptOptions<TIn>): StageDef<TIn, void> {
532
- return {
533
- kind: "side-effect",
534
- sessionPolicy: opts.sessionPolicy ?? "fresh",
535
- prompt: opts.prompt,
536
- inputSchema: opts.inputSchema,
537
- };
538
- }
539
-
540
- function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
541
- return {
542
- kind: "side-effect",
543
- sessionPolicy: "fresh",
544
- run: opts.run,
545
- inputSchema: opts.inputSchema,
546
- inheritsArtifacts: opts.inheritsArtifacts,
547
- reads: opts.reads,
548
- };
549
- }
550
-
551
- function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
552
- return actsFn({ ...overrides, inheritsArtifacts: false });
553
- }
554
-
555
- function terminalScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
556
- return actsScript({ ...opts, inheritsArtifacts: false });
557
- }
558
-
559
- /**
560
- * Artifact-producing stage: invokes a Pi skill that writes
561
- * `.rpiv/artifacts/<bucket>/<file>.md`. Defaults to fresh-session. The
562
- * skill body defaults to the surrounding `stages` record key — override
563
- * via `{ skill: "<other>" }` only when the stage id and the Pi skill
564
- * differ (e.g. a stage keyed `design-after-review` aliasing the
565
- * `design` skill so it can appear twice in the same workflow's edge graph).
566
- *
567
- * Skillless variant: `produces.script({ run, outputSchema?, ... })` runs
568
- * a pure TS function in place of a Pi skill body. The function returns
569
- * the `Output<K, D>` envelope directly.
570
- *
571
- * Raw-prompt variant: `produces.prompt({ prompt, outcome, ... })` dispatches
572
- * author-owned text (no `/skill:` prefix) and collects the reply via `outcome`.
573
- * The typed options omit the dispatch-conflicting fields so invalid combos are
574
- * un-typable on a literal call site.
575
- */
576
- export const produces = Object.assign(producesFn, { script: producesScript, prompt: producesPrompt });
577
-
578
- /**
579
- * Side-effect stage: invokes a Pi skill whose side effect IS the work
580
- * (commit, implement). No artifact-emission check. Defaults to fresh-session.
581
- * Like `produces`, the skill body defaults to the record key.
582
- *
583
- * Skillless variant: `acts.script({ run, ... })` runs a pure TS
584
- * function in place of a Pi skill body; the runner synthesises a
585
- * `SideEffectOutput` envelope so the chain stays uniform.
586
- *
587
- * Raw-prompt variant: `acts.prompt({ prompt, sessionPolicy? })` dispatches
588
- * author-owned text as a pure chat turn (no artifact collected) — the typed
589
- * builder for the continue follow-up shape.
590
- */
591
- export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsPrompt });
592
-
593
- /**
594
- * Terminal side-effect stage: an `acts`-shaped stage that does NOT inherit
595
- * the upstream primary artifact. The stage's prompt receives the run's
596
- * `originalInput` instead of an upstream artifact handle; the
597
- * `ensureUpstreamArtifact` preflight is bypassed; and the rolling primary
598
- * slot is cleared on success so anything downstream also starts without an
599
- * inherited handle.
600
- *
601
- * Sibling to `produces()` / `acts()`. The right answer when a final stage
602
- * (cleanup, summary, post-run notification) shouldn't be coupled to the
603
- * upstream chain's artifact.
604
- *
605
- * Desugars to `acts({ ...overrides, inheritsArtifacts: false })`. The
606
- * skillless variant `terminal.script({ run, ... })` desugars to
607
- * `acts.script({ ...opts, inheritsArtifacts: false })`.
608
- */
609
- export const terminal = Object.assign(terminalFn, { script: terminalScript });
610
-
611
- // ===========================================================================
612
- // Route builders — common patterns
613
- // ===========================================================================
614
-
615
- /**
616
- * Marker attached to EdgeFns that read from `output.data`.
617
- * `validate-workflow.ts:checkPredicateSchemas` warns when a stage feeds a
618
- * marked route but has no `outputSchema` — routing on un-validated data
619
- * is the I6-class defect from the bcc34bc review.
620
- *
621
- * Default is "marked": `defineRoute(targets, fn)` auto-marks. Opt out by
622
- * passing `{ readsData: false }` for the rare route that consults only
623
- * `state` or `output.meta`.
624
- *
625
- * Exported as a `Symbol.for` so it survives `import` boundaries cleanly.
626
- */
627
- export const READS_DATA: unique symbol = Symbol.for("rpiv.workflow.readsData");
628
-
629
- /**
630
- * True iff `fn` was wrapped by `defineRoute(...)` with the data-reading
631
- * marker attached (the default; opt out via `{ readsData: false }`). The
632
- * validator uses this to decide whether an `EdgeFn`'s source stage must
633
- * declare an `outputSchema` — data-reading routes need a validated output
634
- * shape; state-only routes don't.
635
- *
636
- * Centralises the double-cast required to symbol-key into a function object
637
- * so consumers don't sprinkle `as unknown as Record<symbol, …>` at every
638
- * read site.
639
- */
640
- export function marksReadsData(fn: EdgeFn): boolean {
641
- return Boolean((fn as unknown as Record<symbol, boolean>)[READS_DATA]);
642
- }
643
-
644
- /** Options for `defineRoute`. */
645
- export interface DefineRouteOptions {
646
- /**
647
- * Whether the route reads `output.data` (the default). Set to `false` for
648
- * routes that consult only `state` or `output.meta` so the load-time
649
- * outputSchema lint doesn't warn the source stage lacks an
650
- * `outputSchema` (a state-derived route has no data-shape contract to
651
- * validate).
652
- */
653
- readsData?: boolean;
654
- }
655
-
656
- /**
657
- * Promote a hand-rolled `EdgePredicate` to an `EdgeFn` by structurally
658
- * attaching the set of possible returns. `validate-workflow.ts` requires every
659
- * EdgeFn to carry `.targets` so reachability and load-time edge-target
660
- * checks see every branch; this factory is the only blessed way to author
661
- * a multi-branch route.
662
- *
663
- * Auto-marks the returned EdgeFn with `READS_DATA` so the outputSchema lint
664
- * fires when the source stage has no `outputSchema`. If the route consults
665
- * only `state` / `output.meta` and never reads `output.data`, pass
666
- * `{ readsData: false }` to suppress the lint.
667
- *
668
- * Throws if `targets` is empty — a route that can't return anything
669
- * declared is by definition a bug.
670
- */
671
- export function defineRoute(targets: readonly string[], fn: EdgePredicate, opts?: DefineRouteOptions): EdgeFn {
672
- if (targets.length === 0) {
673
- throw new Error("defineRoute: targets must declare at least one possible return value");
674
- }
675
- const wrapped = fn as EdgeFn;
676
- wrapped.targets = [...targets];
677
- if (opts?.readsData !== false) (wrapped as unknown as Record<symbol, boolean>)[READS_DATA] = true;
678
- return wrapped;
679
- }
680
-
681
- /**
682
- * Conditional routing keyed on a numeric field in `output.data`. Each
683
- * branch's predicate is evaluated against `Number(output.data[field])` in
684
- * declaration order; the first matching branch wins. If no predicate
685
- * matches, the last declared branch is the fallback — same posture as the
686
- * prior `threshold` builder, which routed missing/non-numeric fields to its
687
- * `ifBelow` branch by virtue of `NaN > anything === false`.
688
- *
689
- * ```ts
690
- * gate("blockers_count", { revise: gt(0), commit: eq(0) })
691
- * // value > 0 → "revise"
692
- * // value = 0 → "commit"
693
- * // value < 0 → "commit" (no match, falls to last)
694
- * // missing/NaN → "commit" (no match, falls to last)
695
- * ```
696
- *
697
- * Built on `defineRoute` so the `.targets` metadata is attached structurally
698
- * and the `READS_DATA` marker auto-applies (routing reads `output.data`).
699
- */
700
- export function gate(field: string, branches: Record<string, Predicate>): EdgeFn {
701
- const targets = Object.keys(branches);
702
- if (targets.length === 0) {
703
- throw new Error("gate: branches must declare at least one possible return value");
704
- }
705
- const fallback = targets[targets.length - 1]!;
706
- return defineRoute(targets, ({ output }) => {
707
- const value = Number((output?.data as Record<string, unknown> | undefined)?.[field]);
708
- for (const target of targets) {
709
- if (branches[target]!(value)) return target;
710
- }
711
- return fallback;
712
- });
713
- }
13
+ * Module map (each concept has ONE home; this file re-exports, never
14
+ * declares):
15
+ * ./stage-def.ts — StageDef union + arms, Workflow, StageSchema,
16
+ * script/prompt primitives, the produces/acts/terminal
17
+ * factories
18
+ * ./loop-def.ts — the loop vocabulary (LoopDef kinds, JudgedRepetition,
19
+ * VerifySpec, Unit, contexts, LOOP_KINDS); constructors
20
+ * stay in loop-constructors.ts
21
+ * ./routing-dsl.ts — EdgeFn/EdgeTarget/STOP, defineRoute, gate, the
22
+ * READS_DATA / ROUTE_NOTE markers
23
+ */
24
+
25
+ export * from "./loop-def.js";
26
+ export type { Outcome } from "./output-spec.js";
27
+ export * from "./routing-dsl.js";
28
+ export * from "./stage-def.js";