@juicesharp/rpiv-workflow 1.19.0 → 1.20.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 (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/stage-def.ts ADDED
@@ -0,0 +1,527 @@
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 type { AssessLoop, LoopDef, VerifySpec } from "./loop-def.js";
15
+ import type { Output, RunView } from "./output.js";
16
+ import type { Outcome } from "./output-spec.js";
17
+ import type { EdgeTarget } from "./routing-dsl.js";
18
+
19
+ /**
20
+ * Schema attached to a stage's `outputSchema` / `inputSchema`. Structurally
21
+ * a Standard Schema v1 (the converged interface implemented by Zod, Valibot,
22
+ * ArkType, TypeBox, et al.) — re-exported under a name that doesn't leak the
23
+ * spec version into our public surface. When the spec versions, this alias
24
+ * picks the right one in a single line.
25
+ *
26
+ * Sync schemas are the default and the recommended shape for the 95% case
27
+ * (pure shape contracts: `Type.Object({ … })`, `z.object({ … })`). Async
28
+ * schemas are supported at both seams — the runner awaits `~standard.validate`
29
+ * — and are the right answer when correctness needs I/O (filesystem probes,
30
+ * registry lookups, async-by-default libs like ArkType). A hanging async
31
+ * schema is bounded by the stage's `validateTimeoutMs`. See the
32
+ * "Validators: sync vs async" section of the package README for the full
33
+ * rationale.
34
+ */
35
+ export type StageSchema<TIn = unknown, TOut = TIn> = StandardSchemaV1<TIn, TOut>;
36
+
37
+ // ===========================================================================
38
+ // Stage-shape primitives
39
+ // ===========================================================================
40
+
41
+ /**
42
+ * - `"produces"` — protocol skills that write `.rpiv/artifacts/<bucket>/<file>.md`.
43
+ * The runner halts the chain if the path doesn't appear in the transcript.
44
+ * - `"side-effect"` — action skills (commit, implement) where the side effect IS
45
+ * the work; the chain inherits the prior `currentPrimaryArtifact(state)`.
46
+ *
47
+ * Naming is DELIBERATELY split between data and authoring surface: the kind
48
+ * literal is descriptive (`"side-effect"` — what lands in rows and output
49
+ * envelopes) while its factory is a verb (`acts()` — what reads naturally in
50
+ * a stage record). `terminal()` is not a third kind: it builds
51
+ * `"side-effect"` + `inheritsArtifacts: false`. See the README glossary.
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
+ // Script-stage primitives — skillless TS functions in place of `/skill:<x>`
80
+ // ===========================================================================
81
+
82
+ /**
83
+ * Context handed to a script stage's `run` function. Shape mirrors
84
+ * `EdgeContext` / `FanoutContext`: frozen identity (`cwd`) + the chain
85
+ * data the function needs (`input` — upstream Output envelope) + a
86
+ * read-only state snapshot.
87
+ *
88
+ * Script stages cannot fanout, cannot use `sessionPolicy: "continue"`,
89
+ * and do not receive a Pi `WorkflowHostContext` — they're pure TS calls.
90
+ */
91
+ export interface ScriptContext {
92
+ cwd: string;
93
+ /**
94
+ * Inherited upstream `Output` envelope. `undefined` when the script
95
+ * stage is the entry point, or when the upstream stage cleared the
96
+ * rolling primary slot (a `terminal()` ahead of it).
97
+ */
98
+ input: Output | undefined;
99
+ state: RunView;
100
+ }
101
+
102
+ /**
103
+ * Script `produces` stage body — returns the `Output` envelope's
104
+ * value-channel fields (`kind` + `artifacts` + `data`) directly. The
105
+ * runner stamps `meta` (stage, stageNumber, ts, runId) — same posture
106
+ * as how `ArtifactParser`s return `{ kind, data }` and `finalizeOutput`
107
+ * fills the meta in.
108
+ */
109
+ export type ProducesScriptFn<K extends string = string, D = unknown> = (
110
+ ctx: ScriptContext,
111
+ ) => Omit<Output<K, D>, "meta"> | Promise<Omit<Output<K, D>, "meta">>;
112
+
113
+ /**
114
+ * Script `acts` / `terminal` stage body — returns nothing. The runner
115
+ * builds a `SideEffectOutput`-shaped envelope (kind `"side-effect"`,
116
+ * empty `data`) so audit + downstream chain wiring still uniform.
117
+ */
118
+ export type ActsScriptFn = (ctx: ScriptContext) => void | Promise<void>;
119
+
120
+ /**
121
+ * Raw-prompt dispatch body — the third dispatch alongside `skill`
122
+ * (`/skill:<name> <args>`) and script `run` (pure TS, no model). Returns the
123
+ * COMPLETE user message sent into the stage's session: no `/skill:` prefix and
124
+ * no implicit upstream-artifact arg appended. The dynamic form receives the
125
+ * same `ScriptContext` script stages get, so a prompt can weave in the upstream
126
+ * `Output` (`ctx.input`) or the named registry (`ctx.state.named`):
127
+ *
128
+ * acts({ prompt: "Implement the design spec discussed above.", sessionPolicy: "continue" })
129
+ * produces({ prompt: ({ input }) =>
130
+ * `Summarise ${handleToString(input!.artifacts[0]!.handle)} in 3 bullets.`, outcome })
131
+ *
132
+ * A plain `string` is sugar for `() => string`. Unlike a skill stage, a prompt
133
+ * stage skips the skill-registry preflight (there is no skill to register).
134
+ * Mutually exclusive with `skill` (explicit), `run`, `reads`, and
135
+ * `fanout`/`iterate` loops (units own their prompts). Composes with `kind` (a
136
+ * `produces` prompt stage runs the `outcome` collector and publishes; a
137
+ * `side-effect` prompt stage just talks), with `sessionPolicy` (`continue` = a
138
+ * follow-up turn on a session a prior stage populated), and with `assess`
139
+ * loops / `verify` — the prompt is round/attempt 0's message; `feedForward`
140
+ * builds each retry's complete message. (validated at load + preflight.)
141
+ */
142
+ export type PromptFn = (ctx: ScriptContext) => string | Promise<string>;
143
+
144
+ // ===========================================================================
145
+ // StageDef — the discriminated union over the dispatch axis (T1)
146
+ // ===========================================================================
147
+
148
+ /**
149
+ * Knobs shared by every stage regardless of how it dispatches — the base the
150
+ * three `StageDef` arms extend. Not exported: authors name the arms (or just
151
+ * `StageDef`), never the base.
152
+ */
153
+ interface StageDefBase<TIn = unknown, TOut = unknown> {
154
+ kind: StageKind;
155
+ sessionPolicy: SessionPolicy;
156
+ /**
157
+ * Standard Schema v1 validator run against `output.data` after the
158
+ * stage's `Outcome` produces it (the typed record parsed out of the
159
+ * agent's emitted artifact). On rejection the runner honours
160
+ * `onInvalid` ("retry" by default, up to `maxRetries`; "halt" to fail
161
+ * fast).
162
+ */
163
+ outputSchema?: StageSchema<unknown, TOut>;
164
+ /**
165
+ * Standard Schema v1 validator run against the inherited upstream
166
+ * `output.data` before the stage runs. A rejection halts the
167
+ * chain immediately (no retry path — the upstream stage is already
168
+ * frozen).
169
+ */
170
+ inputSchema?: StageSchema<unknown, TIn>;
171
+ onInvalid?: OnInvalid;
172
+ maxRetries?: number;
173
+ validateTimeoutMs?: number;
174
+ /**
175
+ * Whether the stage inherits the chain's primary artifact from
176
+ * upstream `produces` stages. Default `true`. Set to `false` on a
177
+ * terminal side-effect — the stage's prompt receives `originalInput`
178
+ * instead of the upstream artifact handle, the `ensureUpstreamArtifact`
179
+ * preflight is bypassed, and the rolling primary slot is cleared on
180
+ * success so any stage following also starts without an inherited
181
+ * artifact.
182
+ *
183
+ * Authored via the `terminal()` factory; the flag is the underlying
184
+ * mechanism. Meaningless on `kind: "produces"` stages (they emit their
185
+ * own outcome) — `validateWorkflow` warns when set there.
186
+ */
187
+ inheritsArtifacts?: boolean;
188
+ }
189
+
190
+ /**
191
+ * The default dispatch arm: the runner sends `/skill:<skill>` into the
192
+ * stage's session. `skill` defaults to the surrounding `Workflow.stages`
193
+ * record key — set it explicitly only when the stage id and the Pi skill
194
+ * differ (aliased stages like `implement-after-revise` invoking the
195
+ * `implement` skill). Pi resolves the skill at run time; there's no
196
+ * allowlist gate — if Pi can't load it, the runner halts pointing at this
197
+ * stage.
198
+ *
199
+ * The `run?: never` / `prompt?: never` members make the other arms'
200
+ * discriminators structurally unsettable here — an object literal mixing
201
+ * dispatches fails to type-check (see `StageDef`).
202
+ */
203
+ export interface SkillStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
204
+ skill?: string;
205
+ outcome?: Outcome;
206
+ /**
207
+ * Opt-in unit loop. When set, the runner expands this stage into one Pi
208
+ * session per unit through ONE driver (`loop.ts`); the constructor picked
209
+ * the kind:
210
+ * - `fanout({...})` — push: all units precomputed; `produces` kind =
211
+ * collecting units (full collect→validate→publish, `outcome.name`
212
+ * required); `acts` kind = side-effect units.
213
+ * - `iterate({...})` — pull: one unit per call, accumulating; requires
214
+ * `kind: "produces"` + `outcome.name`.
215
+ * - `assess({...})` — producer→judge rounds; requires `kind: "produces"`
216
+ * + `outcome.name` (the producer is a collecting unit too).
217
+ * Mutually exclusive with `sessionPolicy: "continue"` (validated at load +
218
+ * at preflight).
219
+ */
220
+ loop?: LoopDef;
221
+ /**
222
+ * Opt-in post-condition judge. When set, the runner desugars this stage
223
+ * into a degenerate assess loop (attempt → verify rounds through the ONE
224
+ * driver, loop.ts): each attempt is graded by `verify.judge`;
225
+ * `verify.done(verdict)` gates advancement; failures retry with
226
+ * `verify.feedForward` feedback up to `verify.max` attempts, then halt
227
+ * with "verification failed". Author via the `verify()` constructor.
228
+ *
229
+ * Lifecycle follows LOOP semantics: `onLoopStart` fires with
230
+ * `kind: "verify"`, attempts/verdicts fire `onUnitStart`/`onUnitEnd`, and
231
+ * the stage does NOT fire `onStageEnd` (same contract as every loop
232
+ * stage). The verdict publishes to `state.named[verify.judge.outcome.name]`.
233
+ *
234
+ * Requires `kind: "produces"` (the judge grades the attempt's artifact).
235
+ * Composes with `reads`. Mutually exclusive with `loop` and
236
+ * `sessionPolicy: "continue"` (validated at load).
237
+ */
238
+ verify?: VerifySpec;
239
+ /**
240
+ * Names this stage consumes from `state.named` to build its prompt.
241
+ * When set, the runner replaces the default single-artifact prompt
242
+ * (`/skill:<name> <handle>`) with a labelled-flag form
243
+ * (`/skill:<name> --<n1> <h1> --<n2> <h2> …`), reading the most recent
244
+ * `Output` each name has accumulated and iterating its `artifacts` list.
245
+ * Empty (or unset) → default prompt behaviour preserved.
246
+ *
247
+ * Names address `state.named` slots, which are keyed by
248
+ * `stage.outcome?.name ?? stage.<record-key>`. Every name in `reads:`
249
+ * must be filled by some upstream stage's produces success (validated
250
+ * at load time by `validateWorkflow`; the `ensureNamedReads` preflight
251
+ * catches the "haven't reached the producer yet" case at runtime).
252
+ */
253
+ reads?: ReadonlyArray<string>;
254
+ run?: never;
255
+ prompt?: never;
256
+ }
257
+
258
+ /**
259
+ * Skillless script stage: the runner calls `run` instead of dispatching a Pi
260
+ * skill — presence of `run` is the dispatch discriminator. Authored via
261
+ * `produces.script(...)`, `acts.script(...)`, or `terminal.script(...)`.
262
+ *
263
+ * `skill`/`outcome`/`loop`/`verify`/`prompt` are structurally unsettable
264
+ * (`never`): the function IS the work and returns the `Output` envelope
265
+ * directly — there is no skill body, no transcript for a collector to scan,
266
+ * no session for a judge to grade, and a TS function writes its own loops.
267
+ * `sessionPolicy: "continue"` is additionally rejected at load (no Pi
268
+ * session exists to continue) — kept as a load rule because jiti-loaded
269
+ * literals erase these types.
270
+ */
271
+ export interface ScriptStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
272
+ run: ProducesScriptFn<string, TOut> | ActsScriptFn;
273
+ /** Same named-channel consumption as a skill stage — `ScriptContext.state.named` still needs the producer gate. */
274
+ reads?: ReadonlyArray<string>;
275
+ skill?: never;
276
+ outcome?: never;
277
+ loop?: never;
278
+ verify?: never;
279
+ prompt?: never;
280
+ }
281
+
282
+ /**
283
+ * Raw-prompt dispatch: the runner sends this text (resolved per the
284
+ * `PromptFn`, or the literal string) into the stage's session instead of
285
+ * `/skill:<skill>`. The stage runs the model with no skill body and no
286
+ * skill-registry check. Presence of `prompt` is the third dispatch
287
+ * discriminator alongside `run`.
288
+ *
289
+ * `skill`/`run`/`reads` are structurally unsettable (`never`): you're either
290
+ * invoking a skill or sending raw text, and a prompt stage's text is
291
+ * author-owned — read `state.named` from the `PromptFn` instead of `reads`.
292
+ * `loop` is narrowed to `AssessLoop` (fanout/iterate units own their
293
+ * prompts); `verify` composes (the prompt is round/attempt 0's message;
294
+ * retries dispatch `feedForward`'s output raw).
295
+ */
296
+ export interface PromptStage<TIn = unknown, TOut = unknown> extends StageDefBase<TIn, TOut> {
297
+ prompt: string | PromptFn;
298
+ /** A `produces` prompt stage runs the `outcome` collector and publishes like any other producer. */
299
+ outcome?: Outcome;
300
+ /** Model-judged refinement rounds over this prompt stage — assess only. */
301
+ loop?: AssessLoop;
302
+ verify?: VerifySpec;
303
+ skill?: never;
304
+ run?: never;
305
+ reads?: never;
306
+ }
307
+
308
+ /**
309
+ * A stage in the workflow graph — a discriminated union over the DISPATCH
310
+ * axis (T1): skill (`SkillStage`, the default), script (`ScriptStage`,
311
+ * `run` present), or raw prompt (`PromptStage`, `prompt` present). The
312
+ * stage's identity is the surrounding `Workflow.stages` record key.
313
+ *
314
+ * Illegal dispatch combinations (`run` + `skill`, `prompt` + `reads`, …)
315
+ * are unrepresentable on typed call sites — the `never` members fail the
316
+ * assignability check. The load-time validator re-checks the same rules for
317
+ * hand-rolled literals because jiti erases TS types (same posture as the
318
+ * `Judge` union + `judgeShapeIssues`).
319
+ *
320
+ * TYPING MODEL (T2): `<TIn, TOut>` are LOCAL inference helpers — they tie a
321
+ * factory call's `inputSchema`/`outputSchema`/`run` together, then erase at
322
+ * the `Workflow.stages` boundary (`Record<string, StageDef>`). They do NOT
323
+ * carry types across edges; inter-stage typing is runtime-contract-based
324
+ * (schemas validate `output.data` at run time, skill contracts adjudicate
325
+ * composition at load). A typed builder API is a roadmap item.
326
+ */
327
+ export type StageDef<TIn = unknown, TOut = unknown> =
328
+ | SkillStage<TIn, TOut>
329
+ | ScriptStage<TIn, TOut>
330
+ | PromptStage<TIn, TOut>;
331
+
332
+ /**
333
+ * A complete workflow. `name` is what users type as `/wf <name>`; `start`
334
+ * is the entry stage; `stages` is the lexicon; `edges` is the wiring. Every
335
+ * key in `edges` must exist in `stages`; every string value must exist in
336
+ * `stages` or be `"stop"`. Validated at load time by `validate-workflow.ts`.
337
+ */
338
+ export interface Workflow {
339
+ name: string;
340
+ description?: string;
341
+ start: string;
342
+ stages: Record<string, StageDef>;
343
+ edges: Record<string, EdgeTarget>;
344
+ }
345
+
346
+ // ===========================================================================
347
+ // Factories — passthroughs with defaults
348
+ // ===========================================================================
349
+
350
+ /** Identity passthrough; reserved for future normalization / metadata hooks. */
351
+ export function defineWorkflow(spec: Workflow): Workflow {
352
+ return spec;
353
+ }
354
+
355
+ /**
356
+ * Builder options are PROJECTIONS of the union arms (T13): each interface
357
+ * `Pick`s its fields from the arm the factory constructs, and the factory
358
+ * spreads the options over the arm's fixed fields. Adding a knob to an arm
359
+ * is one edit here (extend the `Pick` key list — a stale key no longer on
360
+ * the arm fails compilation); the spread means the factory can never
361
+ * silently drop it.
362
+ */
363
+
364
+ /**
365
+ * Options accepted by `produces.script({ run, ... })`. The validation +
366
+ * inheritance knobs that semantically apply to a pure TS function. `kind`
367
+ * and `sessionPolicy` are not configurable — script stages are always
368
+ * `"produces"` + `"fresh"`.
369
+ */
370
+ interface ProducesScriptOptions<TIn = unknown, TOut = unknown>
371
+ extends Pick<
372
+ ScriptStage<TIn, TOut>,
373
+ "outputSchema" | "inputSchema" | "onInvalid" | "maxRetries" | "validateTimeoutMs" | "inheritsArtifacts" | "reads"
374
+ > {
375
+ run: ProducesScriptFn<string, TOut>;
376
+ }
377
+
378
+ /**
379
+ * Options accepted by `acts.script({ run, ... })` and
380
+ * `terminal.script({ run, ... })`. Validation surface is narrower than
381
+ * the produces variant: side-effect stages have no `outputSchema`
382
+ * (they emit no data envelope), so the retry knobs don't apply.
383
+ */
384
+ interface ActsScriptOptions<TIn = unknown>
385
+ extends Pick<ScriptStage<TIn, void>, "inputSchema" | "inheritsArtifacts" | "reads"> {
386
+ run: ActsScriptFn;
387
+ }
388
+
389
+ /**
390
+ * Options accepted by `produces.prompt({ prompt, outcome, ... })` — the typed
391
+ * builder for a raw-prompt `produces` stage. Dispatch-conflicting fields
392
+ * (`skill`, `run`, `reads`) are structurally absent (the `PromptStage` arm
393
+ * pins them `never`). `outcome` is required (a `produces` stage always needs
394
+ * one); `loop` is `AssessLoop` per the arm.
395
+ */
396
+ interface ProducesPromptOptions<TIn = unknown, TOut = unknown>
397
+ extends Pick<
398
+ PromptStage<TIn, TOut>,
399
+ "prompt" | "outputSchema" | "inputSchema" | "onInvalid" | "maxRetries" | "validateTimeoutMs" | "loop" | "verify"
400
+ > {
401
+ outcome: Outcome;
402
+ /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
403
+ sessionPolicy?: SessionPolicy;
404
+ }
405
+
406
+ /**
407
+ * Options accepted by `acts.prompt({ prompt, ... })` — the typed builder for a
408
+ * raw-prompt side-effect stage (a pure chat turn). Narrower than the produces
409
+ * variant: no `outcome` (nothing collected). For a collecting side-effect
410
+ * prompt stage, use the bare `acts({ prompt, outcome })` field form instead.
411
+ */
412
+ interface ActsPromptOptions<TIn = unknown> extends Pick<PromptStage<TIn, void>, "prompt" | "inputSchema"> {
413
+ /** `"continue"` makes this a follow-up turn on a session a prior stage populated. */
414
+ sessionPolicy?: SessionPolicy;
415
+ }
416
+
417
+ function producesFn(overrides: Partial<StageDef> = {}): StageDef {
418
+ // The cast is the factory's one concession: a `Partial` of a union can't be
419
+ // proven to complete a single arm. Call sites stay arm-checked (an object
420
+ // literal mixing dispatches fails before it reaches the spread).
421
+ return {
422
+ kind: "produces",
423
+ sessionPolicy: "fresh",
424
+ ...overrides,
425
+ } as StageDef;
426
+ }
427
+
428
+ function producesScript<TIn = unknown, TOut = unknown>(opts: ProducesScriptOptions<TIn, TOut>): StageDef<TIn, TOut> {
429
+ return {
430
+ kind: "produces",
431
+ sessionPolicy: "fresh",
432
+ ...opts,
433
+ };
434
+ }
435
+
436
+ function producesPrompt<TIn = unknown, TOut = unknown>(opts: ProducesPromptOptions<TIn, TOut>): StageDef<TIn, TOut> {
437
+ return {
438
+ kind: "produces",
439
+ ...opts,
440
+ sessionPolicy: opts.sessionPolicy ?? "fresh",
441
+ };
442
+ }
443
+
444
+ function actsFn(overrides: Partial<StageDef> = {}): StageDef {
445
+ return {
446
+ kind: "side-effect",
447
+ sessionPolicy: "fresh",
448
+ ...overrides,
449
+ } as StageDef;
450
+ }
451
+
452
+ function actsPrompt<TIn = unknown>(opts: ActsPromptOptions<TIn>): StageDef<TIn, void> {
453
+ return {
454
+ kind: "side-effect",
455
+ ...opts,
456
+ sessionPolicy: opts.sessionPolicy ?? "fresh",
457
+ };
458
+ }
459
+
460
+ function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
461
+ return {
462
+ kind: "side-effect",
463
+ sessionPolicy: "fresh",
464
+ ...opts,
465
+ };
466
+ }
467
+
468
+ function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
469
+ return actsFn({ ...overrides, inheritsArtifacts: false } as Partial<StageDef>);
470
+ }
471
+
472
+ function terminalScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn, void> {
473
+ return actsScript({ ...opts, inheritsArtifacts: false });
474
+ }
475
+
476
+ /**
477
+ * Artifact-producing stage: invokes a Pi skill that writes
478
+ * `.rpiv/artifacts/<bucket>/<file>.md`. Defaults to fresh-session. The
479
+ * skill body defaults to the surrounding `stages` record key — override
480
+ * via `{ skill: "<other>" }` only when the stage id and the Pi skill
481
+ * differ (e.g. a stage keyed `design-after-review` aliasing the
482
+ * `design` skill so it can appear twice in the same workflow's edge graph).
483
+ *
484
+ * Skillless variant: `produces.script({ run, outputSchema?, ... })` runs
485
+ * a pure TS function in place of a Pi skill body. The function returns
486
+ * the `Output<K, D>` envelope directly.
487
+ *
488
+ * Raw-prompt variant: `produces.prompt({ prompt, outcome, ... })` dispatches
489
+ * author-owned text (no `/skill:` prefix) and collects the reply via `outcome`.
490
+ * The typed options omit the dispatch-conflicting fields so invalid combos are
491
+ * un-typable on a literal call site; `loop` is narrowed to `AssessLoop` and
492
+ * `verify` composes (prompt = round/attempt 0; `feedForward` = retries, raw).
493
+ */
494
+ export const produces = Object.assign(producesFn, { script: producesScript, prompt: producesPrompt });
495
+
496
+ /**
497
+ * Side-effect stage: invokes a Pi skill whose side effect IS the work
498
+ * (commit, implement). No artifact-emission check. Defaults to fresh-session.
499
+ * Like `produces`, the skill body defaults to the record key.
500
+ *
501
+ * Skillless variant: `acts.script({ run, ... })` runs a pure TS
502
+ * function in place of a Pi skill body; the runner synthesises a
503
+ * `SideEffectOutput` envelope so the chain stays uniform.
504
+ *
505
+ * Raw-prompt variant: `acts.prompt({ prompt, sessionPolicy? })` dispatches
506
+ * author-owned text as a pure chat turn (no artifact collected) — the typed
507
+ * builder for the continue follow-up shape.
508
+ */
509
+ export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsPrompt });
510
+
511
+ /**
512
+ * Terminal side-effect stage: an `acts`-shaped stage that does NOT inherit
513
+ * the upstream primary artifact. The stage's prompt receives the run's
514
+ * `originalInput` instead of an upstream artifact handle; the
515
+ * `ensureUpstreamArtifact` preflight is bypassed; and the rolling primary
516
+ * slot is cleared on success so anything downstream also starts without an
517
+ * inherited handle.
518
+ *
519
+ * Sibling to `produces()` / `acts()`. The right answer when a final stage
520
+ * (cleanup, summary, post-run notification) shouldn't be coupled to the
521
+ * upstream chain's artifact.
522
+ *
523
+ * Desugars to `acts({ ...overrides, inheritsArtifacts: false })`. The
524
+ * skillless variant `terminal.script({ run, ... })` desugars to
525
+ * `acts.script({ ...opts, inheritsArtifacts: false })`.
526
+ */
527
+ export const terminal = Object.assign(terminalFn, { script: terminalScript });
package/startup.ts CHANGED
@@ -6,8 +6,10 @@
6
6
  */
7
7
 
8
8
  export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
9
- export { registerLifecycle } from "./lifecycle.js";
9
+ export { registerLifecycle } from "./events.js";
10
10
  export {
11
+ getBucketKindMappings,
12
+ registerBucketKindMapping,
11
13
  registerCompositionComparator,
12
14
  registerOutcomeDeriver,
13
15
  registerSkillContracts,
package/state/index.ts CHANGED
@@ -6,15 +6,17 @@
6
6
 
7
7
  export type {
8
8
  ClaimResult,
9
+ LoopCapRow,
9
10
  NamesIndex,
10
11
  RoutingDecision,
11
12
  RunSummary,
13
+ SessionRef,
12
14
  StageStatus,
13
15
  WorkflowHeader,
14
16
  WorkflowStage,
15
17
  } from "./state.js";
16
18
  export {
17
- addNameToIndex,
19
+ appendLoopCap,
18
20
  appendRoutingDecision,
19
21
  appendStage,
20
22
  claimName,
@@ -24,13 +26,18 @@ export {
24
26
  listRuns,
25
27
  namesFilePath,
26
28
  readAllStages,
29
+ readAllStagesForResume,
27
30
  readHeader,
28
31
  readLastStage,
32
+ readLoopCaps,
29
33
  readNamesIndex,
30
34
  readRoutingDecisions,
31
35
  rebuildIndex,
36
+ releaseName,
32
37
  resolveRun,
38
+ runFileFor,
33
39
  runsDir,
40
+ STATE_SCHEMA_VERSION,
34
41
  stateFilePath,
35
42
  VALID_NAME,
36
43
  writeHeader,