@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.
package/README.md CHANGED
@@ -129,7 +129,7 @@ edges: { "code-review": gate("blockers_count", { revise: gt(0), commit: eq(0) })
129
129
 
130
130
  Branches are evaluated against `Number(output.data[field])` in declaration order; the first matching predicate wins, and the last declared branch is the fallback when no predicate matches (so missing or non-numeric fields route to the last branch).
131
131
 
132
- Hand-rolled routes use `defineRoute(targets, fn, opts?)` — by default `opts.readsData` is `true` (reads `output.data`, requires the source stage to declare an `outputSchema`); pass `{ readsData: false }` for a route that consults only `state` / `output.meta`.
132
+ `gate` is the numeric convenience only. String/enum, multi-field, or computed routing uses `defineRoute(targets, fn, opts?)` — the body is plain TS (e.g. `output.data.verdict === "approve" ? "commit" : "revise"`), so there's no separate string helper. By default `opts.readsData` is `true` (reads `output.data`, requires the source stage to declare an `outputSchema`); pass `{ readsData: false }` for a route that consults only `state` / `output.meta`.
133
133
 
134
134
  ## Script stages (no Pi session)
135
135
 
@@ -250,7 +250,7 @@ export default function (host: WorkflowHost): void {
250
250
  }
251
251
  ```
252
252
 
253
- Every fired event walks the registry in registration order, then the per-call bundle (if any) the embedder passed to `runWorkflow({ lifecycle })`. Multiple bundles coexist; one bundle throwing does not affect siblings or halt the run (throws are caught and logged via `ctx.ui.notify(..., "warning")`).
253
+ Every fired event walks the registry in registration order, then the per-call bundle (if any) the embedder passed to `runWorkflow(ctx, { lifecycle })`. Multiple bundles coexist; one bundle throwing does not affect siblings or halt the run (throws are caught and logged via `ctx.ui.notify(..., "warning")`).
254
254
 
255
255
  The registry is anchored on `Symbol.for("@juicesharp/rpiv-workflow:lifecycle")`, mirroring the `registerBuiltIns` pattern, so cross-package module resolution still shares one slot. Snapshot semantics: each event observes the registry as it stands at that instant — a registration made mid-event applies to subsequent events, not the in-flight one.
256
256
 
@@ -259,22 +259,23 @@ The registry is anchored on `Symbol.for("@juicesharp/rpiv-workflow:lifecycle")`,
259
259
  ## Host boundary
260
260
 
261
261
  `rpiv-workflow`'s public type surface names **zero** `@earendil-works/pi-coding-agent`
262
- types. The runtime declares two workflow-owned port interfaces in
262
+ types. The runtime declares three workflow-owned port interfaces in
263
263
  `./host.js`:
264
264
 
265
265
  - `WorkflowHost` — registry-level host (default export, continue-policy
266
266
  sends, skill-registration preflight).
267
- - `WorkflowContext` — per-command ctx passed to `runWorkflow`; also the
268
- replacement ctx delivered to `newSession`'s `withSession` callback.
269
- `sendUserMessage` is optional at the type level (the outer command ctx
270
- Pi delivers to `/wf` doesn't carry one) — the runtime guarantees it is
271
- present inside `withSession`.
267
+ - `WorkflowHostContext` — per-command ctx passed to `runWorkflow`; also the
268
+ base shape for the replacement ctx delivered to `newSession`'s
269
+ `withSession` callback. `sendUserMessage` is optional at this level (the
270
+ outer command ctx Pi delivers to `/wf` doesn't carry one).
271
+ - `WorkflowSessionContext` — the narrower subtype delivered inside
272
+ `withSession`, where `sendUserMessage` is guaranteed present.
272
273
 
273
274
  Pi's `ExtensionAPI` / `ExtensionCommandContext` / `ReplacedSessionContext`
274
275
  structurally satisfy these ports, so existing embedders pass their Pi
275
276
  handles through unchanged. A
276
277
  compile-time tripwire (`host.test.ts`) fails immediately if Pi's API ever
277
- drifts below the port shape. A future non-Pi host implements the three
278
+ drifts below the port shapes. A future non-Pi host implements the three
278
279
  port interfaces and drives the runtime without any pi-coding-agent
279
280
  dependency.
280
281
 
@@ -285,7 +286,7 @@ Embedders drive workflows from outside `/wf`:
285
286
  ```ts
286
287
  import { runWorkflow } from "@juicesharp/rpiv-workflow";
287
288
 
288
- const result = await runWorkflow({
289
+ const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
289
290
  workflow: myFlow,
290
291
  input: "task description",
291
292
  host: piHost, // any WorkflowHost-shaped value
@@ -294,6 +295,50 @@ const result = await runWorkflow({
294
295
 
295
296
  Returns `{ runId, stagesCompleted, success }`. Past-run inspection uses `listRuns(cwd)` / `readHeader` / `readLastStage` / `listArtifacts`.
296
297
 
298
+ ### By name
299
+
300
+ For the common "just run this workflow by name" case, `runWorkflowByName` folds the `loadWorkflows` → `findWorkflow` → `runWorkflow` dance into one call:
301
+
302
+ ```ts
303
+ import { runWorkflowByName } from "@juicesharp/rpiv-workflow";
304
+
305
+ const result = await runWorkflowByName(ctx, "research", "add dark mode", { host: piHost });
306
+ if (!result.success) ctx.ui.notify(result.error ?? "workflow failed", "error");
307
+ ```
308
+
309
+ It never throws — every expected failure comes back in the same `RunWorkflowResult` envelope: error-severity load issues refuse the run, and an unknown name returns a failure envelope listing the available workflows. The fourth argument is `RunWorkflowByNameOptions` (`RunWorkflowOptions` minus `workflow`/`input`), so `host`, `trigger`, `lifecycle`, and the iteration caps thread through unchanged.
310
+
311
+ ### Resume by run-id
312
+
313
+ `resumeWorkflowByRunId` is the resume-side counterpart — it folds the `resolveRun` → `loadWorkflows` → `findWorkflow` → `resumeWorkflow` dance into one call keyed on the run-id (the `<run-id>` slug, exactly what `listRuns()` returns on `RunSummary.runId`). The run's header already names its workflow, so you supply only the id:
314
+
315
+ ```ts
316
+ import { resumeWorkflowByRunId, listRuns } from "@juicesharp/rpiv-workflow";
317
+
318
+ const [latest] = listRuns(ctx.cwd).filter((r) => !r.success); // e.g. a past failed run
319
+ if (latest) {
320
+ const result = await resumeWorkflowByRunId(ctx, latest.runId, { host: piHost });
321
+ if (!result.success) ctx.ui.notify(result.error ?? "resume failed", "error");
322
+ }
323
+ ```
324
+
325
+ Like `runWorkflowByName` it never throws: an unresolvable run-id, error-severity load issues, or a workflow that's no longer registered each come back as a failure envelope. The suffix is `ByRunId`, not `ByName`, on purpose — you resume one specific past *run* (a workflow has many), so the key is the run-id, not a workflow name. The third argument is `ResumeWorkflowByRunIdOptions` (`ResumeWorkflowOptions` minus `workflow`/`header`/`ref`).
326
+
327
+ > **Notify contract.** `resumeWorkflow` and `resumeWorkflowByRunId` are pure — they return envelopes and never notify, matching `runWorkflow`/`runWorkflowByName`. A no-JSONL refusal (bad run-id, load error, workflow gone, unreconstructable trail) carries **no `runId`** on the envelope; an in-run failure carries one and was already surfaced by the stage machinery's JSONL failure row. The `/wf` command uses exactly that `!result.runId` discriminator to notify the former once without double-notifying the latter.
328
+
329
+ ### Cancellation
330
+
331
+ Pass an `AbortSignal` to cancel a long run cooperatively:
332
+
333
+ ```ts
334
+ const controller = new AbortController();
335
+ const p = runWorkflow(ctx, { workflow, input, host: piHost, signal: controller.signal });
336
+ // …later, from a timeout / webhook / user action:
337
+ controller.abort();
338
+ ```
339
+
340
+ The runner checks the signal at the **between-stage** seam — before the start stage and before every routed next stage. On abort it records an `"aborted"` terminal row for the stage about to run and resolves with `{ success: false }`. It does **not** interrupt a stage already streaming (Pi owns the live session), so cancellation lands at the next stage boundary, not mid-stage. Threads through `runWorkflowByName` / `resumeWorkflowByRunId` unchanged.
341
+
297
342
  ### Lifecycle
298
343
 
299
344
  Pass `lifecycle` to observe stage progress in-process without re-reading the JSONL:
@@ -301,7 +346,7 @@ Pass `lifecycle` to observe stage progress in-process without re-reading the JSO
301
346
  ```ts
302
347
  import { runWorkflow } from "@juicesharp/rpiv-workflow";
303
348
 
304
- const result = await runWorkflow({
349
+ const result = await runWorkflow(ctx, {
305
350
  workflow: myFlow,
306
351
  input: "task description",
307
352
  host: piHost,
@@ -463,7 +508,3 @@ export default defineWorkflow({
463
508
  The contract is identical — author an async `~standard.validate` and the runner awaits it. A schema whose Promise never settles is bounded by the stage's `validateTimeoutMs` (default 5 min); a rejected Promise surfaces as a clean stage halt, attributed to the stage, with the same error class as a shape-failure halt. No opt-in flag, no parallel code path.
464
509
 
465
510
  > Keep validation separate from the collector + parser. The collector's job is "what did the agent produce?" (enumerate); the parser's job is "parse it into typed data" (shape). The validator's job is "is the result correct?" (check + verify). With async validators available you don't have to push I/O verification into a custom collector/parser — keep them pure and put correctness checks on `outputSchema`.
466
-
467
- ## Architecture
468
-
469
- See [`.rpiv/guidance/packages/rpiv-workflow/architecture.md`](../../.rpiv/guidance/packages/rpiv-workflow/architecture.md).
package/api.ts CHANGED
@@ -191,7 +191,7 @@ export type IterateUnit = FanoutUnit;
191
191
  * read-only state snapshot.
192
192
  *
193
193
  * Script stages cannot fanout, cannot use `sessionPolicy: "continue"`,
194
- * and do not receive a Pi `RunnerCtx` — they're pure TS calls.
194
+ * and do not receive a Pi `WorkflowHostContext` — they're pure TS calls.
195
195
  */
196
196
  export interface ScriptContext {
197
197
  cwd: string;
package/audit.ts CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  } from "./messages.js";
24
24
  import { appendStage, listArtifacts, type WorkflowStage } from "./state/index.js";
25
25
  import type { StopSignal } from "./transcript.js";
26
- import type { FanoutSession, RunnerCtx, RunState, SessionContext } from "./types.js";
26
+ import type { FanoutSession, RunContext, RunState, SessionContext, WorkflowHostContext } from "./types.js";
27
27
 
28
28
  /** Single source of ISO-8601 timestamps for audit rows + output meta. */
29
29
  export const nowIso = (): string => new Date().toISOString();
@@ -45,6 +45,41 @@ export type AuditCtx = Pick<
45
45
  isScript?: boolean;
46
46
  };
47
47
 
48
+ /**
49
+ * The read-only run identity (`workflow` name + `totalStages` + `trigger`)
50
+ * threaded onto every `SessionContext` and `AuditCtx`. Single source for the
51
+ * `runIdentity` sub-literal that session/audit constructions across the runner
52
+ * would otherwise re-spell by hand.
53
+ */
54
+ export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
55
+ return { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger };
56
+ }
57
+
58
+ /**
59
+ * Build the `AuditCtx` `recordTerminalFailure` needs for a stage failure that
60
+ * escaped a session (preflight halts, downstream throws, routing errors,
61
+ * resume-time refusals). One source for the shape so every halt path records
62
+ * a uniform row. `isScript: true` drops the `skill` field from the JSONL row
63
+ * and switches `onStageError` to `scriptStageRef`.
64
+ */
65
+ export function auditCtxFor(
66
+ run: RunContext,
67
+ stageName: string,
68
+ skill: string,
69
+ opts?: { isScript?: boolean },
70
+ ): AuditCtx {
71
+ return {
72
+ cwd: run.cwd,
73
+ runId: run.runId,
74
+ state: run.state,
75
+ stageName,
76
+ skill,
77
+ lifecycle: run.lifecycle,
78
+ runIdentity: runIdentityOf(run),
79
+ ...(opts?.isScript ? { isScript: true } : {}),
80
+ };
81
+ }
82
+
48
83
  /**
49
84
  * JSONL `WorkflowStage.stage` value for fanout-unit rows — built from
50
85
  * the parent stage's record key (`stageName`) suffixed with the
@@ -90,7 +125,7 @@ export function recordStage(
90
125
  }
91
126
 
92
127
  /** Surface every artifact recorded so far — recap on stage failure. */
93
- export function notifyPartialArtifacts(ctx: RunnerCtx, cwd: string, runId: string): void {
128
+ export function notifyPartialArtifacts(ctx: WorkflowHostContext, cwd: string, runId: string): void {
94
129
  const items = listArtifacts(cwd, runId);
95
130
  if (items.length === 0) return;
96
131
  const artifactList = items.map((i) => ` • ${i.stage}: ${handleToString(i.artifact.handle)}`).join("\n");
@@ -98,7 +133,7 @@ export function notifyPartialArtifacts(ctx: RunnerCtx, cwd: string, runId: strin
98
133
  }
99
134
 
100
135
  export async function recordTerminalFailure(
101
- ctx: RunnerCtx,
136
+ ctx: WorkflowHostContext,
102
137
  audit: AuditCtx,
103
138
  args: {
104
139
  status: "failed" | "aborted";
@@ -106,7 +141,7 @@ export async function recordTerminalFailure(
106
141
  notifyLevel: "warning" | "error";
107
142
  errMsg: string;
108
143
  },
109
- onFailure?: (ctx: RunnerCtx) => void,
144
+ onFailure?: (ctx: WorkflowHostContext) => void,
110
145
  ): Promise<void> {
111
146
  recordStage(
112
147
  audit.cwd,
@@ -154,11 +189,11 @@ export async function recordTerminalFailure(
154
189
  * and state.termination.error.
155
190
  */
156
191
  export async function recordStopFailure(
157
- ctx: RunnerCtx,
192
+ ctx: WorkflowHostContext,
158
193
  audit: AuditCtx,
159
194
  stop: Exclude<StopSignal, "stop">,
160
195
  errorMessage: string,
161
- onFailure?: (ctx: RunnerCtx) => void,
196
+ onFailure?: (ctx: WorkflowHostContext) => void,
162
197
  ): Promise<void> {
163
198
  await recordTerminalFailure(ctx, audit, stopFailureArgs(audit.skill, stop, errorMessage), onFailure);
164
199
  }
@@ -214,7 +249,7 @@ function stopFailureArgs(
214
249
  }
215
250
  }
216
251
 
217
- export function recordCancellation(ctx: RunnerCtx, audit: AuditCtx): void {
252
+ export function recordCancellation(ctx: WorkflowHostContext, audit: AuditCtx): void {
218
253
  recordStage(
219
254
  audit.cwd,
220
255
  audit.runId,
package/built-ins.ts CHANGED
@@ -23,6 +23,11 @@
23
23
  import type { Workflow } from "./api.js";
24
24
 
25
25
  const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-ins");
26
+ const PROVIDERS_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-providers");
27
+ const FLUSH_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-flush");
28
+
29
+ /** A lazy contributor of built-in workflows — run once by `flushBuiltInProviders`. */
30
+ type BuiltInsProvider = () => void | Promise<void>;
26
31
 
27
32
  type Global = Record<symbol, unknown>;
28
33
 
@@ -36,6 +41,18 @@ function getRegistry(): Workflow[] {
36
41
  return registry;
37
42
  }
38
43
 
44
+ // Provider list + flush latch use the same `Symbol.for` global-slot strategy as
45
+ // the registry, so a duplicate module load shares one process-wide state.
46
+ function getProviders(): BuiltInsProvider[] {
47
+ const g = globalThis as unknown as Global;
48
+ let providers = g[PROVIDERS_KEY] as BuiltInsProvider[] | undefined;
49
+ if (!providers) {
50
+ providers = [];
51
+ g[PROVIDERS_KEY] = providers;
52
+ }
53
+ return providers;
54
+ }
55
+
39
56
  /**
40
57
  * Register one or more workflows into the `built-in` layer. Idempotent on
41
58
  * `Workflow.name` — re-registering an existing name replaces the prior
@@ -51,15 +68,42 @@ export function registerBuiltIns(workflows: readonly Workflow[]): void {
51
68
  }
52
69
  }
53
70
 
71
+ /**
72
+ * Register a LAZY built-in provider. The thunk runs once on the first
73
+ * `flushBuiltInProviders()` (which `loadWorkflows` awaits), letting a sibling
74
+ * defer constructing its workflow definitions off startup and onto first `/wf`.
75
+ * Register before the first read — `/wf` is the earliest reader.
76
+ */
77
+ export function registerBuiltInsProvider(provider: BuiltInsProvider): void {
78
+ getProviders().push(provider);
79
+ }
80
+
81
+ /**
82
+ * Run all pending providers once, then memoize. Concurrency-safe (callers await
83
+ * the same promise; later calls are no-ops). Providers registered after the
84
+ * first flush won't run — acceptable, all register at extension load.
85
+ */
86
+ export function flushBuiltInProviders(): Promise<void> {
87
+ const g = globalThis as unknown as Global;
88
+ const existing = g[FLUSH_KEY] as Promise<void> | undefined;
89
+ if (existing) return existing;
90
+ const pending = getProviders().splice(0);
91
+ const flush = Promise.all(pending.map((p) => p())).then(() => undefined);
92
+ g[FLUSH_KEY] = flush;
93
+ return flush;
94
+ }
95
+
54
96
  /** Read-only view of the registry — consumed by `load.ts`. */
55
97
  export function getBuiltIns(): readonly Workflow[] {
56
98
  return getRegistry();
57
99
  }
58
100
 
59
101
  /**
60
- * Test reset. Wired into the repo-wide test setup so cross-test
61
- * registration leaks don't bias the next case.
102
+ * Test reset (wired into repo-wide setup). Clears the registry, pending lazy
103
+ * providers, and the flush latch so the next case starts clean.
62
104
  */
63
105
  export function __resetBuiltIns(): void {
64
106
  getRegistry().length = 0;
107
+ getProviders().length = 0;
108
+ (globalThis as unknown as Global)[FLUSH_KEY] = undefined;
65
109
  }
package/command-run.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * /wf run-path: parse → loadWorkflows → runWorkflow. Statically imports the
3
+ * heavy runtime (runner + loader); reached only via the dynamic import in
4
+ * `./command.ts`, so it evaluates lazily on first `/wf`, not at startup.
5
+ */
6
+
7
+ import { parseArgs } from "./command.js";
8
+ import type { WorkflowHost, WorkflowHostContext } from "./host.js";
9
+ import { renderConfigLayer } from "./layers.js";
10
+ import { findWorkflow, type Issue, loadWorkflows } from "./load/index.js";
11
+ import {
12
+ MSG_INTERACTIVE_ONLY,
13
+ MSG_LOAD_ABORTED,
14
+ MSG_NO_WORKFLOWS_REGISTERED,
15
+ MSG_RESUME_USAGE,
16
+ MSG_WORKFLOW_NOT_FOUND,
17
+ MSG_WORKFLOW_THREW,
18
+ } from "./messages.js";
19
+ import { formatWorkflowDetails, formatWorkflowList } from "./preview.js";
20
+ import { resumeWorkflowByRunId, runWorkflow } from "./runner/index.js";
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Orchestrator
24
+ // ---------------------------------------------------------------------------
25
+
26
+ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ctx: WorkflowHostContext): Promise<void> {
27
+ if (!ctx.hasUI) {
28
+ ctx.ui.notify(MSG_INTERACTIVE_ONLY, "error");
29
+ return;
30
+ }
31
+
32
+ const loaded = await loadWorkflows(ctx.cwd);
33
+ surfaceIssues(ctx, loaded.issues);
34
+
35
+ const workflowNames = new Set(loaded.workflows.map((w) => w.name));
36
+ const parsed = parseArgs(args, { workflowNames, default: loaded.default });
37
+
38
+ if (parsed.kind === "resume") {
39
+ await handleResume(host, ctx, parsed.ref);
40
+ return;
41
+ }
42
+
43
+ const { workflow: workflowName, input } = parsed;
44
+
45
+ if (!input) {
46
+ const trimmed = args.trim();
47
+ const previewing = trimmed.length > 0 && workflowNames.has(trimmed);
48
+ ctx.ui.notify(previewing ? formatWorkflowDetails(loaded, trimmed) : formatWorkflowList(loaded), "info");
49
+ return;
50
+ }
51
+
52
+ // Block execution on load errors — running a partially-loaded workflow set
53
+ // would silently mask the user's intent (e.g. their preferred workflow
54
+ // failed to import).
55
+ const errorCount = loaded.issues.filter((i) => i.severity === "error").length;
56
+ if (errorCount > 0) {
57
+ ctx.ui.notify(MSG_LOAD_ABORTED(errorCount), "error");
58
+ return;
59
+ }
60
+
61
+ // Standalone install: rpiv-workflow ships zero workflows; if nothing else
62
+ // registered one, there's nothing to run. parseArgs returns "" for the
63
+ // workflow name in this case (no default + first token didn't match) —
64
+ // surface the empty-registry verdict instead of falling through to a
65
+ // generic not-found notify.
66
+ if (!workflowName) {
67
+ ctx.ui.notify(MSG_NO_WORKFLOWS_REGISTERED, "error");
68
+ return;
69
+ }
70
+
71
+ const workflow = findWorkflow(loaded, workflowName);
72
+ if (!workflow) {
73
+ ctx.ui.notify(MSG_WORKFLOW_NOT_FOUND(workflowName), "error");
74
+ return;
75
+ }
76
+
77
+ // runWorkflow returns a result envelope rather than throwing — but a
78
+ // thrown predicate or invariant could still bubble. Catch so Pi's
79
+ // dispatcher doesn't print a raw stack.
80
+ try {
81
+ await runWorkflow(ctx, { workflow, input, host, trigger: { kind: "command", name: "wf" } });
82
+ } catch (e) {
83
+ const reason = e instanceof Error ? e.message : String(e);
84
+ ctx.ui.notify(MSG_WORKFLOW_THREW(reason), "error");
85
+ }
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // Resume handler
90
+ // ---------------------------------------------------------------------------
91
+
92
+ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, runId: string): Promise<void> {
93
+ if (!runId) {
94
+ ctx.ui.notify(MSG_RESUME_USAGE, "error");
95
+ return;
96
+ }
97
+ try {
98
+ const result = await resumeWorkflowByRunId(ctx, runId, { host });
99
+ // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
100
+ // load error, workflow gone, or an unreconstructable trail) — nothing else
101
+ // surfaces it, so notify here. An in-run failure carries a runId and was
102
+ // already notified by the stage machinery via its JSONL failure row;
103
+ // re-notifying would double up.
104
+ if (!result.success && result.runId === undefined && result.error) {
105
+ ctx.ui.notify(result.error, "error");
106
+ }
107
+ } catch (e) {
108
+ ctx.ui.notify(MSG_WORKFLOW_THREW(e instanceof Error ? e.message : String(e)), "error");
109
+ }
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Private helpers
114
+ // ---------------------------------------------------------------------------
115
+
116
+ /** Surface every load + validation issue as a notify, prefixed by severity. */
117
+ function surfaceIssues(ctx: WorkflowHostContext, issues: readonly Issue[]): void {
118
+ for (const issue of issues) {
119
+ const level: "warning" | "error" = issue.severity === "error" ? "error" : "warning";
120
+ ctx.ui.notify(formatIssue(issue), level);
121
+ }
122
+ }
123
+
124
+ function formatIssue(issue: Issue): string {
125
+ if (issue.kind === "load") {
126
+ const where = issue.path ? ` (${issue.path})` : "";
127
+ return `[${renderConfigLayer(issue.layer)} config${where}] ${issue.message}`;
128
+ }
129
+ const stageTag = issue.stage ? ` — stage "${issue.stage}"` : "";
130
+ const pathTag = issue.path ? ` (${issue.path})` : "";
131
+ return `[${renderConfigLayer(issue.layer)} config${pathTag}] workflow "${issue.workflow}"${stageTag}: ${issue.message}`;
132
+ }
package/command.ts CHANGED
@@ -1,18 +1,12 @@
1
- /** /wf slash command: parse → loadWorkflows → runWorkflow. */
1
+ /**
2
+ * /wf slash command registration — kept light. The heavy run-path (runner +
3
+ * loader, ~530ms) lives in `./command-run.js`, dynamically imported only when
4
+ * `/wf` is invoked, so registering the command costs nothing at startup.
5
+ * `parseArgs` stays here (pure, exported for tests).
6
+ */
2
7
 
3
- import type { WorkflowContext, WorkflowHost } from "./host.js";
4
- import { renderConfigLayer } from "./layers.js";
5
- import { findWorkflow, type Issue, loadWorkflows } from "./load/index.js";
6
- import {
7
- CMD_DESCRIPTION,
8
- MSG_INTERACTIVE_ONLY,
9
- MSG_LOAD_ABORTED,
10
- MSG_NO_WORKFLOWS_REGISTERED,
11
- MSG_WORKFLOW_NOT_FOUND,
12
- MSG_WORKFLOW_THREW,
13
- } from "./messages.js";
14
- import { formatWorkflowDetails, formatWorkflowList } from "./preview.js";
15
- import { runWorkflow } from "./runner/index.js";
8
+ import type { WorkflowHost, WorkflowHostContext } from "./host.js";
9
+ import { CMD_DESCRIPTION } from "./messages.js";
16
10
 
17
11
  // ---------------------------------------------------------------------------
18
12
  // Public entry
@@ -21,86 +15,43 @@ import { runWorkflow } from "./runner/index.js";
21
15
  export function registerWorkflowCommand(host: WorkflowHost): void {
22
16
  host.registerCommand("wf", {
23
17
  description: CMD_DESCRIPTION,
24
- handler: (args: string, ctx: WorkflowContext) => handleWorkflowCommand(host, args, ctx),
18
+ handler: async (args: string, ctx: WorkflowHostContext) => {
19
+ // Lazy — runner/loader graph evaluates on first `/wf`, not at startup.
20
+ const { handleWorkflowCommand } = await import("./command-run.js");
21
+ return handleWorkflowCommand(host, args, ctx);
22
+ },
25
23
  });
26
24
  }
27
25
 
28
26
  // ---------------------------------------------------------------------------
29
- // Orchestrator
27
+ // Arg parsing (pure; exported for tests + consumed by ./command-run.js)
30
28
  // ---------------------------------------------------------------------------
31
29
 
32
- async function handleWorkflowCommand(host: WorkflowHost, args: string, ctx: WorkflowContext): Promise<void> {
33
- if (!ctx.hasUI) {
34
- ctx.ui.notify(MSG_INTERACTIVE_ONLY, "error");
35
- return;
36
- }
37
-
38
- const loaded = await loadWorkflows(ctx.cwd);
39
- surfaceIssues(ctx, loaded.issues);
40
-
41
- const workflowNames = new Set(loaded.workflows.map((w) => w.name));
42
- const { workflow: workflowName, input } = parseArgs(args, { workflowNames, default: loaded.default });
43
-
44
- if (!input) {
45
- const trimmed = args.trim();
46
- const previewing = trimmed.length > 0 && workflowNames.has(trimmed);
47
- ctx.ui.notify(previewing ? formatWorkflowDetails(loaded, trimmed) : formatWorkflowList(loaded), "info");
48
- return;
49
- }
50
-
51
- // Block execution on load errors — running a partially-loaded workflow set
52
- // would silently mask the user's intent (e.g. their preferred workflow
53
- // failed to import).
54
- const errorCount = loaded.issues.filter((i) => i.severity === "error").length;
55
- if (errorCount > 0) {
56
- ctx.ui.notify(MSG_LOAD_ABORTED(errorCount), "error");
57
- return;
58
- }
59
-
60
- // Standalone install: rpiv-workflow ships zero workflows; if nothing else
61
- // registered one, there's nothing to run. parseArgs returns "" for the
62
- // workflow name in this case (no default + first token didn't match) —
63
- // surface the empty-registry verdict instead of falling through to a
64
- // generic not-found notify.
65
- if (!workflowName) {
66
- ctx.ui.notify(MSG_NO_WORKFLOWS_REGISTERED, "error");
67
- return;
68
- }
69
-
70
- const workflow = findWorkflow(loaded, workflowName);
71
- if (!workflow) {
72
- ctx.ui.notify(MSG_WORKFLOW_NOT_FOUND(workflowName), "error");
73
- return;
74
- }
75
-
76
- // runWorkflow returns a result envelope rather than throwing — but a
77
- // thrown predicate or invariant could still bubble. Catch so Pi's
78
- // dispatcher doesn't print a raw stack.
79
- try {
80
- await runWorkflow(ctx, { workflow, input, host, trigger: { kind: "command", name: "wf" } });
81
- } catch (e) {
82
- const reason = e instanceof Error ? e.message : String(e);
83
- ctx.ui.notify(MSG_WORKFLOW_THREW(reason), "error");
84
- }
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // Arg parsing (exported for tests)
89
- // ---------------------------------------------------------------------------
30
+ export type ParsedCommand = { kind: "run"; workflow: string; input: string } | { kind: "resume"; ref: string };
90
31
 
91
32
  /**
92
33
  * First token is a workflow name iff recognised; otherwise the whole arg is
93
34
  * input bound to the resolved default. When no default is registered (the
94
35
  * empty-registry case), the returned `workflow` is `""` and the orchestrator
95
36
  * surfaces `MSG_NO_WORKFLOWS_REGISTERED`.
37
+ *
38
+ * `@<ref>` on the first token is the resume sigil — the first whitespace-
39
+ * delimited token after `@` is the run reference. Leading space after the
40
+ * sigil is tolerated (`@ ref` === `@ref`); trailing tokens are ignored.
96
41
  */
97
42
  export function parseArgs(
98
43
  args: string,
99
44
  loaded: { workflowNames: ReadonlySet<string>; default: string | undefined },
100
- ): { workflow: string; input: string } {
45
+ ): ParsedCommand {
101
46
  const trimmed = args.trim();
47
+
48
+ if (trimmed.startsWith("@")) {
49
+ // First token after the sigil is the ref; ignore any trailing tokens for now.
50
+ return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "" };
51
+ }
52
+
102
53
  if (!trimmed) {
103
- return { workflow: loaded.default ?? "", input: "" };
54
+ return { kind: "run", workflow: loaded.default ?? "", input: "" };
104
55
  }
105
56
 
106
57
  const firstSpace = trimmed.indexOf(" ");
@@ -108,30 +59,8 @@ export function parseArgs(
108
59
 
109
60
  if (loaded.workflowNames.has(firstToken)) {
110
61
  const remaining = firstSpace === -1 ? "" : trimmed.slice(firstSpace + 1).trim();
111
- return { workflow: firstToken, input: remaining };
62
+ return { kind: "run", workflow: firstToken, input: remaining };
112
63
  }
113
64
 
114
- return { workflow: loaded.default ?? "", input: trimmed };
115
- }
116
-
117
- // ---------------------------------------------------------------------------
118
- // Private helpers
119
- // ---------------------------------------------------------------------------
120
-
121
- /** Surface every load + validation issue as a notify, prefixed by severity. */
122
- function surfaceIssues(ctx: WorkflowContext, issues: readonly Issue[]): void {
123
- for (const issue of issues) {
124
- const level: "warning" | "error" = issue.severity === "error" ? "error" : "warning";
125
- ctx.ui.notify(formatIssue(issue), level);
126
- }
127
- }
128
-
129
- function formatIssue(issue: Issue): string {
130
- if (issue.kind === "load") {
131
- const where = issue.path ? ` (${issue.path})` : "";
132
- return `[${renderConfigLayer(issue.layer)} config${where}] ${issue.message}`;
133
- }
134
- const stageTag = issue.stage ? ` — stage "${issue.stage}"` : "";
135
- const pathTag = issue.path ? ` (${issue.path})` : "";
136
- return `[${renderConfigLayer(issue.layer)} config${pathTag}] workflow "${issue.workflow}"${stageTag}: ${issue.message}`;
65
+ return { kind: "run", workflow: loaded.default ?? "", input: trimmed };
137
66
  }