@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/stage-def.ts ADDED
@@ -0,0 +1,595 @@
1
+ /**
2
+ * Stage vocabulary + factories — what a stage IS (`StageDef` and its three
3
+ * dispatch arms), what a workflow is, and the blessed constructors
4
+ * (`defineWorkflow`, `produces` / `acts` / `terminal` and their `.script` /
5
+ * `.prompt` builders). Split out of api.ts; the loop shapes live in
6
+ * loop-def.ts, the routing DSL in routing-dsl.ts.
7
+ *
8
+ * Factories are pure passthroughs that apply sane defaults. Same idiom as
9
+ * `defineConfig` in Vite/Astro/Tailwind: zero runtime cost, exists solely
10
+ * for type inference + uniform shape at the call site.
11
+ */
12
+
13
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
14
+ import { requireNonEmptyString } from "./internal-utils.js";
15
+ import type { AssessLoop, LoopDef, VerifySpec } from "./loop-def.js";
16
+ import type { Output, RunView } from "./output.js";
17
+ import type { Outcome } from "./output-spec.js";
18
+ import type { EdgeTarget } from "./routing-dsl.js";
19
+
20
+ /**
21
+ * Schema attached to a stage's `outputSchema` / `inputSchema`. Structurally
22
+ * a Standard Schema v1 (the converged interface implemented by Zod, Valibot,
23
+ * ArkType, TypeBox, et al.) — re-exported under a name that doesn't leak the
24
+ * spec version into our public surface. When the spec versions, this alias
25
+ * picks the right one in a single line.
26
+ *
27
+ * Sync schemas are the default and the recommended shape for the 95% case
28
+ * (pure shape contracts: `Type.Object({ … })`, `z.object({ … })`). Async
29
+ * schemas are supported at both seams — the runner awaits `~standard.validate`
30
+ * — and are the right answer when correctness needs I/O (filesystem probes,
31
+ * registry lookups, async-by-default libs like ArkType). A hanging async
32
+ * schema is bounded by the stage's `validateTimeoutMs`. See the
33
+ * "Validators: sync vs async" section of the package README for the full
34
+ * rationale.
35
+ */
36
+ export type StageSchema<TIn = unknown, TOut = TIn> = StandardSchemaV1<TIn, TOut>;
37
+
38
+ // ===========================================================================
39
+ // Stage-shape primitives
40
+ // ===========================================================================
41
+
42
+ /**
43
+ * - `"produces"` — protocol skills that write `.rpiv/artifacts/<bucket>/<file>.md`.
44
+ * The runner halts the chain if the path doesn't appear in the transcript.
45
+ * - `"side-effect"` — action skills (commit, implement) where the side effect IS
46
+ * the work; the chain inherits the prior `currentPrimaryArtifact(state)`.
47
+ *
48
+ * Naming is DELIBERATELY split between data and authoring surface: the kind
49
+ * literal is descriptive (`"side-effect"` — what lands in rows and output
50
+ * envelopes) while its factory is a verb (`acts()` — what reads naturally in
51
+ * a stage record). `terminal()` is not a third kind: it builds
52
+ * `"side-effect"` + `inheritsArtifacts: false`. See the README glossary.
53
+ *
54
+ * The `as const` array is the single source of truth: the literal-union type
55
+ * is derived via `(typeof ARRAY)[number]`, and `validate-workflow.ts` consumes
56
+ * the same array for the runtime enum check. Adding a variant updates both
57
+ * type-level and runtime arms in one edit.
58
+ */
59
+ export const STAGE_KINDS = ["produces", "side-effect"] as const;
60
+ export type StageKind = (typeof STAGE_KINDS)[number];
61
+
62
+ /**
63
+ * - `"fresh"` — the stage runs in a brand-new detached child session.
64
+ * - `"continue"` — the stage FORKS its predecessor's persisted child session
65
+ * (`SessionManager.forkFrom`), so the child carries the prior conversation as
66
+ * context; the continuation turn is then sent into it, and its outcome is
67
+ * sliced past the inherited prefix by a `branchOffset` re-derived from the
68
+ * forked branch. No predecessor session (start stage / after a loop / file
69
+ * gone) degrades to a fresh dispatch.
70
+ */
71
+ export const SESSION_POLICIES = ["fresh", "continue"] as const;
72
+ export type SessionPolicy = (typeof SESSION_POLICIES)[number];
73
+
74
+ /**
75
+ * What happens when a stage's `outputSchema` rejects the extracted output:
76
+ * - `"retry"` — re-invoke the stage up to `maxRetries`, threading the
77
+ * schema's issues back to the agent via a retry prompt.
78
+ * - `"halt"` — record a terminal failure on the first rejection.
79
+ */
80
+ export const ON_INVALID_VALUES = ["retry", "halt"] as const;
81
+ export type OnInvalid = (typeof ON_INVALID_VALUES)[number];
82
+
83
+ // ===========================================================================
84
+ // Script-stage primitives — skillless TS functions in place of `/skill:<x>`
85
+ // ===========================================================================
86
+
87
+ /**
88
+ * Context handed to a script stage's `run` function. Shape mirrors
89
+ * `EdgeContext` / `FanoutContext`: frozen identity (`cwd`) + the chain
90
+ * data the function needs (`input` — upstream Output envelope) + a
91
+ * read-only state snapshot.
92
+ *
93
+ * Script stages cannot fanout, cannot use `sessionPolicy: "continue"`,
94
+ * and do not receive a Pi `WorkflowHostContext` — they're pure TS calls.
95
+ */
96
+ export interface ScriptContext {
97
+ cwd: string;
98
+ /**
99
+ * Inherited upstream `Output` envelope. `undefined` when the script
100
+ * stage is the entry point, or when the upstream stage cleared the
101
+ * rolling primary slot (a `terminal()` ahead of it).
102
+ */
103
+ input: Output | undefined;
104
+ state: RunView;
105
+ }
106
+
107
+ /**
108
+ * Script `produces` stage body — returns the `Output` envelope's
109
+ * value-channel fields (`kind` + `artifacts` + `data`) directly. The
110
+ * runner stamps `meta` (stage, stageNumber, ts, runId) — same posture
111
+ * as how `ArtifactParser`s return `{ kind, data }` and `finalizeOutput`
112
+ * fills the meta in.
113
+ */
114
+ export type ProducesScriptFn<K extends string = string, D = unknown> = (
115
+ ctx: ScriptContext,
116
+ ) => Omit<Output<K, D>, "meta"> | Promise<Omit<Output<K, D>, "meta">>;
117
+
118
+ /**
119
+ * Script `acts` / `terminal` stage body — returns nothing. The runner
120
+ * builds a `SideEffectOutput`-shaped envelope (kind `"side-effect"`,
121
+ * empty `data`) so audit + downstream chain wiring still uniform.
122
+ */
123
+ export type ActsScriptFn = (ctx: ScriptContext) => void | Promise<void>;
124
+
125
+ /**
126
+ * Raw-prompt dispatch body — the third dispatch alongside `skill`
127
+ * (`/skill:<name> <args>`) and script `run` (pure TS, no model). Returns the
128
+ * COMPLETE user message sent into the stage's session: no `/skill:` prefix and
129
+ * no implicit upstream-artifact arg appended. The dynamic form receives the
130
+ * same `ScriptContext` script stages get, so a prompt can weave in the upstream
131
+ * `Output` (`ctx.input`) or the named registry (`ctx.state.named`):
132
+ *
133
+ * acts({ prompt: "Implement the design spec discussed above.", sessionPolicy: "continue" })
134
+ * produces({ prompt: ({ input }) =>
135
+ * `Summarise ${handleToString(input!.artifacts[0]!.handle)} in 3 bullets.`, outcome })
136
+ *
137
+ * A plain `string` is sugar for `() => string`. Unlike a skill stage, a prompt
138
+ * stage skips the skill-registry preflight (there is no skill to register).
139
+ * Mutually exclusive with `skill` (explicit), `run`, `reads`, and
140
+ * `fanout`/`iterate` loops (units own their prompts). Composes with `kind` (a
141
+ * `produces` prompt stage runs the `outcome` collector and publishes; a
142
+ * `side-effect` prompt stage just talks), with `sessionPolicy` (`continue` = a
143
+ * follow-up turn on a session a prior stage populated), and with `assess`
144
+ * loops / `verify` — the prompt is round/attempt 0's message; `feedForward`
145
+ * builds each retry's complete message. (validated at load + preflight.)
146
+ */
147
+ export type PromptFn = (ctx: ScriptContext) => string | Promise<string>;
148
+
149
+ // ===========================================================================
150
+ // Channel-read declarations for `reads:` stage fields
151
+ // ===========================================================================
152
+
153
+ /**
154
+ * A single `reads:` entry: a bare channel name (latest-wins, the historical
155
+ * default) or a spec selecting ALL accumulated entries of the channel.
156
+ * `fanin()` builds the all-entries spec — the consumer-side mirror of
157
+ * `fanout()`, the fanout-and-synthesize fan-in idiom.
158
+ */
159
+ export type StageRead = string | { readonly name: string; readonly all?: boolean };
160
+
161
+ /**
162
+ * Read EVERY accumulated entry of a channel (run order), not just the latest.
163
+ * The canonical consumer side of fanout-and-synthesize:
164
+ * fanout({ ..., outcome: { name: "plans" } })
165
+ * stage({ reads: [fanin("plans")], skill: "synthesize" })
166
+ * Throws on an empty name, mirroring the value-returning loop/routing builders
167
+ * (gate()/match()/assess()) — NOT the pure passthrough factories in this file
168
+ * (produces()/acts()/terminal()), which apply defaults without validating.
169
+ */
170
+ export function fanin(name: string): { readonly name: string; readonly all: true } {
171
+ requireNonEmptyString(name, "fanin(name)", "name must be a non-empty channel name");
172
+ return { name, all: true };
173
+ }
174
+
175
+ /** The channel name of a read, normalizing bare-string and spec forms. */
176
+ export function readName(read: StageRead): string {
177
+ return typeof read === "string" ? read : read.name;
178
+ }
179
+
180
+ /** Whether a read consumes ALL accumulated entries (vs. latest-wins). */
181
+ export function readsAll(read: StageRead): boolean {
182
+ return typeof read !== "string" && read.all === true;
183
+ }
184
+
185
+ // ===========================================================================
186
+ // StageDef — the discriminated union over the dispatch axis
187
+ // ===========================================================================
188
+
189
+ /**
190
+ * Knobs shared by every stage regardless of how it dispatches — the base the
191
+ * three `StageDef` arms extend. Not exported: authors name the arms (or just
192
+ * `StageDef`), never the base.
193
+ */
194
+ interface StageDefBase<TIn = unknown, TOut = unknown> {
195
+ kind: StageKind;
196
+ sessionPolicy: SessionPolicy;
197
+ /**
198
+ * Standard Schema v1 validator run against `output.data` after the
199
+ * stage's `Outcome` produces it (the typed record parsed out of the
200
+ * agent's emitted artifact). On rejection the runner honours
201
+ * `onInvalid` ("retry" by default, up to `maxRetries`; "halt" to fail
202
+ * fast).
203
+ */
204
+ outputSchema?: StageSchema<unknown, TOut>;
205
+ /**
206
+ * Standard Schema v1 validator run against the inherited upstream
207
+ * `output.data` before the stage runs. A rejection halts the
208
+ * chain immediately (no retry path — the upstream stage is already
209
+ * frozen).
210
+ */
211
+ inputSchema?: StageSchema<unknown, TIn>;
212
+ onInvalid?: OnInvalid;
213
+ maxRetries?: number;
214
+ validateTimeoutMs?: number;
215
+ /**
216
+ * Whether the stage inherits the chain's primary artifact from
217
+ * upstream `produces` stages. Default `true`. Set to `false` on a
218
+ * terminal side-effect — the stage's prompt receives `originalInput`
219
+ * instead of the upstream artifact handle, the `ensureUpstreamArtifact`
220
+ * preflight is bypassed, and the rolling primary slot is cleared on
221
+ * success so any stage following also starts without an inherited
222
+ * artifact.
223
+ *
224
+ * Authored via the `terminal()` factory; the flag is the underlying
225
+ * mechanism. Meaningless on `kind: "produces"` stages (they emit their
226
+ * own outcome) — `validateWorkflow` warns when set there.
227
+ */
228
+ inheritsArtifacts?: boolean;
229
+ }
230
+
231
+ /**
232
+ * The default dispatch arm: the runner sends `/skill:<skill>` into the
233
+ * stage's session. `skill` defaults to the surrounding `Workflow.stages`
234
+ * record key — set it explicitly only when the stage id and the Pi skill
235
+ * differ (aliased stages like `implement-after-revise` invoking the
236
+ * `implement` skill). Pi resolves the skill at run time; there's no
237
+ * allowlist gate — if Pi can't load it, the runner halts pointing at this
238
+ * stage.
239
+ *
240
+ * The `run?: never` / `prompt?: never` members make the other arms'
241
+ * discriminators structurally unsettable here — an object literal mixing
242
+ * dispatches fails to type-check (see `StageDef`).
243
+ */
244
+ export interface SkillStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
245
+ skill?: string;
246
+ outcome?: Outcome;
247
+ /**
248
+ * Opt-in unit loop. When set, the runner expands this stage into one Pi
249
+ * session per unit through ONE driver (`loop.ts`); the constructor picked
250
+ * the kind:
251
+ * - `fanout({...})` — push: all units precomputed; `produces` kind =
252
+ * collecting units (full collect→validate→publish, `outcome.name`
253
+ * required); `acts` kind = side-effect units.
254
+ * - `iterate({...})` — pull: one unit per call, accumulating; requires
255
+ * `kind: "produces"` + `outcome.name`.
256
+ * - `assess({...})` — producer→judge rounds; requires `kind: "produces"`
257
+ * + `outcome.name` (the producer is a collecting unit too).
258
+ * Mutually exclusive with `sessionPolicy: "continue"` (validated at load +
259
+ * at preflight).
260
+ */
261
+ loop?: LoopDef;
262
+ /**
263
+ * Opt-in post-condition judge. When set, the runner desugars this stage
264
+ * into a degenerate assess loop (attempt → verify rounds through the ONE
265
+ * driver, loop.ts): each attempt is graded by `verify.judge`;
266
+ * `verify.done(verdict)` gates advancement; failures retry with
267
+ * `verify.feedForward` feedback up to `verify.max` attempts, then halt
268
+ * with "verification failed". Author via the `verify()` constructor.
269
+ *
270
+ * Lifecycle follows LOOP semantics: `onLoopStart` fires with
271
+ * `kind: "verify"`, attempts/verdicts fire `onUnitStart`/`onUnitEnd`, and
272
+ * the stage does NOT fire `onStageEnd` (same contract as every loop
273
+ * stage). The verdict publishes to `state.named[verify.judge.outcome.name]`.
274
+ *
275
+ * Requires `kind: "produces"` (the judge grades the attempt's artifact).
276
+ * Composes with `reads`. Mutually exclusive with `loop` and
277
+ * `sessionPolicy: "continue"` (validated at load).
278
+ */
279
+ verify?: VerifySpec;
280
+ /**
281
+ * Names this stage consumes from `state.named` to build its prompt.
282
+ * When set, the runner replaces the default single-artifact prompt
283
+ * (`/skill:<name> <handle>`) with a labelled-flag form
284
+ * (`/skill:<name> --<n1> <h1> --<n2> <h2> …`), reading each name's
285
+ * accumulated `Output` and iterating its `artifacts` list.
286
+ *
287
+ * A bare string reads the channel's LATEST entry (`array.at(-1)`); wrap a
288
+ * name in `fanin("name")` to read EVERY accumulated entry — the
289
+ * fanout-and-synthesize fan-in idiom. Empty (or unset) → default prompt
290
+ * behaviour preserved.
291
+ *
292
+ * Names address `state.named` slots, which are keyed by
293
+ * `stage.outcome?.name ?? stage.<record-key>`. Every name in `reads:`
294
+ * must be filled by some upstream stage's produces success (validated
295
+ * at load time by `validateWorkflow`; the `ensureNamedReads` preflight
296
+ * catches the "haven't reached the producer yet" case at runtime).
297
+ */
298
+ reads?: ReadonlyArray<StageRead>;
299
+ run?: never;
300
+ prompt?: never;
301
+ }
302
+
303
+ /**
304
+ * Skillless script stage: the runner calls `run` instead of dispatching a Pi
305
+ * skill — presence of `run` is the dispatch discriminator. Authored via
306
+ * `produces.script(...)`, `acts.script(...)`, or `terminal.script(...)`.
307
+ *
308
+ * `skill`/`outcome`/`loop`/`verify`/`prompt` are structurally unsettable
309
+ * (`never`): the function IS the work and returns the `Output` envelope
310
+ * directly — there is no skill body, no transcript for a collector to scan,
311
+ * no session for a judge to grade, and a TS function writes its own loops.
312
+ * `sessionPolicy: "continue"` is additionally rejected at load (no Pi
313
+ * session exists to continue) — kept as a load rule because jiti-loaded
314
+ * literals erase these types.
315
+ */
316
+ export interface ScriptStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
317
+ run: ProducesScriptFn<string, TOut> | ActsScriptFn;
318
+ /** Same named-channel consumption as a skill stage — `ScriptContext.state.named` still needs the producer gate. `fanin()` reads all entries. */
319
+ reads?: ReadonlyArray<StageRead>;
320
+ skill?: never;
321
+ outcome?: never;
322
+ loop?: never;
323
+ verify?: never;
324
+ prompt?: never;
325
+ }
326
+
327
+ /**
328
+ * Raw-prompt dispatch: the runner sends this text (resolved per the
329
+ * `PromptFn`, or the literal string) into the stage's session instead of
330
+ * `/skill:<skill>`. The stage runs the model with no skill body and no
331
+ * skill-registry check. Presence of `prompt` is the third dispatch
332
+ * discriminator alongside `run`.
333
+ *
334
+ * `skill`/`run`/`reads` are structurally unsettable (`never`): you're either
335
+ * invoking a skill or sending raw text, and a prompt stage's text is
336
+ * author-owned — read `state.named` from the `PromptFn` instead of `reads`.
337
+ * `loop` is narrowed to `AssessLoop` (fanout/iterate units own their
338
+ * prompts); `verify` composes (the prompt is round/attempt 0's message;
339
+ * retries dispatch `feedForward`'s output raw).
340
+ */
341
+ export interface PromptStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
342
+ prompt: string | PromptFn;
343
+ /** A `produces` prompt stage runs the `outcome` collector and publishes like any other producer. */
344
+ outcome?: Outcome;
345
+ /** Model-judged refinement rounds over this prompt stage — assess only. */
346
+ loop?: AssessLoop;
347
+ verify?: VerifySpec;
348
+ skill?: never;
349
+ run?: never;
350
+ reads?: never;
351
+ }
352
+
353
+ /**
354
+ * A stage in the workflow graph — a discriminated union over the DISPATCH
355
+ * axis: skill (`SkillStage`, the default), script (`ScriptStage`,
356
+ * `run` present), or raw prompt (`PromptStage`, `prompt` present). The
357
+ * stage's identity is the surrounding `Workflow.stages` record key.
358
+ *
359
+ * Illegal dispatch combinations (`run` + `skill`, `prompt` + `reads`, …)
360
+ * are unrepresentable on typed call sites — the `never` members fail the
361
+ * assignability check. The load-time validator re-checks the same rules for
362
+ * hand-rolled literals because jiti erases TS types (same posture as the
363
+ * `Judge` union + `judgeShapeIssues`).
364
+ *
365
+ * TYPING MODEL: `<TIn, TOut>` are LOCAL inference helpers — they tie a
366
+ * factory call's `inputSchema`/`outputSchema`/`run` together, then erase at
367
+ * the `Workflow.stages` boundary (`Record<string, StageDef>`). They do NOT
368
+ * carry types across edges; inter-stage typing is runtime-contract-based
369
+ * (schemas validate `output.data` at run time, skill contracts adjudicate
370
+ * composition at load). A typed builder API is a roadmap item.
371
+ */
372
+ export type StageDef<TIn = unknown, TOut = unknown> =
373
+ | SkillStage<TIn, TOut>
374
+ | ScriptStage<TIn, TOut>
375
+ | PromptStage<TIn, TOut>;
376
+
377
+ /**
378
+ * A complete workflow. `name` is what users type as `/wf <name>`; `start`
379
+ * is the entry stage; `stages` is the lexicon; `edges` is the wiring. Every
380
+ * key in `edges` must exist in `stages`; every string value must exist in
381
+ * `stages` or be `"stop"`. Validated at load time by `validate-workflow.ts`.
382
+ */
383
+ export interface Workflow {
384
+ name: string;
385
+ description?: string;
386
+ start: string;
387
+ stages: Record<string, StageDef>;
388
+ edges: Record<string, EdgeTarget>;
389
+ }
390
+
391
+ // ===========================================================================
392
+ // Factories — passthroughs with defaults
393
+ // ===========================================================================
394
+
395
+ /** Identity passthrough; reserved for future normalization / metadata hooks. */
396
+ export function defineWorkflow(spec: Workflow): Workflow {
397
+ return spec;
398
+ }
399
+
400
+ /**
401
+ * Builder options are PROJECTIONS of the union arms: each interface
402
+ * `Pick`s its fields from the arm the factory constructs, and the factory
403
+ * spreads the options over the arm's fixed fields. Adding a knob to an arm
404
+ * is one edit here (extend the `Pick` key list — a stale key no longer on
405
+ * the arm fails compilation); the spread means the factory can never
406
+ * silently drop it.
407
+ */
408
+
409
+ /**
410
+ * Options accepted by `produces.script({ run, ... })`. The validation +
411
+ * inheritance knobs that semantically apply to a pure TS function. `kind`
412
+ * and `sessionPolicy` are not configurable — script stages are always
413
+ * `"produces"` + `"fresh"`.
414
+ */
415
+ interface ProducesScriptOptions<TIn = unknown, TOut = unknown>
416
+ extends Pick<
417
+ ScriptStage<TIn, TOut>,
418
+ "outputSchema" | "inputSchema" | "onInvalid" | "maxRetries" | "validateTimeoutMs" | "inheritsArtifacts" | "reads"
419
+ > {
420
+ run: ProducesScriptFn<string, TOut>;
421
+ }
422
+
423
+ /**
424
+ * Options accepted by `acts.script({ run, ... })` and
425
+ * `terminal.script({ run, ... })`. Validation surface is narrower than
426
+ * the produces variant: side-effect stages have no `outputSchema`
427
+ * (they emit no data envelope), so the retry knobs don't apply.
428
+ */
429
+ interface ActsScriptOptions<TIn = unknown>
430
+ extends Pick<ScriptStage<TIn, void>, "inputSchema" | "inheritsArtifacts" | "reads"> {
431
+ run: ActsScriptFn;
432
+ }
433
+
434
+ /**
435
+ * Options accepted by `produces.prompt({ prompt, outcome, ... })` — the typed
436
+ * builder for a raw-prompt `produces` stage. Dispatch-conflicting fields
437
+ * (`skill`, `run`, `reads`) are structurally absent (the `PromptStage` arm
438
+ * pins them `never`). `outcome` is required (a `produces` stage always needs
439
+ * one); `loop` is `AssessLoop` per the arm.
440
+ */
441
+ interface ProducesPromptOptions<TIn = unknown, TOut = unknown>
442
+ extends Pick<
443
+ PromptStage<TIn, TOut>,
444
+ "prompt" | "outputSchema" | "inputSchema" | "onInvalid" | "maxRetries" | "validateTimeoutMs" | "loop" | "verify"
445
+ > {
446
+ outcome: Outcome;
447
+ /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
448
+ sessionPolicy?: SessionPolicy;
449
+ }
450
+
451
+ /**
452
+ * Options accepted by `acts.prompt({ prompt, ... })` — the typed builder for a
453
+ * raw-prompt side-effect stage (a pure chat turn). Narrower than the produces
454
+ * variant: no `outcome` (nothing collected). For a collecting side-effect
455
+ * prompt stage, use the bare `acts({ prompt, outcome })` field form instead.
456
+ */
457
+ interface ActsPromptOptions<TIn = unknown> extends Pick<PromptStage<TIn, void>, "prompt" | "inputSchema"> {
458
+ /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
459
+ sessionPolicy?: SessionPolicy;
460
+ }
461
+
462
+ /**
463
+ * THE stage-defaults authority — owns the load-bearing `as StageDef<TIn, TOut>`
464
+ * cast (a `Partial<StageDef>` union can't be proven to complete a single arm,
465
+ * so the cast is required for the `Partial`-override factories; taming it here
466
+ * means callers don't repeat the concession) + the shared
467
+ * `{ kind, sessionPolicy, ...overrides }` body. Genericized to `<TIn, TOut>` so
468
+ * the four typed factories (`producesScript`/`producesPrompt`/`actsPrompt`/
469
+ * `actsScript`) route through it without widening against their
470
+ * `StageDef<TIn, TOut>` / `StageDef<TIn, void>` return annotations; the two
471
+ * `Partial`-override factories `producesFn`/`actsFn` call it with the default
472
+ * `<unknown, unknown>` params. `overrides.sessionPolicy ?? "fresh"` honors the
473
+ * `"continue"` override the two prompt factories expose (the trailing
474
+ * `...overrides` spread makes a present `sessionPolicy` win regardless). The
475
+ * cast's load-bearingness is documented ONCE here, not on each twin.
476
+ */
477
+ function withDefaults<TIn = unknown, TOut = unknown>(
478
+ kind: "produces" | "side-effect",
479
+ overrides: Partial<StageDef<TIn, TOut>> & { sessionPolicy?: SessionPolicy } = {},
480
+ ): StageDef<TIn, TOut> {
481
+ return { kind, sessionPolicy: overrides.sessionPolicy ?? "fresh", ...overrides } as StageDef<TIn, TOut>;
482
+ }
483
+
484
+ function producesFn(overrides: Partial<StageDef> = {}): StageDef {
485
+ return withDefaults("produces", overrides);
486
+ }
487
+
488
+ function producesScript<TIn = unknown, TOut = unknown>(opts: ProducesScriptOptions<TIn, TOut>): StageDef<TIn, TOut> {
489
+ return withDefaults<TIn, TOut>("produces", opts);
490
+ }
491
+
492
+ function producesPrompt<TIn = unknown, TOut = unknown>(opts: ProducesPromptOptions<TIn, TOut>): StageDef<TIn, TOut> {
493
+ return withDefaults<TIn, TOut>("produces", opts);
494
+ }
495
+
496
+ function actsFn(overrides: Partial<StageDef> = {}): StageDef {
497
+ return withDefaults("side-effect", overrides);
498
+ }
499
+
500
+ function actsPrompt<TIn = unknown>(opts: ActsPromptOptions<TIn>): StageDef<TIn, void> {
501
+ return withDefaults<TIn, void>("side-effect", opts);
502
+ }
503
+
504
+ function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
505
+ return withDefaults<TIn, void>("side-effect", opts);
506
+ }
507
+
508
+ // A terminal stage = side-effect + inheritsArtifacts: false (see the `terminal()`
509
+ // public doc). `terminalFn` (Partial path) and `terminalScript` (concrete-opts
510
+ // path below) are the two realizations; both set the same marker.
511
+ //
512
+ // "terminal" SENSE 1 (the factory — this fn + the `terminal` export below): a
513
+ // side-effect stage that does NOT inherit the upstream artifact. Distinct from
514
+ // SENSE 2 (graph sink — `StageShape.edge.mode: "terminal"` in loop-constructors.ts
515
+ // / `{ kind: "stop" }` in routing.ts: no outgoing edge OR explicit `STOP`;
516
+ // orthogonal to this factory — a `terminal()` stage can route onward, and a
517
+ // plain stage can be a sink) and SENSE 3 (run-outcome prose — "terminal
518
+ // failure/outcome" = a halt that ends the run, e.g. audit.ts `writeFailureRow`).
519
+ // See the `terminal` export doc below for the full glossary.
520
+ function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
521
+ return withDefaults("side-effect", { ...overrides, inheritsArtifacts: false });
522
+ }
523
+
524
+ // Concrete-opts twin of `terminalFn` above — both realize "side-effect +
525
+ // inheritsArtifacts: false" via their respective paths (script vs Partial).
526
+ function terminalScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
527
+ return actsScript({ ...opts, inheritsArtifacts: false });
528
+ }
529
+
530
+ /**
531
+ * Artifact-producing stage: invokes a Pi skill that writes
532
+ * `.rpiv/artifacts/<bucket>/<file>.md`. Defaults to fresh-session. The
533
+ * skill body defaults to the surrounding `stages` record key — override
534
+ * via `{ skill: "<other>" }` only when the stage id and the Pi skill
535
+ * differ (e.g. a stage keyed `design-after-review` aliasing the
536
+ * `design` skill so it can appear twice in the same workflow's edge graph).
537
+ *
538
+ * Skillless variant: `produces.script({ run, outputSchema?, ... })` runs
539
+ * a pure TS function in place of a Pi skill body. The function returns
540
+ * the `Output<K, D>` envelope directly.
541
+ *
542
+ * Raw-prompt variant: `produces.prompt({ prompt, outcome, ... })` dispatches
543
+ * author-owned text (no `/skill:` prefix) and collects the reply via `outcome`.
544
+ * The typed options omit the dispatch-conflicting fields so invalid combos are
545
+ * un-typable on a literal call site; `loop` is narrowed to `AssessLoop` and
546
+ * `verify` composes (prompt = round/attempt 0; `feedForward` = retries, raw).
547
+ */
548
+ export const produces = Object.assign(producesFn, { script: producesScript, prompt: producesPrompt });
549
+
550
+ /**
551
+ * Side-effect stage: invokes a Pi skill whose side effect IS the work
552
+ * (commit, implement). No artifact-emission check. Defaults to fresh-session.
553
+ * Like `produces`, the skill body defaults to the record key.
554
+ *
555
+ * Skillless variant: `acts.script({ run, ... })` runs a pure TS
556
+ * function in place of a Pi skill body; the runner synthesises a
557
+ * `SideEffectOutput` envelope so the chain stays uniform.
558
+ *
559
+ * Raw-prompt variant: `acts.prompt({ prompt, sessionPolicy? })` dispatches
560
+ * author-owned text as a pure chat turn (no artifact collected) — the typed
561
+ * builder for the continue follow-up shape.
562
+ */
563
+ export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsPrompt });
564
+
565
+ /**
566
+ * Terminal side-effect stage: an `acts`-shaped stage that does NOT inherit
567
+ * the upstream primary artifact. The stage's prompt receives the run's
568
+ * `originalInput` instead of an upstream artifact handle; the
569
+ * `ensureUpstreamArtifact` preflight is bypassed; and the rolling primary
570
+ * slot is cleared on success so anything downstream also starts without an
571
+ * inherited handle.
572
+ *
573
+ * Sibling to `produces()` / `acts()`. The right answer when a final stage
574
+ * (cleanup, summary, post-run notification) shouldn't be coupled to the
575
+ * upstream chain's artifact.
576
+ *
577
+ * Desugars to `acts({ ...overrides, inheritsArtifacts: false })`. The
578
+ * skillless variant `terminal.script({ run, ... })` desugars to
579
+ * `acts.script({ ...opts, inheritsArtifacts: false })`.
580
+ *
581
+ * ── Glossary: "terminal" has three unrelated senses in this package ──
582
+ * 1. FACTORY (this export, `terminalFn`/`terminalScript`): a side-effect
583
+ * stage that does NOT inherit the upstream artifact (`inheritsArtifacts:
584
+ * false`). A `terminal()` stage may still carry a downstream edge.
585
+ * 2. GRAPH SINK (`StageShape.edge.mode: "terminal"` in loop-constructors.ts;
586
+ * `{ kind: "stop" }` in routing.ts `RoutingResult`; rendered "(terminal)"
587
+ * by preview.ts `formatEdge`; "implicit terminals" in validate/graph.ts):
588
+ * a stage with NO outgoing edge OR an explicit `STOP`. Orthogonal to the
589
+ * factory — a `terminal()` stage can route onward, a plain stage can be a
590
+ * sink.
591
+ * 3. RUN OUTCOME ("terminal failure/outcome" prose, e.g. audit.ts
592
+ * `writeFailureRow` / `recordTerminalFailure`): a failure/cancellation/
593
+ * abort that ends the run.
594
+ */
595
+ export const terminal = Object.assign(terminalFn, { script: terminalScript });
@@ -0,0 +1,84 @@
1
+ import type { FailureText } from "./messages.js";
2
+
3
+ /**
4
+ * Shared-kernel stage error vocabulary — a package-root LEAF (zero value
5
+ * imports; only a type-only `FailureText` pull) so
6
+ * both the engine's loop-primitive layer (`loop-kinds.ts`) and the runner's
7
+ * per-stage pipeline (`runner/{preflight,input-validation,failure}.ts`) can
8
+ * throw it without anyone importing across the `runner/` boundary. Homed at
9
+ * the root, the import arrow points strictly downward for every consumer
10
+ * (`loop-kinds.ts` — a module the runner imports FROM — never reaches back
11
+ * UP into `runner/`). `runner/errors.ts` re-exports it so the in-`runner/`
12
+ * call sites keep their local spelling.
13
+ */
14
+
15
+ /**
16
+ * Thrown by a preflight check on failure; carries the recorded-row
17
+ * attribution + notify/err messages so `runStageOrRecordFailure` can land
18
+ * a uniform JSONL row regardless of which slot tripped.
19
+ *
20
+ * `kind` annotates the violation class for diagnostics only — control
21
+ * flow at the catch site is uniform:
22
+ * - `"halt"` — runtime-state failure (skill not registered, missing
23
+ * upstream artifact, schema mismatch).
24
+ * - `"invariant"` — authoring-time-knowable violation that
25
+ * `validateWorkflow` should reject at load. A throw
26
+ * here means validation was bypassed or the rule lives
27
+ * only in the runner (continue-without-pi).
28
+ */
29
+ export class StagePreflightError extends Error {
30
+ constructor(
31
+ public readonly kind: "halt" | "invariant",
32
+ public readonly skill: string,
33
+ public readonly notifyMsg: string,
34
+ public readonly errMsg: string,
35
+ public readonly notifyPartial: boolean,
36
+ ) {
37
+ super(errMsg);
38
+ this.name = "StagePreflightError";
39
+ }
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Facade constructors
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * The ONE construction site — `notifyPartial` is DERIVED from `kind` (halt →
48
+ * `true`, invariant → `false`), so a status/level mismatch is unrepresentable.
49
+ * Modeled after `audit.ts:terminalArgsOf` (which derives `notifyLevel` from
50
+ * `status`). Halt sites build via `haltPreflight` / `invariantPreflight` so
51
+ * the literal `new StagePreflightError(…)` never re-appears at a call site.
52
+ */
53
+ function preflightErrorOf(
54
+ kind: "halt" | "invariant",
55
+ skill: string,
56
+ notifyMsg: string,
57
+ errMsg: string,
58
+ ): StagePreflightError {
59
+ return new StagePreflightError(kind, skill, notifyMsg, errMsg, kind === "halt");
60
+ }
61
+
62
+ /**
63
+ * Pattern A — runtime-state failure (skill not registered, missing upstream
64
+ * artifact, schema mismatch). `notifyPartial: true` (the stage produced a
65
+ * partial worth surfacing). Built from one `FailureText` so the toast/error
66
+ * pairing lives in the `FAIL_*` factory and can't drift.
67
+ */
68
+ export function haltPreflight(skill: string, failure: FailureText): StagePreflightError {
69
+ return preflightErrorOf("halt", skill, failure.toast, failure.error);
70
+ }
71
+
72
+ /**
73
+ * Pattern B — authoring-time-knowable violation that `validateWorkflow` should
74
+ * reject at load (`continue-without-pi`, a corrupted loop cursor). A throw
75
+ * here means validation was bypassed or the rule lives only in the runner.
76
+ * `notifyPartial: false`. Single-message form (notifyMsg === errMsg); the
77
+ * two-arg overload splits them (e.g. a runner wrapper that frames the user
78
+ * message while preserving the raw `reason` as `errMsg`).
79
+ */
80
+ export function invariantPreflight(name: string, msg: string): StagePreflightError;
81
+ export function invariantPreflight(name: string, notifyMsg: string, errMsg: string): StagePreflightError;
82
+ export function invariantPreflight(name: string, notifyMsg: string, errMsg?: string): StagePreflightError {
83
+ return preflightErrorOf("invariant", name, notifyMsg, errMsg ?? notifyMsg);
84
+ }