@juicesharp/rpiv-workflow 1.17.1 → 1.18.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.
@@ -343,50 +343,50 @@ edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) })
343
343
 
344
344
  ## Conditional routing
345
345
 
346
- ### gate
346
+ A conditional edge is an **`EdgeFn`**: a `(ctx) => string` predicate carrying a `.targets` array of every stage it can return. `.targets` is required — the validator and reachability BFS enumerate it — so you wrap a TS predicate rather than dropping a bare arrow into `edges`. Two wrappers:
347
347
 
348
- Conditional routing keyed on a numeric field in `output.data`. Branches evaluated against `Number(output.data[field])` in declaration order; first matching predicate wins. Last declared branch is the fallback when no predicate matches.
348
+ - **`defineRoute(targets, fn)`** — general. Arbitrary TS body, explicit `targets`. Use for strings, enums, multiple fields, ranges — anything.
349
+ - **`gate(field, branches)`** — terse convenience for one **numeric** field with threshold predicates; derives `.targets` from the branch keys. Not more powerful than `defineRoute`, just shorter for the numeric case.
350
+
351
+ ### gate (numeric field)
352
+
353
+ Branches evaluated against `Number(output.data[field])` in declaration order; first match wins, last branch is the fallback. Helpers (`gt`/`gte`/`lt`/`lte`/`eq`) take a `number` — non-numeric fields route with `defineRoute` instead.
349
354
 
350
355
  ```typescript
351
356
  import { gate, gt, eq } from "@juicesharp/rpiv-workflow";
352
357
 
353
358
  edges: {
354
359
  "code-review": gate("blockers_count", {
355
- revise: gt(0), // value > 0 → "revise"
356
- commit: eq(0), // value = 0 → "commit"
360
+ revise: gt(0), // > 0 → "revise"
361
+ commit: eq(0), // = 0 → "commit"; missing/NaN/< 0 falls to last
357
362
  })
358
363
  }
359
- // value < 0 → "commit" (no match, falls to last)
360
- // missing/NaN → "commit" (no match, falls to last)
361
364
  ```
362
365
 
363
- ### defineRoute
366
+ ### defineRoute (strings, enums, multi-field)
364
367
 
365
- Hand-rolled multi-branch routing. Returns an `EdgeFn` with `.targets` metadata for graph introspection. Auto-marks the route as reading `output.data` — pass `{ readsData: false }` for state-only routes.
368
+ The body is plain TS, so there is no separate string/enum helper — compare the field directly. Every value the body can return must appear in `targets`, or the validator flags the edge. Auto-marks the route as reading `output.data` (the source stage needs an `outputSchema`); pass `{ readsData: false }` for a state-only route.
366
369
 
367
370
  ```typescript
368
371
  import { defineRoute } from "@juicesharp/rpiv-workflow";
369
372
 
370
373
  edges: {
371
- "decide": defineRoute(
372
- ["fast-path", "slow-path"], // All possible returns (required)
373
- ({ output }) => {
374
- const data = output?.data as { complexity: string };
375
- return data?.complexity === "high" ? "slow-path" : "fast-path";
376
- },
377
- )
374
+ review: defineRoute(["commit", "revise", "escalate"], ({ output }) => {
375
+ const verdict = (output?.data as { verdict?: string })?.verdict;
376
+ if (verdict === "approve") return "commit";
377
+ if (verdict === "reject") return "escalate";
378
+ return "revise";
379
+ }),
378
380
  }
379
381
  ```
380
382
 
381
- ### Predicate helpers
383
+ ### Predicate helpers (numeric — for `gate`)
382
384
 
383
- | Helper | Returns true when |
384
- |--------|-------------------|
385
- | `gt(n)` | value > n |
386
- | `gte(n)` | value >= n |
387
- | `lt(n)` | value < n |
388
- | `lte(n)` | value <= n |
389
- | `eq(n)` | value === n |
385
+ | Helper | Returns true when | | Helper | Returns true when |
386
+ |--------|---|---|--------|---|
387
+ | `gt(n)` | value > n | | `lte(n)` | value <= n |
388
+ | `gte(n)` | value >= n | | `eq(n)` | value === n |
389
+ | `lt(n)` | value < n | | | |
390
390
 
391
391
  ## Outcomes
392
392
 
package/extension.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * rpiv-workflow — thin Pi extension entry. `package.json` `pi.extensions` points
3
+ * here, NOT at `./index.ts`: the barrel statically re-exports the whole runtime
4
+ * (~530ms) and would tax every session. This pulls only the two registrars
5
+ * (`/wf` registration is itself lazy); the barrel stays the embedder API surface.
6
+ */
7
+
8
+ import { registerWorkflowCommand } from "./command.js";
9
+ import { type DocsProtocolHost, registerDocsProtocol } from "./docs-protocol.js";
10
+ import type { WorkflowHost } from "./host.js";
11
+
12
+ /** Host ports the `default` needs; Pi's `ExtensionAPI` structurally satisfies both. */
13
+ type ExtensionHost = WorkflowHost & DocsProtocolHost;
14
+
15
+ export default function (host: ExtensionHost): void {
16
+ registerWorkflowCommand(host);
17
+ registerDocsProtocol(host);
18
+ }
package/fanout.ts CHANGED
@@ -11,18 +11,24 @@
11
11
  */
12
12
 
13
13
  import type { FanoutUnit } from "./api.js";
14
+ import { runIdentityOf } from "./audit.js";
14
15
  import { buildLifecycleContext, skillStageRef } from "./lifecycle.js";
15
16
  import { MSG_STAGE_COMPLETE, STATUS_FANOUT_UNIT, STATUS_KEY } from "./messages.js";
16
- import type { FanoutSession, RunContext, RunnerCtx } from "./types.js";
17
+ import type { FanoutSession, RunContext, WorkflowHostContext } from "./types.js";
17
18
 
18
19
  export interface FanoutDeps {
19
- runFanoutSession: (ctx: RunnerCtx, session: FanoutSession) => Promise<void>;
20
+ runFanoutSession: (ctx: WorkflowHostContext, session: FanoutSession) => Promise<void>;
20
21
  /**
21
22
  * Resume the chain after the fanout node's units finish. Receives the
22
23
  * fanout node's name so the routing layer can look up the outgoing
23
24
  * edge from it.
24
25
  */
25
- advanceAfter: (curCtx: RunnerCtx, completedName: string, completedIdx: number, run: RunContext) => Promise<void>;
26
+ advanceAfter: (
27
+ curCtx: WorkflowHostContext,
28
+ completedName: string,
29
+ completedIdx: number,
30
+ run: RunContext,
31
+ ) => Promise<void>;
26
32
  }
27
33
 
28
34
  /**
@@ -41,7 +47,7 @@ export interface FanoutDeps {
41
47
  * session to run — the continuation-style self-call increments it.
42
48
  */
43
49
  export async function runFanout(
44
- curCtx: RunnerCtx,
50
+ curCtx: WorkflowHostContext,
45
51
  stageIdx: number,
46
52
  currentName: string,
47
53
  skill: string,
@@ -86,7 +92,7 @@ export async function runFanout(
86
92
  stageName: currentName,
87
93
  skill,
88
94
  lifecycle: run.lifecycle,
89
- runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
95
+ runIdentity: runIdentityOf(run),
90
96
  unitIndex: p,
91
97
  label: unit.label,
92
98
  id: unit.id,
package/host.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * interfaces.
11
11
  *
12
12
  * - `WorkflowHost` — registry-level host (default-export ctor + continue-policy sender).
13
- * - `WorkflowContext` — per-command ctx passed into `runWorkflow`, also the
13
+ * - `WorkflowHostContext` — per-command ctx passed into `runWorkflow`, also the
14
14
  * replacement ctx delivered to `newSession`'s `withSession`
15
15
  * callback. `sendUserMessage` is optional at the type
16
16
  * level (the outer command ctx may not carry one) but
@@ -36,7 +36,7 @@ export interface WorkflowHost {
36
36
  name: string,
37
37
  options: {
38
38
  description?: string;
39
- handler: (args: string, ctx: WorkflowContext) => Promise<void>;
39
+ handler: (args: string, ctx: WorkflowHostContext) => Promise<void>;
40
40
  },
41
41
  ): void;
42
42
  /**
@@ -60,13 +60,15 @@ export interface WorkflowHost {
60
60
  * Exhaustive list of members the runtime touches — adding any reach
61
61
  * outside this list is a port-widening decision, not an oversight.
62
62
  *
63
- * `sendUserMessage` is declared optional because the outer command ctx
64
- * Pi delivers to a `/wf` handler does not carry one — only the
65
- * replacement ctx inside `newSession`'s `withSession` callback does. The
66
- * runtime guarantees it is present in that callback; callers outside
67
- * `withSession` must not rely on it.
63
+ * `sendUserMessage` is declared optional HERE because the outer command
64
+ * ctx Pi delivers to a `/wf` handler does not carry one. The replacement
65
+ * ctx delivered inside `newSession`'s `withSession` callback always does
66
+ * — that stronger guarantee is modelled by the `WorkflowSessionContext`
67
+ * subtype below, which `withSession` delivers. Code holding a bare
68
+ * `WorkflowHostContext` (the workflow-start path before any session
69
+ * opens) must still null-check before calling.
68
70
  */
69
- export interface WorkflowContext {
71
+ export interface WorkflowHostContext {
70
72
  cwd: string;
71
73
  hasUI: boolean;
72
74
  ui: {
@@ -76,7 +78,6 @@ export interface WorkflowContext {
76
78
  sessionManager: {
77
79
  getBranch(): unknown;
78
80
  };
79
- isIdle(): boolean;
80
81
  waitForIdle(): Promise<void>;
81
82
  /**
82
83
  * Open a fresh session and run `withSession` on the replacement ctx.
@@ -86,12 +87,24 @@ export interface WorkflowContext {
86
87
  * delivered to `withSession`.
87
88
  */
88
89
  newSession(options: {
89
- withSession: (replacement: WorkflowContext) => Promise<void>;
90
+ withSession: (replacement: WorkflowSessionContext) => Promise<void>;
90
91
  }): Promise<{ cancelled: boolean }>;
91
92
  /**
92
- * Present on the replacement ctx delivered inside `withSession`; not
93
- * present on the outer command ctx. The runtime narrows internally
94
- * before calling.
93
+ * Optional on the base port — only the outer command ctx lacks it.
94
+ * Inside a session use `WorkflowSessionContext`, where it is required.
95
95
  */
96
96
  sendUserMessage?(content: string): Promise<void>;
97
97
  }
98
+
99
+ /**
100
+ * The replacement ctx delivered to `newSession`'s `withSession` callback.
101
+ * Identical to `WorkflowHostContext` except `sendUserMessage` is
102
+ * GUARANTEED present — Pi always wires a sender into a freshly-opened
103
+ * session. Narrowing the optional to required here turns what used to be
104
+ * a runtime `if (!ctx.sendUserMessage) throw` guard into a compile-time
105
+ * fact for every caller operating inside a session. `host.test.ts`
106
+ * asserts Pi's internal replacement ctx still satisfies this.
107
+ */
108
+ export interface WorkflowSessionContext extends WorkflowHostContext {
109
+ sendUserMessage(content: string): Promise<void>;
110
+ }
package/index.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  /**
2
- * rpiv-workflow — Pi extension entry point.
3
- *
4
- * Registers the `/wf` slash command and (optionally) exposes the workflow
5
- * runtime as a programmatic API for sibling packages that want to
6
- * contribute built-in workflows via `registerBuiltIns(...)`.
2
+ * rpiv-workflow — public API barrel for embedders. The Pi extension `default`
3
+ * entry lives in the thin `./extension.ts` (not here); startup-time siblings
4
+ * should import the runner-free `@juicesharp/rpiv-workflow/registration` entry.
7
5
  *
8
6
  * Skill-agnostic: the runner sends `/skill:<name>` via Pi's native skill
9
7
  * dispatch — workflows can name any skill installed in Pi's search path
@@ -17,6 +15,7 @@
17
15
  * 1. Authoring DSL — `./api.js`, `./predicates.js`, `./typebox-adapter.js`
18
16
  * What a `workflows.config.ts` author imports to declare a workflow:
19
17
  * `defineWorkflow`, `produces`, `acts`, `terminal`, `defineRoute`, `gate`,
18
+ * `STOP` (terminal-edge sentinel; `"stop"` literal also valid),
20
19
  * `Workflow`, `StageDef`, `EdgeFn`, `EdgeTarget`, `EdgeContext`,
21
20
  * `StageSchema`, `StageKind`, `SessionPolicy`, `OutputSpec`,
22
21
  * `READS_DATA`, the runtime-mirror `*_VALUES` arrays, the
@@ -24,9 +23,14 @@
24
23
  * (the TypeBox adapter).
25
24
  *
26
25
  * 2. Runner (programmatic embedders) — `./runner/index.js`, `./host.js`
27
- * Drive a workflow from outside `/wf`: `runWorkflow`,
28
- * `RunWorkflowOptions`, `RunWorkflowResult`. Embedders type their
29
- * host handles against `WorkflowHost` / `WorkflowContext` (the host
26
+ * Drive a workflow from outside `/wf`: `runWorkflow` (+ the by-name
27
+ * sugar `runWorkflowByName`) and `resumeWorkflow` (+ the by-run-id
28
+ * sugar `resumeWorkflowByRunId`), with `RunWorkflowOptions`,
29
+ * `RunWorkflowByNameOptions`, `ResumeWorkflowOptions`,
30
+ * `ResumeWorkflowByRunIdOptions`, and the shared `RunWorkflowResult`.
31
+ * Every options bag accepts an optional `signal: AbortSignal` for
32
+ * between-stage cooperative cancellation. Embedders type their host
33
+ * handles against `WorkflowHost` / `WorkflowHostContext` (the host
30
34
  * ports) — Pi's `ExtensionAPI` / `ExtensionCommandContext` /
31
35
  * `ReplacedSessionContext` structurally satisfy them, so the
32
36
  * values pass through without casting.
@@ -77,7 +81,8 @@
77
81
  *
78
82
  * 8. Persistence (low-level — JSONL inspect) — `./state/index.js`
79
83
  * Read past runs at `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`:
80
- * `listRuns`, `readHeader`, `readLastStage`, `listArtifacts`,
84
+ * `listRuns`, `readHeader`, `resolveRun` (run-id → header; today an
85
+ * alias of `readHeader`), `readLastStage`, `listArtifacts`,
81
86
  * `stateFilePath`, `runsDir`, `RunSummary`,
82
87
  * `WorkflowHeader`, `WorkflowStage`. `recordStage` lives on
83
88
  * `@juicesharp/rpiv-workflow/internal` (test-only — rpiv-pi's
@@ -97,12 +102,15 @@
97
102
  * workflow-owned port in `./host.js`:
98
103
  *
99
104
  * • `WorkflowHost` — registry-level (default export + continue sends)
100
- * • `WorkflowContext` — per-command ctx for `runWorkflow`; also the
101
- * replacement ctx delivered to `newSession`'s
102
- * `withSession` callback. `sendUserMessage` is
103
- * optional at the type level (the outer command
104
- * ctx omits it); the runtime guarantees it is
105
- * present inside `withSession`.
105
+ * • `WorkflowHostContext` — per-command ctx for `runWorkflow`; also the
106
+ * base shape of the replacement ctx delivered to
107
+ * `newSession`'s `withSession` callback.
108
+ * `sendUserMessage` is optional at the type level
109
+ * (the outer command ctx omits it); the runtime
110
+ * guarantees it is present inside `withSession`.
111
+ * • `WorkflowSessionContext` — the narrower subtype delivered inside
112
+ * `withSession`, where `sendUserMessage` is
113
+ * GUARANTEED present (optional → required).
106
114
  *
107
115
  * Pi's `ExtensionAPI` / `ExtensionCommandContext` are structurally
108
116
  * compatible with these ports — embedders pass their existing Pi handles
@@ -118,125 +126,23 @@
118
126
  * if Pi's types drift below the port's required shape.
119
127
  */
120
128
 
121
- import { registerWorkflowCommand } from "./command.js";
122
- import { type DocsProtocolHost, registerDocsProtocol } from "./docs-protocol.js";
123
- import type { WorkflowHost } from "./host.js";
129
+ // Runner-free surface (DSL, registrars, loader, outcomes, …) lives in
130
+ // `./registration.js`; startup-time siblings import that to skip the ~530ms
131
+ // engine. This entry layers the runner on top for embedders.
132
+ export * from "./registration.js";
124
133
 
134
+ // The execution engine — the only re-export unique to this entry.
125
135
  export {
126
- type ActsScriptFn,
127
- acts,
128
- type DefineRouteOptions,
129
- defineRoute,
130
- defineWorkflow,
131
- type EdgeContext,
132
- type EdgeFn,
133
- type EdgeTarget,
134
- type FanoutContext,
135
- type FanoutFn,
136
- type FanoutUnit,
137
- gate,
138
- type IterateContext,
139
- type IterateFn,
140
- type IterateUnit,
141
- marksReadsData,
142
- ON_INVALID_VALUES,
143
- type OnInvalid,
144
- type ProducesScriptFn,
145
- type PromptFn,
146
- produces,
147
- READS_DATA,
148
- type ScriptContext,
149
- SESSION_POLICIES,
150
- type SessionPolicy,
151
- STAGE_KINDS,
152
- type StageDef,
153
- type StageKind,
154
- type StageSchema,
155
- terminal,
156
- type Workflow,
157
- } from "./api.js";
158
- export { registerBuiltIns } from "./built-ins.js";
159
- export {
160
- type Artifact,
161
- type ArtifactHandle,
162
- fs,
163
- handleToString,
164
- inline,
165
- opaque,
166
- url,
167
- } from "./handle.js";
168
- export type { WorkflowContext, WorkflowHost } from "./host.js";
169
- export { type LifecycleContext, type LifecycleListeners, registerLifecycle, type StageRef } from "./lifecycle.js";
170
- export type { ConfigLayer, Issue, LoadedWorkflows, LoadIssue, OverlayPaths } from "./load/index.js";
171
- export { aliasSkills, loadWorkflows, projectOverlayPaths, userOverlayPaths } from "./load/index.js";
172
- export {
173
- type DirectoryPathCollectorOpts,
174
- directoryPathCollector,
175
- type GitCommitData,
176
- type GitHeadSnapshot,
177
- gitCommitCollector,
178
- gitCommitOutcome,
179
- gitCommitParser,
180
- gitHeadSnapshot,
181
- jsonBodyParser,
182
- noopCollector,
183
- sideEffectOutcome,
184
- type ToolCall,
185
- type ToolCallCollectorOpts,
186
- type TranscriptPathCollectorOpts,
187
- toolCallCollector,
188
- transcriptPathCollector,
189
- type UrlCollectorOpts,
190
- unionCollectors,
191
- urlCollector,
192
- type WorkspaceDiffCollectorOpts,
193
- type WorkspaceDiffSnapshot,
194
- workspaceDiffCollector,
195
- } from "./outcomes/index.js";
196
- export type {
197
- ArtifactCollector,
198
- ArtifactParser,
199
- CollectCtx,
200
- CollectResult,
201
- Output,
202
- OutputMeta,
203
- OutputSpec,
204
- ParseCtx,
205
- ParseResult,
206
- SnapshotCtx,
207
- SnapshotFn,
208
- } from "./output.js";
209
- export { defineCollector, defineParser } from "./output-spec.js";
210
- export { eq, gt, gte, lt, lte, type Predicate } from "./predicates.js";
211
- export { type RunWorkflowOptions, type RunWorkflowResult, runWorkflow } from "./runner/index.js";
212
- export {
213
- listArtifacts,
214
- listRuns,
215
- type RunSummary,
216
- readHeader,
217
- readLastStage,
218
- runsDir,
219
- stateFilePath,
220
- type WorkflowHeader,
221
- type WorkflowStage,
222
- } from "./state/index.js";
223
- export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
224
- export { typeboxSchema } from "./typebox-adapter.js";
225
- export type { RunState } from "./types.js";
226
- export { type SchemaValidationFailure, validateOutputData } from "./validate-output.js";
227
- export { validateWorkflow, type WorkflowValidationIssue } from "./validate-workflow.js";
228
-
229
- /**
230
- * Local intersection of the two host ports this extension's `default`
231
- * function needs. `WorkflowHost` covers the workflow-command surface;
232
- * `DocsProtocolHost` covers the `on("before_agent_start", ...)` hook used
233
- * to prepend the docs-protocol block. Pi's `ExtensionAPI` structurally
234
- * satisfies both; programmatic embedders keep using the narrower
235
- * `WorkflowHost` port, so this alias stays local — not re-exported.
236
- */
237
- type ExtensionHost = WorkflowHost & DocsProtocolHost;
136
+ type ResumeWorkflowByRunIdOptions,
137
+ type ResumeWorkflowOptions,
138
+ type RunWorkflowByNameOptions,
139
+ type RunWorkflowOptions,
140
+ type RunWorkflowResult,
141
+ resumeWorkflow,
142
+ resumeWorkflowByRunId,
143
+ runWorkflow,
144
+ runWorkflowByName,
145
+ } from "./runner/index.js";
238
146
 
239
- export default function (host: ExtensionHost): void {
240
- registerWorkflowCommand(host);
241
- registerDocsProtocol(host);
242
- }
147
+ // NOTE: the Pi extension `default` entry is `./extension.ts`, not this barrel,
148
+ // so loading the extension doesn't evaluate the runtime re-exports above.
package/internal-utils.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  import { isAbsolute, join } from "node:path";
10
10
  import type { StageDef } from "./api.js";
11
11
  import type { Artifact } from "./handle.js";
12
+ import type { Output } from "./output.js";
12
13
  import type { RunState } from "./types.js";
13
14
 
14
15
  /** Exhaustiveness guard for discriminated-union switches. */
@@ -58,6 +59,40 @@ export async function withTimeout<T>(promise: Promise<T>, ms: number, message: s
58
59
  }
59
60
  }
60
61
 
62
+ /**
63
+ * The single authority for "a completed produces stage mutates the rolling
64
+ * artifact state." Called by the live skill path (sessions/sessions.ts), the
65
+ * live script path (runner/script-stage.ts), and state reconstruction
66
+ * (runner/resume.ts) — keeping all three in lockstep (parity-tested).
67
+ *
68
+ * Scope: primary slot + named-publish registry ONLY. `state.output` and
69
+ * `state.stagesCompleted` stay at call sites — `state.output` lives in the
70
+ * shared, gated `tryRecordStage` (also serving fanout, which never advances
71
+ * the primary), so folding it here would couple fanout to the produces rule.
72
+ *
73
+ * - kind "produces" → first artifact wins the rolling slot; the
74
+ * full Output appends onto state.named[key].
75
+ * - inheritsArtifacts === false → clear the slot (terminal()).
76
+ * - other side-effect → leave the slot untouched.
77
+ */
78
+ export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
79
+ if (def.kind === "produces") {
80
+ const next = output.artifacts[0];
81
+ if (next) state.primaryArtifact = next;
82
+ const key = resolvePublishName(def, stageName);
83
+ let slot = state.named[key];
84
+ if (!slot) {
85
+ slot = [];
86
+ state.named[key] = slot;
87
+ }
88
+ slot.push(output);
89
+ return;
90
+ }
91
+ if (def.inheritsArtifacts === false) {
92
+ state.primaryArtifact = undefined;
93
+ }
94
+ }
95
+
61
96
  /**
62
97
  * Resolve `p` against `cwd`. Returns `p` unchanged if it is already absolute;
63
98
  * otherwise joins `cwd + p` with the platform path separator. Uses
package/internal.ts CHANGED
@@ -22,6 +22,6 @@
22
22
  */
23
23
 
24
24
  export { recordStage } from "./audit.js";
25
- export { __resetBuiltIns, getBuiltIns } from "./built-ins.js";
25
+ export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins.js";
26
26
  export { __resetLifecycleRegistry } from "./lifecycle.js";
27
27
  export { __resetLoadCache } from "./load/cache.js";
package/iterate.ts CHANGED
@@ -15,14 +15,21 @@
15
15
  * terminator, and `run.maxIterations` (the backstop for a generator that never
16
16
  * returns null). No markdown regex, no per-convention counter — rpiv-workflow
17
17
  * stays convention-agnostic; the `IterateFn` body owns the convention.
18
+ *
19
+ * Resume contract: `resumeWorkflow` re-enters this pull loop at the next
20
+ * not-yet-completed unit by feeding `runIterate` the reconstructed entry artifact
21
+ * + accumulated prefix. That REQUIRES the `IterateFn` to be deterministic w.r.t.
22
+ * its entry artifact + accumulated outputs — resume guards the one checkable
23
+ * boundary (the re-pulled next unit) and trusts the completed prefix by contract.
24
+ * See `runner/resume-iterate.ts`.
18
25
  */
19
26
 
20
27
  import type { StageDef } from "./api.js";
21
- import { iterateRowStage } from "./audit.js";
28
+ import { iterateRowStage, runIdentityOf } from "./audit.js";
22
29
  import type { Artifact } from "./handle.js";
23
30
  import { MSG_ITERATE_ZERO_UNITS, MSG_STAGE_COMPLETE, STATUS_ITERATE_UNIT, STATUS_KEY } from "./messages.js";
24
31
  import type { Output } from "./output.js";
25
- import type { RunContext, RunnerCtx, StageSession } from "./types.js";
32
+ import type { RunContext, StageSession, WorkflowHostContext } from "./types.js";
26
33
 
27
34
  export interface IterateDeps {
28
35
  /**
@@ -30,18 +37,23 @@ export interface IterateDeps {
30
37
  * validate → record → accumulate). The same `runStageSession` a normal
31
38
  * `produces` stage uses — iterate adds no bespoke session machinery.
32
39
  */
33
- runStageSession: (ctx: RunnerCtx, s: StageSession) => Promise<void>;
40
+ runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
34
41
  /**
35
42
  * Resume the chain after the iterate node's units finish (generator
36
43
  * returned null). Receives the iterate node's REAL name so routing looks up
37
44
  * the outgoing edge from it — the per-unit audit decoration never leaks
38
45
  * into routing.
39
46
  */
40
- advanceAfter: (curCtx: RunnerCtx, completedName: string, completedIdx: number, run: RunContext) => Promise<void>;
47
+ advanceAfter: (
48
+ curCtx: WorkflowHostContext,
49
+ completedName: string,
50
+ completedIdx: number,
51
+ run: RunContext,
52
+ ) => Promise<void>;
41
53
  /** Re-capture the outcome's pre-stage snapshot per unit (each unit is its own produces pass). */
42
54
  captureSnapshot: (def: StageDef, idx: number, run: RunContext) => Promise<unknown>;
43
55
  /** Record the terminal failure when the `maxIterations` backstop trips. */
44
- haltIterations: (curCtx: RunnerCtx, run: RunContext, stageName: string, count: number) => Promise<void>;
56
+ haltIterations: (curCtx: WorkflowHostContext, run: RunContext, stageName: string, count: number) => Promise<void>;
45
57
  }
46
58
 
47
59
  /**
@@ -63,7 +75,7 @@ export interface IterateDeps {
63
75
  * `onSuccess`).
64
76
  */
65
77
  export async function runIterate(
66
- curCtx: RunnerCtx,
78
+ curCtx: WorkflowHostContext,
67
79
  stageIdx: number,
68
80
  currentName: string,
69
81
  skill: string,
@@ -115,7 +127,7 @@ export async function runIterate(
115
127
  stageName: iterateRowStage(currentName, unit.id ?? unit.label),
116
128
  skill,
117
129
  lifecycle: run.lifecycle,
118
- runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
130
+ runIdentity: runIdentityOf(run),
119
131
  stage: def,
120
132
  stageIndex: stageIdx,
121
133
  snapshot,
@@ -123,7 +135,7 @@ export async function runIterate(
123
135
  onFailure: undefined,
124
136
  onSuccess: (freshCtx) => {
125
137
  // `tryRecordStage` set `state.output` to this unit's validated Output
126
- // (and `maybeAdvancePrimary` already pushed it onto state.named) before
138
+ // (and `applyCompletedStage` already pushed it onto state.named) before
127
139
  // onSuccess fired. Thread it into `accumulated` for the next pull.
128
140
  const produced = run.state.output!;
129
141
  return runIterate(
package/lifecycle.ts CHANGED
@@ -148,7 +148,7 @@ export interface LifecycleListeners {
148
148
  // Internal — dispatcher (consumed by the runner; not exported publicly)
149
149
  // ---------------------------------------------------------------------------
150
150
 
151
- /** Subset of `WorkflowContext` the dispatcher needs for throw-safe logging. */
151
+ /** Subset of `WorkflowHostContext` the dispatcher needs for throw-safe logging. */
152
152
  export interface DispatchHost {
153
153
  ui: { notify(message: string, level?: "info" | "warning" | "error"): void };
154
154
  }
package/load/index.ts CHANGED
@@ -53,7 +53,7 @@
53
53
  import { existsSync, readdirSync } from "node:fs";
54
54
  import { dirname, join } from "node:path";
55
55
  import type { Workflow } from "../api.js";
56
- import { getBuiltIns } from "../built-ins.js";
56
+ import { flushBuiltInProviders, getBuiltIns } from "../built-ins.js";
57
57
  import type { ConfigLayer } from "../layers.js";
58
58
  import { LEGACY_OVERLAY_NOTICE, LEGACY_RUNS_NOTICE, LEGACY_USER_CONFIG_NOTICE } from "../messages.js";
59
59
  import { validateWorkflow, type WorkflowValidationIssue } from "../validate-workflow.js";
@@ -128,6 +128,10 @@ export function findWorkflow(loaded: LoadedWorkflows, name: string): Workflow |
128
128
  * resolved set. Never throws — load + validation errors flow through `issues`.
129
129
  */
130
130
  export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
131
+ // Flush lazy built-in providers before reading the registry — lets siblings
132
+ // defer constructing definitions to first `/wf` (the earliest reader).
133
+ await flushBuiltInProviders();
134
+
131
135
  const acc: LoadAccumulator = {
132
136
  issues: [],
133
137
  workflowMap: new Map(),
package/messages.ts CHANGED
@@ -44,6 +44,10 @@ export const ERR_STAGE_NO_RESPONSE = (skill: string) => `${skill} produced no as
44
44
  export const MSG_WORKFLOW_COMPLETE = (stages: number) => `rpiv: workflow complete (${stages} stages)`;
45
45
  export const MSG_WORKFLOW_CANCELLED = "rpiv: workflow cancelled";
46
46
 
47
+ // Programmatic abort via RunWorkflowOptions.signal — checked between stages.
48
+ export const MSG_WORKFLOW_ABORTED = "rpiv: workflow aborted";
49
+ export const ERR_WORKFLOW_ABORTED = (stage: string) => `workflow aborted before stage "${stage}" (signal)`;
50
+
47
51
  export const MSG_VALIDATION_RETRY = (skill: string, attempt: number) =>
48
52
  `rpiv: ${skill} output validation failed — asking agent to fix (attempt ${attempt})`;
49
53
  export const MSG_VALIDATION_EXHAUSTED = (skill: string) => `rpiv: ${skill} output validation exhausted retries`;
@@ -180,6 +184,36 @@ export const MSG_SCRIPT_THREW = (stage: string, reason: string) =>
180
184
  `✗ ${stage} script threw — stopping workflow: ${reason}`;
181
185
  export const ERR_SCRIPT_THREW = (stage: string, reason: string) => `${stage} script threw: ${reason}`;
182
186
 
187
+ // ---------------------------------------------------------------------------
188
+ // Resume-refusal messages — reconstruct refusals returned in the
189
+ // RunWorkflowResult envelope (the caller notifies; no-JSONL → no machinery row)
190
+ // ---------------------------------------------------------------------------
191
+
192
+ export const ERR_RESUME_NO_ROWS = (runId: string) => `rpiv: run ${runId} has no recorded stages — nothing to resume`;
193
+ export const ERR_RESUME_STAGE_GONE = (stage: string, workflow: string) =>
194
+ `rpiv: cannot resume — stage "${stage}" from the run no longer exists in workflow "${workflow}" ` +
195
+ `(renamed or removed)`;
196
+ export const ERR_RESUME_FANOUT_MISMATCH = (stage: string) =>
197
+ `rpiv: cannot resume — fanout stage "${stage}" recomputed a different unit list than the run recorded ` +
198
+ `(the FanoutFn must be deterministic w.r.t. its entry artifact; resume refuses rather than re-run the wrong units)`;
199
+ export const MSG_RESUME_FANOUT_MISMATCH = (stage: string) =>
200
+ `rpiv: fanout "${stage}" changed on resume — cannot safely continue`;
201
+ export const ERR_RESUME_ITERATE_MISMATCH = (stage: string) =>
202
+ `rpiv: cannot resume — iterate stage "${stage}" recomputed a different unit than the run recorded at the resume point ` +
203
+ `(the IterateFn must be deterministic w.r.t. its entry artifact + accumulated outputs; resume refuses rather than re-run the wrong unit)`;
204
+ export const MSG_RESUME_ITERATE_MISMATCH = (stage: string) =>
205
+ `rpiv: iterate "${stage}" changed on resume — cannot safely continue`;
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // Resume-refusal messages — resumeWorkflowByRef pre-resume guards (resolve →
209
+ // load-gate → find); returned in the envelope before resumeWorkflow is reached
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export const MSG_RESUME_USAGE = "rpiv: usage — /wf @<run-id>";
213
+ export const MSG_RUN_NOT_FOUND = (ref: string) => `rpiv: no run found for "${ref}"`;
214
+ export const MSG_RESUME_WORKFLOW_GONE = (workflow: string, ref: string) =>
215
+ `rpiv: run "${ref}" used workflow "${workflow}", which is no longer registered`;
216
+
183
217
  // ---------------------------------------------------------------------------
184
218
  // /wf command shell — notify-only (never lands in state.error; ERR_ reserved)
185
219
  // ---------------------------------------------------------------------------