@juicesharp/rpiv-workflow 1.17.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -38,6 +38,9 @@
38
38
  "audit.ts",
39
39
  "built-ins.ts",
40
40
  "command.ts",
41
+ "command-run.ts",
42
+ "extension.ts",
43
+ "registration.ts",
41
44
  "fanout.ts",
42
45
  "handle.ts",
43
46
  "host.ts",
@@ -54,6 +57,7 @@
54
57
  "preview.ts",
55
58
  "routing.ts",
56
59
  "runner/",
60
+ "startup.ts",
57
61
  "sessions/",
58
62
  "state/",
59
63
  "transcript.ts",
@@ -69,15 +73,17 @@
69
73
  ],
70
74
  "exports": {
71
75
  ".": "./index.ts",
76
+ "./startup": "./startup.ts",
77
+ "./registration": "./registration.ts",
72
78
  "./internal": "./internal.ts"
73
79
  },
74
80
  "pi": {
75
81
  "extensions": [
76
- "./index.ts"
82
+ "./extension.ts"
77
83
  ]
78
84
  },
79
85
  "dependencies": {
80
- "@juicesharp/rpiv-config": "^1.17.0",
86
+ "@juicesharp/rpiv-config": "^1.18.0",
81
87
  "jiti": "^2.7.0"
82
88
  },
83
89
  "peerDependencies": {
@@ -0,0 +1,113 @@
1
+ /**
2
+ * rpiv-workflow — runner-free public surface: the entire API EXCEPT the
3
+ * execution engine (`./runner/index.js`, ~530ms), which lives only on the main
4
+ * `./index.ts` (`export * from here` + the runner). Siblings that touch
5
+ * rpiv-workflow at startup (registering built-ins/lifecycle, authoring
6
+ * definitions, listing workflows) import this so they never drag the runner onto
7
+ * the startup path. Dependencies flow runner → leaf, so this can't pull it.
8
+ */
9
+
10
+ export {
11
+ type ActsScriptFn,
12
+ acts,
13
+ type DefineRouteOptions,
14
+ defineRoute,
15
+ defineWorkflow,
16
+ type EdgeContext,
17
+ type EdgeFn,
18
+ type EdgeTarget,
19
+ type FanoutContext,
20
+ type FanoutFn,
21
+ type FanoutUnit,
22
+ gate,
23
+ type IterateContext,
24
+ type IterateFn,
25
+ type IterateUnit,
26
+ marksReadsData,
27
+ ON_INVALID_VALUES,
28
+ type OnInvalid,
29
+ type ProducesScriptFn,
30
+ type PromptFn,
31
+ produces,
32
+ READS_DATA,
33
+ type ScriptContext,
34
+ SESSION_POLICIES,
35
+ type SessionPolicy,
36
+ STAGE_KINDS,
37
+ STOP,
38
+ type StageDef,
39
+ type StageKind,
40
+ type StageSchema,
41
+ terminal,
42
+ type Workflow,
43
+ } from "./api.js";
44
+ export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
45
+ export {
46
+ type Artifact,
47
+ type ArtifactHandle,
48
+ fs,
49
+ handleToString,
50
+ inline,
51
+ opaque,
52
+ url,
53
+ } from "./handle.js";
54
+ export type { WorkflowHost, WorkflowHostContext, WorkflowSessionContext } from "./host.js";
55
+ export { type LifecycleContext, type LifecycleListeners, registerLifecycle, type StageRef } from "./lifecycle.js";
56
+ export type { ConfigLayer, Issue, LoadedWorkflows, LoadIssue, OverlayPaths } from "./load/index.js";
57
+ export { aliasSkills, loadWorkflows, projectOverlayPaths, userOverlayPaths } from "./load/index.js";
58
+ export {
59
+ type DirectoryPathCollectorOpts,
60
+ directoryPathCollector,
61
+ type GitCommitData,
62
+ type GitHeadSnapshot,
63
+ gitCommitCollector,
64
+ gitCommitOutcome,
65
+ gitCommitParser,
66
+ gitHeadSnapshot,
67
+ jsonBodyParser,
68
+ noopCollector,
69
+ sideEffectOutcome,
70
+ type ToolCall,
71
+ type ToolCallCollectorOpts,
72
+ type TranscriptPathCollectorOpts,
73
+ toolCallCollector,
74
+ transcriptPathCollector,
75
+ type UrlCollectorOpts,
76
+ unionCollectors,
77
+ urlCollector,
78
+ type WorkspaceDiffCollectorOpts,
79
+ type WorkspaceDiffSnapshot,
80
+ workspaceDiffCollector,
81
+ } from "./outcomes/index.js";
82
+ export type {
83
+ ArtifactCollector,
84
+ ArtifactParser,
85
+ CollectCtx,
86
+ CollectResult,
87
+ Output,
88
+ OutputMeta,
89
+ OutputSpec,
90
+ ParseCtx,
91
+ ParseResult,
92
+ SnapshotCtx,
93
+ SnapshotFn,
94
+ } from "./output.js";
95
+ export { defineCollector, defineParser } from "./output-spec.js";
96
+ export { eq, gt, gte, lt, lte, type Predicate } from "./predicates.js";
97
+ export {
98
+ listArtifacts,
99
+ listRuns,
100
+ type RunSummary,
101
+ readHeader,
102
+ readLastStage,
103
+ resolveRun,
104
+ runsDir,
105
+ stateFilePath,
106
+ type WorkflowHeader,
107
+ type WorkflowStage,
108
+ } from "./state/index.js";
109
+ export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
110
+ export { typeboxSchema } from "./typebox-adapter.js";
111
+ export type { RunState } from "./types.js";
112
+ export { type SchemaValidationFailure, validateOutputData } from "./validate-output.js";
113
+ export { validateWorkflow, type WorkflowValidationIssue } from "./validate-workflow.js";
@@ -0,0 +1,95 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import type { WorkflowHostContext } from "../host.js";
3
+
4
+ // Mock the loader + core runner so the convenience layer is tested in isolation
5
+ // (no jiti, no filesystem, no Pi session runtime).
6
+ vi.mock("../load/index.js", () => ({
7
+ loadWorkflows: vi.fn(),
8
+ findWorkflow: vi.fn(),
9
+ }));
10
+ vi.mock("./runner.js", () => ({
11
+ runWorkflow: vi.fn(),
12
+ }));
13
+
14
+ import { findWorkflow, loadWorkflows } from "../load/index.js";
15
+ import { runWorkflowByName } from "./by-name.js";
16
+ import { runWorkflow } from "./runner.js";
17
+
18
+ // Type-only context — runWorkflowByName only reads ctx.cwd and forwards ctx.
19
+ const ctx = { cwd: "/repo" } as unknown as WorkflowHostContext;
20
+
21
+ beforeEach(() => {
22
+ vi.mocked(loadWorkflows).mockReset();
23
+ vi.mocked(findWorkflow).mockReset();
24
+ vi.mocked(runWorkflow).mockReset();
25
+ });
26
+
27
+ describe("runWorkflowByName", () => {
28
+ it("refuses when the overlay has error-severity load issues, listing only errors", async () => {
29
+ vi.mocked(loadWorkflows).mockResolvedValue({
30
+ workflows: [],
31
+ issues: [
32
+ { severity: "error", message: "bad overlay A" },
33
+ { severity: "warning", message: "ignore me" },
34
+ { severity: "error", message: "bad overlay B" },
35
+ ],
36
+ } as unknown as Awaited<ReturnType<typeof loadWorkflows>>);
37
+
38
+ const result = await runWorkflowByName(ctx, "research", "input");
39
+
40
+ expect(result.success).toBe(false);
41
+ expect(result.stagesCompleted).toBe(0);
42
+ expect(result.error).toContain("2 load error(s)");
43
+ expect(result.error).toContain("bad overlay A");
44
+ expect(result.error).toContain("bad overlay B");
45
+ expect(result.error).not.toContain("ignore me");
46
+ // Never resolves or dispatches off a partial set.
47
+ expect(findWorkflow).not.toHaveBeenCalled();
48
+ expect(runWorkflow).not.toHaveBeenCalled();
49
+ });
50
+
51
+ it("returns a not-found envelope listing available workflow names", async () => {
52
+ vi.mocked(loadWorkflows).mockResolvedValue({
53
+ workflows: [{ name: "research" }, { name: "ship" }],
54
+ issues: [],
55
+ } as unknown as Awaited<ReturnType<typeof loadWorkflows>>);
56
+ vi.mocked(findWorkflow).mockReturnValue(undefined);
57
+
58
+ const result = await runWorkflowByName(ctx, "nope", "input");
59
+
60
+ expect(result.success).toBe(false);
61
+ expect(result.stagesCompleted).toBe(0);
62
+ expect(result.error).toContain('"nope" not found');
63
+ expect(result.error).toContain("research, ship");
64
+ expect(runWorkflow).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it("reports 'none' when no workflows are available", async () => {
68
+ vi.mocked(loadWorkflows).mockResolvedValue({
69
+ workflows: [],
70
+ issues: [],
71
+ } as unknown as Awaited<ReturnType<typeof loadWorkflows>>);
72
+ vi.mocked(findWorkflow).mockReturnValue(undefined);
73
+
74
+ const result = await runWorkflowByName(ctx, "nope", "input");
75
+
76
+ expect(result.error).toContain("available: none");
77
+ });
78
+
79
+ it("delegates to runWorkflow with the resolved workflow, input, and opts", async () => {
80
+ const wf = { name: "research" };
81
+ vi.mocked(loadWorkflows).mockResolvedValue({
82
+ workflows: [wf],
83
+ issues: [{ severity: "warning", message: "non-fatal" }],
84
+ } as unknown as Awaited<ReturnType<typeof loadWorkflows>>);
85
+ vi.mocked(findWorkflow).mockReturnValue(wf as unknown as ReturnType<typeof findWorkflow>);
86
+ vi.mocked(runWorkflow).mockResolvedValue({ stagesCompleted: 3, success: true });
87
+
88
+ const host = { withSession: vi.fn() } as unknown as NonNullable<Parameters<typeof runWorkflowByName>[3]>["host"];
89
+ const result = await runWorkflowByName(ctx, "research", "add dark mode", { host });
90
+
91
+ // Warnings do not gate; opts flow through alongside workflow + input.
92
+ expect(runWorkflow).toHaveBeenCalledWith(ctx, { workflow: wf, input: "add dark mode", host });
93
+ expect(result).toEqual({ stagesCompleted: 3, success: true });
94
+ });
95
+ });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `runWorkflowByName` — the ergonomic one-shot entry point.
3
+ *
4
+ * Sugar over the three-step `loadWorkflows` → `findWorkflow` → `runWorkflow`
5
+ * dance for the common "just run this workflow by name" case. Lives in its
6
+ * own module (not `runner.ts`) so the core graph walker stays decoupled from
7
+ * the loader — `runWorkflow` still takes a pre-resolved `Workflow`; only this
8
+ * convenience layer reaches into `load/`.
9
+ *
10
+ * Contract mirrors `command.ts` (the `/wf` handler) so the programmatic path
11
+ * and the slash-command path never diverge:
12
+ * 1. error-severity load issues → refuse (a broken overlay means the
13
+ * merged set may be partial / wrong)
14
+ * 2. name not found → failure envelope listing what IS available
15
+ * 3. otherwise → delegate to `runWorkflow`
16
+ *
17
+ * Every expected failure is returned as a `RunWorkflowResult` envelope, never
18
+ * thrown — consistent with `runWorkflow`'s own pre-flight rejections and the
19
+ * loader's "never throws" guarantee. Callers branch on `result.success`.
20
+ */
21
+
22
+ import type { WorkflowHostContext } from "../host.js";
23
+ import { findWorkflow, loadWorkflows } from "../load/index.js";
24
+ import { type RunWorkflowOptions, type RunWorkflowResult, runWorkflow } from "./runner.js";
25
+
26
+ /**
27
+ * Options for `runWorkflowByName` — the full `RunWorkflowOptions` surface
28
+ * minus the two fields this helper supplies positionally (`workflow` is
29
+ * resolved by name; `input` is the third argument). Derived via `Omit` so it
30
+ * tracks `RunWorkflowOptions` automatically — new options (host, trigger,
31
+ * lifecycle, caps) flow through with zero edits here.
32
+ */
33
+ export type RunWorkflowByNameOptions = Omit<RunWorkflowOptions, "workflow" | "input">;
34
+
35
+ /**
36
+ * Load the merged overlay for `ctx.cwd`, resolve `name`, and run it.
37
+ *
38
+ * const result = await runWorkflowByName(ctx, "research", "add dark mode");
39
+ * if (!result.success) ctx.ui.notify(result.error ?? "failed", "error");
40
+ *
41
+ * Pass `opts` to thread a `host` (required for continue-policy stages), a
42
+ * `trigger`, `lifecycle` listeners, or the iteration caps — same semantics as
43
+ * `runWorkflow`.
44
+ */
45
+ export async function runWorkflowByName(
46
+ ctx: WorkflowHostContext,
47
+ name: string,
48
+ input: string,
49
+ opts?: RunWorkflowByNameOptions,
50
+ ): Promise<RunWorkflowResult> {
51
+ const loaded = await loadWorkflows(ctx.cwd);
52
+
53
+ // Gate on load errors exactly as command.ts does: a broken config/pack
54
+ // file can drop or mangle workflows during the layered merge, so running
55
+ // anything off a partial set risks dispatching the wrong thing silently.
56
+ const errors = loaded.issues.filter((i) => i.severity === "error");
57
+ if (errors.length > 0) {
58
+ return {
59
+ stagesCompleted: 0,
60
+ success: false,
61
+ error: `workflow overlay has ${errors.length} load error(s): ${errors.map((i) => i.message).join("; ")}`,
62
+ };
63
+ }
64
+
65
+ const workflow = findWorkflow(loaded, name);
66
+ if (!workflow) {
67
+ const available = loaded.workflows.map((w) => w.name);
68
+ return {
69
+ stagesCompleted: 0,
70
+ success: false,
71
+ error: `workflow "${name}" not found (available: ${available.length > 0 ? available.join(", ") : "none"})`,
72
+ };
73
+ }
74
+
75
+ return runWorkflow(ctx, { workflow, input, ...opts });
76
+ }
@@ -0,0 +1,115 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import type { WorkflowHostContext } from "../host.js";
3
+ import type { WorkflowHeader } from "../state/state.js";
4
+
5
+ // Mock the loader + state reads + core runner so the convenience layer is tested
6
+ // in isolation (no jiti, no filesystem, no Pi session runtime).
7
+ vi.mock("../load/index.js", () => ({
8
+ loadWorkflows: vi.fn(),
9
+ findWorkflow: vi.fn(),
10
+ }));
11
+ vi.mock("../state/index.js", () => ({
12
+ resolveRun: vi.fn(),
13
+ }));
14
+ vi.mock("./runner.js", () => ({
15
+ resumeWorkflow: vi.fn(),
16
+ }));
17
+
18
+ import { findWorkflow, loadWorkflows } from "../load/index.js";
19
+ import { resolveRun } from "../state/index.js";
20
+ import { resumeWorkflowByRunId } from "./by-run-id.js";
21
+ import { resumeWorkflow } from "./runner.js";
22
+
23
+ // Type-only context — resumeWorkflowByRunId only reads ctx.cwd and forwards ctx.
24
+ const ctx = { cwd: "/repo" } as unknown as WorkflowHostContext;
25
+
26
+ const RUN_ID = "2026-06-03_07-30-00-ab12";
27
+ const header: WorkflowHeader = {
28
+ runId: RUN_ID,
29
+ workflow: "research",
30
+ input: "add dark mode",
31
+ ts: "2026-06-03T07:30:00Z",
32
+ };
33
+
34
+ const loaded = (over: Partial<Awaited<ReturnType<typeof loadWorkflows>>> = {}) =>
35
+ ({ workflows: [{ name: "research" }], issues: [], ...over }) as unknown as Awaited<ReturnType<typeof loadWorkflows>>;
36
+
37
+ beforeEach(() => {
38
+ vi.mocked(resolveRun).mockReset();
39
+ vi.mocked(loadWorkflows).mockReset();
40
+ vi.mocked(findWorkflow).mockReset();
41
+ vi.mocked(resumeWorkflow).mockReset();
42
+ });
43
+
44
+ describe("resumeWorkflowByRunId", () => {
45
+ it("returns a not-found envelope when the run-id doesn't resolve; never loads or resumes", async () => {
46
+ vi.mocked(resolveRun).mockReturnValue(undefined);
47
+
48
+ const result = await resumeWorkflowByRunId(ctx, "bogus-id");
49
+
50
+ expect(result.success).toBe(false);
51
+ expect(result.stagesCompleted).toBe(0);
52
+ expect(result.error).toContain('no run found for "bogus-id"');
53
+ // No runId on the envelope — command's discriminator notifies this once.
54
+ expect(result.runId).toBeUndefined();
55
+ expect(resolveRun).toHaveBeenCalledWith("/repo", "bogus-id");
56
+ expect(loadWorkflows).not.toHaveBeenCalled();
57
+ expect(resumeWorkflow).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it("refuses on error-severity load issues; never resolves the workflow or resumes", async () => {
61
+ vi.mocked(resolveRun).mockReturnValue(header);
62
+ vi.mocked(loadWorkflows).mockResolvedValue(
63
+ loaded({
64
+ issues: [
65
+ { severity: "error", message: "bad overlay" },
66
+ { severity: "warning", message: "ignore me" },
67
+ ],
68
+ } as unknown as Awaited<ReturnType<typeof loadWorkflows>>),
69
+ );
70
+
71
+ const result = await resumeWorkflowByRunId(ctx, RUN_ID);
72
+
73
+ expect(result.success).toBe(false);
74
+ expect(result.error).toContain("config error");
75
+ expect(result.runId).toBeUndefined();
76
+ expect(findWorkflow).not.toHaveBeenCalled();
77
+ expect(resumeWorkflow).not.toHaveBeenCalled();
78
+ });
79
+
80
+ it("returns a workflow-gone envelope when the run's workflow is no longer loaded", async () => {
81
+ vi.mocked(resolveRun).mockReturnValue({ ...header, workflow: "deleted-wf" });
82
+ vi.mocked(loadWorkflows).mockResolvedValue(loaded());
83
+ vi.mocked(findWorkflow).mockReturnValue(undefined);
84
+
85
+ const result = await resumeWorkflowByRunId(ctx, RUN_ID);
86
+
87
+ expect(result.success).toBe(false);
88
+ expect(result.error).toContain('"deleted-wf"');
89
+ expect(result.error).toContain("no longer registered");
90
+ expect(result.runId).toBeUndefined();
91
+ expect(resumeWorkflow).not.toHaveBeenCalled();
92
+ });
93
+
94
+ it("delegates to resumeWorkflow with the resolved workflow, header, run-id as ref, and opts", async () => {
95
+ const wf = { name: "research" };
96
+ vi.mocked(resolveRun).mockReturnValue(header);
97
+ // Warnings do not gate.
98
+ vi.mocked(loadWorkflows).mockResolvedValue(
99
+ loaded({ issues: [{ severity: "warning", message: "non-fatal" }] } as unknown as Awaited<
100
+ ReturnType<typeof loadWorkflows>
101
+ >),
102
+ );
103
+ vi.mocked(findWorkflow).mockReturnValue(wf as unknown as ReturnType<typeof findWorkflow>);
104
+ vi.mocked(resumeWorkflow).mockResolvedValue({ runId: RUN_ID, stagesCompleted: 2, success: true });
105
+
106
+ const host = {
107
+ getCommands: vi.fn(),
108
+ } as unknown as NonNullable<Parameters<typeof resumeWorkflowByRunId>[2]>["host"];
109
+ const result = await resumeWorkflowByRunId(ctx, RUN_ID, { host });
110
+
111
+ // ref is the run-id; opts flow through alongside workflow + header.
112
+ expect(resumeWorkflow).toHaveBeenCalledWith(ctx, { workflow: wf, header, ref: RUN_ID, host });
113
+ expect(result).toEqual({ runId: RUN_ID, stagesCompleted: 2, success: true });
114
+ });
115
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `resumeWorkflowByRunId` — the ergonomic one-shot resume entry point.
3
+ *
4
+ * Sugar over the `resolveRun` → `loadWorkflows` → `findWorkflow` →
5
+ * `resumeWorkflow` dance, the resume-side counterpart to `runWorkflowByName`.
6
+ * Lives in its own module (not `runner.ts`) so the core graph walker stays
7
+ * decoupled from the loader + state reads — `resumeWorkflow` still takes a
8
+ * pre-resolved `Workflow` + `WorkflowHeader`; only this convenience layer
9
+ * reaches into `load/` and `state/`.
10
+ *
11
+ * Naming: the suffix names the identifier the caller hands in.
12
+ * `runWorkflowByName` resolves a *workflow* by name (you're starting a run, so
13
+ * you say which workflow); `resumeWorkflowByRunId` resolves a specific past
14
+ * *run* by its run-id (a workflow has many runs, so a workflow name can't
15
+ * identify one). `runId` is literally the `<run-id>` slug naming the JSONL file
16
+ * under `<cwd>/.rpiv/workflows/runs/` — exactly what `listRuns()` returns on
17
+ * `RunSummary.runId`. (When `resolveRun` later grows symbolic resolution —
18
+ * `@latest`, relative refs — the parameter can widen to a `ref`; today it is a
19
+ * plain run-id and the name says so.)
20
+ *
21
+ * The run header already names its workflow, so the lookup is free — the caller
22
+ * supplies only the run-id.
23
+ *
24
+ * Contract mirrors `command.ts`'s former resume guards so the programmatic path
25
+ * and the `/wf @<run-id>` path never diverge:
26
+ * 1. run-id doesn't resolve to a run → failure envelope (`MSG_RUN_NOT_FOUND`)
27
+ * 2. error-severity load issues → refuse (a broken overlay may
28
+ * mis-resolve the workflow) (`MSG_LOAD_ABORTED`)
29
+ * 3. header's workflow no longer loaded → failure envelope (`MSG_RESUME_WORKFLOW_GONE`)
30
+ * 4. otherwise → delegate to `resumeWorkflow`
31
+ *
32
+ * Pure, like `runWorkflowByName` and `resumeWorkflow`: every expected failure is
33
+ * returned in the `RunWorkflowResult` envelope, never thrown and never
34
+ * self-notified. Callers branch on `result.success` and surface `result.error`
35
+ * themselves (see `command.ts`'s `!result.runId` discriminator, which notifies
36
+ * no-JSONL refusals once while leaving in-run failures to the stage machinery).
37
+ */
38
+
39
+ import type { WorkflowHostContext } from "../host.js";
40
+ import { findWorkflow, loadWorkflows } from "../load/index.js";
41
+ import { MSG_LOAD_ABORTED, MSG_RESUME_WORKFLOW_GONE, MSG_RUN_NOT_FOUND } from "../messages.js";
42
+ import { resolveRun } from "../state/index.js";
43
+ import { type ResumeWorkflowOptions, type RunWorkflowResult, resumeWorkflow } from "./runner.js";
44
+
45
+ /**
46
+ * Options for `resumeWorkflowByRunId` — the full `ResumeWorkflowOptions` surface
47
+ * minus the three fields this helper resolves itself (`workflow` from the
48
+ * header, `header` from the run-id, `ref` supplied as the run-id). Derived via
49
+ * `Omit` so it tracks `ResumeWorkflowOptions` automatically — new options
50
+ * (host, lifecycle, caps) flow through with zero edits here.
51
+ */
52
+ export type ResumeWorkflowByRunIdOptions = Omit<ResumeWorkflowOptions, "workflow" | "header" | "ref">;
53
+
54
+ /**
55
+ * Resolve `runId` to a run header, load the merged overlay for `ctx.cwd`, find
56
+ * the run's workflow, and resume it.
57
+ *
58
+ * const result = await resumeWorkflowByRunId(ctx, "2026-06-03_07-30-00-ab12", { host });
59
+ * if (!result.success) ctx.ui.notify(result.error ?? "resume failed", "error");
60
+ *
61
+ * Pass `opts` to thread a `host` (required for continue-policy stages),
62
+ * `lifecycle` listeners, or the iteration caps — same semantics as
63
+ * `resumeWorkflow`.
64
+ */
65
+ export async function resumeWorkflowByRunId(
66
+ ctx: WorkflowHostContext,
67
+ runId: string,
68
+ opts?: ResumeWorkflowByRunIdOptions,
69
+ ): Promise<RunWorkflowResult> {
70
+ const header = resolveRun(ctx.cwd, runId);
71
+ if (!header) {
72
+ return { stagesCompleted: 0, success: false, error: MSG_RUN_NOT_FOUND(runId) };
73
+ }
74
+
75
+ const loaded = await loadWorkflows(ctx.cwd);
76
+
77
+ // Gate on load errors exactly as the run-by-name path does: a broken
78
+ // config/pack file can drop or mangle workflows during the layered merge, so
79
+ // resolving the run's workflow off a partial set risks resuming the wrong thing.
80
+ const errors = loaded.issues.filter((i) => i.severity === "error");
81
+ if (errors.length > 0) {
82
+ return { stagesCompleted: 0, success: false, error: MSG_LOAD_ABORTED(errors.length) };
83
+ }
84
+
85
+ const workflow = findWorkflow(loaded, header.workflow);
86
+ if (!workflow) {
87
+ return { stagesCompleted: 0, success: false, error: MSG_RESUME_WORKFLOW_GONE(header.workflow, runId) };
88
+ }
89
+
90
+ // `ref` is the run-id here — it surfaces in `trigger.meta.resumedFrom`.
91
+ return resumeWorkflow(ctx, { workflow, header, ref: runId, ...opts });
92
+ }
@@ -8,7 +8,7 @@
8
8
  * downstream-stage throws.
9
9
  */
10
10
 
11
- import { nowIso, recordTerminalFailure } from "../audit.js";
11
+ import { auditCtxFor, nowIso, recordTerminalFailure } from "../audit.js";
12
12
  import { skillStageRef } from "../lifecycle.js";
13
13
  import {
14
14
  ERR_BACKWARD_JUMP_EXHAUSTED,
@@ -18,7 +18,7 @@ import {
18
18
  } from "../messages.js";
19
19
  import { edgeIsDecision, nextStage } from "../routing.js";
20
20
  import { appendRoutingDecision } from "../state/index.js";
21
- import type { RunContext, RunnerCtx } from "../types.js";
21
+ import type { RunContext, WorkflowHostContext } from "../types.js";
22
22
  import { finalizeWorkflow, lifecycleCtxFor, runStageOrRecordFailure } from "./runner.js";
23
23
 
24
24
  /**
@@ -27,7 +27,7 @@ import { finalizeWorkflow, lifecycleCtxFor, runStageOrRecordFailure } from "./ru
27
27
  * structural concern.
28
28
  */
29
29
  export async function advanceChain(
30
- curCtx: RunnerCtx,
30
+ curCtx: WorkflowHostContext,
31
31
  currentName: string,
32
32
  idx: number,
33
33
  run: RunContext,
@@ -83,7 +83,7 @@ export async function advanceChain(
83
83
  * routing rows are pure telemetry).
84
84
  */
85
85
  function auditRoutingDecision(
86
- curCtx: RunnerCtx,
86
+ curCtx: WorkflowHostContext,
87
87
  run: RunContext,
88
88
  idx: number,
89
89
  currentName: string,
@@ -124,7 +124,11 @@ function auditRoutingDecision(
124
124
  * Trip attribution targets `nextName` (the stage the guard refused to
125
125
  * re-enter), not the just-completed stage. Same lesson as Q12+IB.
126
126
  */
127
- async function checkBackwardJumpGuard(curCtx: RunnerCtx, run: RunContext, nextName: string): Promise<boolean> {
127
+ async function checkBackwardJumpGuard(
128
+ curCtx: WorkflowHostContext,
129
+ run: RunContext,
130
+ nextName: string,
131
+ ): Promise<boolean> {
128
132
  const { state } = run;
129
133
  if (!run.visited.has(nextName)) {
130
134
  state.telemetry.backwardJumps = 0;
@@ -132,24 +136,12 @@ async function checkBackwardJumpGuard(curCtx: RunnerCtx, run: RunContext, nextNa
132
136
  }
133
137
  state.telemetry.backwardJumps++;
134
138
  if (state.telemetry.backwardJumps <= run.maxBackwardJumps) return true;
135
- await recordTerminalFailure(
136
- curCtx,
137
- {
138
- cwd: run.cwd,
139
- runId: run.runId,
140
- state,
141
- stageName: nextName,
142
- skill: nextName,
143
- lifecycle: run.lifecycle,
144
- runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
145
- },
146
- {
147
- status: "failed",
148
- notifyMsg: MSG_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
149
- notifyLevel: "error",
150
- errMsg: ERR_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
151
- },
152
- );
139
+ await recordTerminalFailure(curCtx, auditCtxFor(run, nextName, nextName), {
140
+ status: "failed",
141
+ notifyMsg: MSG_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
142
+ notifyLevel: "error",
143
+ errMsg: ERR_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
144
+ });
153
145
  return false;
154
146
  }
155
147
 
@@ -159,27 +151,15 @@ async function checkBackwardJumpGuard(curCtx: RunnerCtx, run: RunContext, nextNa
159
151
  * `currentName` (the edge belongs to the just-completed stage).
160
152
  */
161
153
  async function haltOnRoutingError(
162
- curCtx: RunnerCtx,
154
+ curCtx: WorkflowHostContext,
163
155
  run: RunContext,
164
156
  currentName: string,
165
157
  reason: string,
166
158
  ): Promise<void> {
167
- await recordTerminalFailure(
168
- curCtx,
169
- {
170
- cwd: run.cwd,
171
- runId: run.runId,
172
- state: run.state,
173
- stageName: currentName,
174
- skill: currentName,
175
- lifecycle: run.lifecycle,
176
- runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
177
- },
178
- {
179
- status: "failed",
180
- notifyMsg: MSG_CHAIN_ADVANCE_FAILED(currentName, reason),
181
- notifyLevel: "error",
182
- errMsg: reason,
183
- },
184
- );
159
+ await recordTerminalFailure(curCtx, auditCtxFor(run, currentName, currentName), {
160
+ status: "failed",
161
+ notifyMsg: MSG_CHAIN_ADVANCE_FAILED(currentName, reason),
162
+ notifyLevel: "error",
163
+ errMsg: reason,
164
+ });
185
165
  }
package/runner/index.ts CHANGED
@@ -4,4 +4,13 @@
4
4
  * re-exports only the symbols the package itself needs to publish.
5
5
  */
6
6
 
7
- export { MAX_BACKWARD_JUMPS, type RunWorkflowOptions, type RunWorkflowResult, runWorkflow } from "./runner.js";
7
+ export { type RunWorkflowByNameOptions, runWorkflowByName } from "./by-name.js";
8
+ export { type ResumeWorkflowByRunIdOptions, resumeWorkflowByRunId } from "./by-run-id.js";
9
+ export {
10
+ MAX_BACKWARD_JUMPS,
11
+ type ResumeWorkflowOptions,
12
+ type RunWorkflowOptions,
13
+ type RunWorkflowResult,
14
+ resumeWorkflow,
15
+ runWorkflow,
16
+ } from "./runner.js";