@niwa-labs/workflow 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/package.json +55 -4
  4. package/src/actions.ts +408 -0
  5. package/src/agent.ts +211 -0
  6. package/src/ask.ts +84 -0
  7. package/src/bridge.ts +710 -0
  8. package/src/catalogue.ts +74 -0
  9. package/src/check.ts +880 -0
  10. package/src/child.ts +1378 -0
  11. package/src/cockpit/actions.ts +128 -0
  12. package/src/cockpit/catalogue-actions.ts +97 -0
  13. package/src/cockpit/dashboard.tsx +134 -0
  14. package/src/cockpit/groups.ts +45 -0
  15. package/src/cockpit/index.tsx +50 -0
  16. package/src/cockpit/launch.tsx +136 -0
  17. package/src/cockpit/plan.ts +101 -0
  18. package/src/cockpit/run-commands.tsx +102 -0
  19. package/src/cockpit/run-page.tsx +140 -0
  20. package/src/cockpit/run-summary.ts +16 -0
  21. package/src/cockpit/runs.tsx +73 -0
  22. package/src/cockpit/statistics.tsx +176 -0
  23. package/src/cockpit/track.tsx +159 -0
  24. package/src/cockpit/workflows.tsx +383 -0
  25. package/src/describe-cache.ts +122 -0
  26. package/src/describe.ts +174 -0
  27. package/src/guide.ts +213 -0
  28. package/src/index.ts +2813 -0
  29. package/src/inspect.ts +235 -0
  30. package/src/installation.ts +90 -0
  31. package/src/language.ts +217 -0
  32. package/src/records-entry.ts +63 -0
  33. package/src/records.ts +574 -0
  34. package/src/registry.ts +250 -0
  35. package/src/revise.ts +89 -0
  36. package/src/runner.ts +339 -0
  37. package/src/script-types.ts +549 -0
  38. package/src/stats.ts +460 -0
  39. package/src/status.ts +512 -0
  40. package/src/store.ts +259 -0
  41. package/src/subscriptions.ts +102 -0
  42. package/src/waiting.ts +61 -0
  43. package/test/cockpit-actions.test.ts +20 -0
  44. package/test/cockpit-groups.test.ts +42 -0
  45. package/test/cockpit-plan.test.ts +118 -0
  46. package/test/fixtures/branches-host.ts +58 -0
  47. package/test/fixtures/branches-script.js +23 -0
  48. package/test/fixtures/bridge-host.ts +23 -0
  49. package/test/fixtures/bridge-keys-script.js +15 -0
  50. package/test/fixtures/bridge-wait-script.js +8 -0
  51. package/test/fixtures/cancel-host.ts +58 -0
  52. package/test/fixtures/cancel-script.js +12 -0
  53. package/test/fixtures/crash-host.ts +61 -0
  54. package/test/fixtures/crash-script.js +14 -0
  55. package/test/fixtures/ping-records.ts +20 -0
  56. package/test/fixtures/revision-host.ts +57 -0
  57. package/test/fixtures/revision-script.js +11 -0
  58. package/test/fixtures/running-host.ts +61 -0
  59. package/test/fixtures/running-script.js +12 -0
  60. package/test/fixtures/with-data/flow.ts +2 -0
  61. package/test/fixtures/with-data/table.json +1 -0
  62. package/test/git-repo.ts +45 -0
  63. package/test/git-worktree.test.ts +413 -0
  64. package/test/question-format.test.ts +279 -0
  65. package/test/workflow-agent-caps.test.ts +91 -0
  66. package/test/workflow-agent-lifetime.test.ts +93 -0
  67. package/test/workflow-agent-options.test.ts +216 -0
  68. package/test/workflow-agent-schema.test.ts +386 -0
  69. package/test/workflow-agent-typings.test.ts +241 -0
  70. package/test/workflow-ask-resume.test.ts +145 -0
  71. package/test/workflow-branch-keys.test.ts +133 -0
  72. package/test/workflow-bridge-inproc.test.ts +230 -0
  73. package/test/workflow-bridge.test.ts +141 -0
  74. package/test/workflow-builtin-candidate.test.ts +230 -0
  75. package/test/workflow-builtin.test.ts +197 -0
  76. package/test/workflow-cancel-agent.test.ts +144 -0
  77. package/test/workflow-cancel.test.ts +166 -0
  78. package/test/workflow-chain.test.ts +84 -0
  79. package/test/workflow-check-options.test.ts +144 -0
  80. package/test/workflow-check-uses.test.ts +148 -0
  81. package/test/workflow-check.test.ts +282 -0
  82. package/test/workflow-contract.test.ts +295 -0
  83. package/test/workflow-crash-resume.test.ts +141 -0
  84. package/test/workflow-deadline.test.ts +102 -0
  85. package/test/workflow-describe-cache.test.ts +240 -0
  86. package/test/workflow-directory.test.ts +73 -0
  87. package/test/workflow-emits.test.ts +261 -0
  88. package/test/workflow-group-keys.test.ts +72 -0
  89. package/test/workflow-harnesses.test.ts +262 -0
  90. package/test/workflow-inspect.test.ts +152 -0
  91. package/test/workflow-language-types.test.ts +148 -0
  92. package/test/workflow-manifest.test.ts +93 -0
  93. package/test/workflow-manual-pause.test.ts +116 -0
  94. package/test/workflow-owners.test.ts +154 -0
  95. package/test/workflow-pause.test.ts +200 -0
  96. package/test/workflow-phases.test.ts +445 -0
  97. package/test/workflow-plugin-entries.test.ts +59 -0
  98. package/test/workflow-record-refs.test.ts +310 -0
  99. package/test/workflow-replay.test.ts +206 -0
  100. package/test/workflow-resume-once.test.ts +188 -0
  101. package/test/workflow-revision.test.ts +216 -0
  102. package/test/workflow-scope.test.ts +505 -0
  103. package/test/workflow-script-defaults.test.ts +119 -0
  104. package/test/workflow-script-error.test.ts +228 -0
  105. package/test/workflow-script-libraries.test.ts +88 -0
  106. package/test/workflow-script-packages.test.ts +119 -0
  107. package/test/workflow-stdout.test.ts +89 -0
  108. package/test/workflow-stop.test.ts +299 -0
  109. package/test/workflow-store.test.ts +220 -0
  110. package/test/workflow-visible.test.ts +136 -0
  111. package/test/workflow-wait-version.test.ts +54 -0
  112. package/test/workflow-wait.test.ts +224 -0
  113. package/test/workflow-waiting-agent.test.ts +64 -0
  114. package/tsconfig.json +15 -0
@@ -0,0 +1,445 @@
1
+ // The phases of a script: `workflow({ phases })` declares the plan, `phase(title)` enters one (the script itself, or
2
+ // only the branch of `parallel`/`pipeline` it is called in), the typing holds the title to the declared ones, the
3
+ // child refuses an undeclared one where it is named, and a run's progress (done | current | ahead, several current
4
+ // while branches are in different phases) is derived from the records its branches wrote.
5
+
6
+ import { afterEach, expect, test } from "bun:test";
7
+ import { mkdir, writeFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ import { record, recordId, seq, streamId } from "@niwa-labs/core";
12
+ import type { ActionName, JournalReader, StoredRecord } from "@niwa-labs/core";
13
+ import { plugin } from "@niwa-labs/plugin";
14
+ import { createNiwa, requests, timers, counter, eventually, gate, spawnHost, tempHome, connectAsOwner, watch } from "@niwa-labs/testing";
15
+ import type { Host } from "@niwa-labs/testing";
16
+ import { workflow, workflowCheck, workflowGet, workflowInspect, workflowInstall, workflowList, workflowRegister, workflowResume, workflowRevise, workflowRuns, workflowStart, workflowWait } from "../src/index.ts";
17
+ import { inspectRun } from "../src/inspect.ts";
18
+ import { runEntry, statusOf, type RunStatus } from "../src/status.ts";
19
+
20
+ import { PhaseEntered, PhaseLeft, RunId, RunRequested, RunStarted, StepPhase } from "../src/records.ts";
21
+ import { scriptTyping } from "../src/script-types.ts";
22
+ import { z } from "zod";
23
+
24
+ /** A record a branch of a test waits for. */
25
+ const Go = record("test.go", z.object({}));
26
+
27
+ const homes: Array<{ cleanup(): Promise<void> }> = [];
28
+ const hosts: Host[] = [];
29
+
30
+ afterEach(async () => {
31
+ for (const host of hosts.splice(0)) await host.close().catch(() => {});
32
+ for (const home of homes.splice(0)) await home.cleanup();
33
+ });
34
+
35
+ async function served(): Promise<{ host: Host; home: string }> {
36
+ const home = await tempHome();
37
+ homes.push(home);
38
+ const host = createNiwa({ home: home.path });
39
+ host.use(requests(), timers([]), plugin("go", (api) => api.declare(Go)), workflow({ triggers: [Go] }));
40
+ await host.serve();
41
+ hosts.push(host);
42
+ return { host, home: home.path };
43
+ }
44
+
45
+ async function scriptIn(home: string, name: string, lines: readonly string[]): Promise<string> {
46
+ const file = join(home, name);
47
+ await mkdir(home, { recursive: true });
48
+ await writeFile(file, lines.join("\n"));
49
+ return file;
50
+ }
51
+
52
+ const PHASES = 'phases: [{ title: "Ревью" }, { title: "Фикс", detail: "чиним подтверждённое" }]';
53
+
54
+ test("the typing gives phase() the union of the declared titles, never with none declared, and no step takes a phase", () => {
55
+ const declared = scriptTyping([], [], [], [], new Map(), ["Ревью", "Фикс"]).declarations;
56
+ expect(declared).toContain('type NiwaPhase = ("Ревью") | ("Фикс");');
57
+ expect(declared).toContain("declare function phase(title: NiwaPhase): void;");
58
+ expect(declared).toContain("type NiwaCallOptions = { label?: string; reason?: string };");
59
+ expect(declared).not.toMatch(/phase\?:/);
60
+ expect(scriptTyping([], []).declarations).toContain("type NiwaPhase = never;");
61
+ });
62
+
63
+ test("check: a declared phase passes at the top and in a branch; an undeclared one, phase() with no phases and a step's phase option are type errors", async () => {
64
+ const { host, home } = await served();
65
+ const good = await scriptIn(home, "good.ts", [
66
+ `export default workflow({ ${PHASES} }, async () => {`,
67
+ ' phase("Ревью");',
68
+ " await now();",
69
+ ' await parallel([async () => { phase("Фикс"); await now(); }, async () => { await now(); }]);',
70
+ "});",
71
+ ]);
72
+ const report = await host.call(workflowCheck, { file: good });
73
+ expect(report.errors).toEqual([]);
74
+ expect(report.phases).toEqual([{ title: "Ревью" }, { title: "Фикс", detail: "чиним подтверждённое" }]);
75
+
76
+ const undeclared = await scriptIn(home, "undeclared.ts", [`export default workflow({ ${PHASES} }, async () => {`, ' phase("Деплой");', "});"]);
77
+ expect((await host.call(workflowCheck, { file: undeclared })).errors).toMatchObject([{ line: 2, code: "TS2345" }]);
78
+
79
+ const none = await scriptIn(home, "none.ts", ["export default workflow({}, async () => {", ' phase("Ревью");', "});"]);
80
+ expect((await host.call(workflowCheck, { file: none })).errors).toMatchObject([{ line: 2, code: "TS2345" }]);
81
+
82
+ const option = await scriptIn(home, "option.ts", [
83
+ `export default workflow({ ${PHASES} }, async () => {`,
84
+ ' await now({ phase: "Ревью" });',
85
+ ' await ask({ phase: "Ревью" }, "look");',
86
+ "});",
87
+ ]);
88
+ expect((await host.call(workflowCheck, { file: option })).errors).toMatchObject([
89
+ { line: 2, code: expect.stringMatching(/^TS/) },
90
+ { line: 3, code: expect.stringMatching(/^TS/) },
91
+ ]);
92
+ }, 30_000);
93
+
94
+ test("check: phases with a repeated or empty title, or not written as a literal, are an error at the phases", async () => {
95
+ const { host, home } = await served();
96
+ const twice = await scriptIn(home, "twice.ts", ['export default workflow({ phases: [{ title: "A" }, { title: "A" }] }, async () => {});']);
97
+ const twiceReport = await host.call(workflowCheck, { file: twice });
98
+ expect(twiceReport.ok).toBe(false);
99
+ expect(twiceReport.errors).toEqual([{ file: twice, line: 1, column: 35, code: "phases", message: expect.stringContaining('the phase "A" is declared twice') }]);
100
+
101
+ const empty = await scriptIn(home, "empty.ts", ['export default workflow({ phases: [{ title: " " }] }, async () => {});']);
102
+ expect((await host.call(workflowCheck, { file: empty })).errors).toMatchObject([{ code: "phases", message: expect.stringContaining("a phase has a title") }]);
103
+
104
+ const computed = await scriptIn(home, "computed.ts", ['const titles = [{ title: "A" }];', "export default workflow({ phases: titles }, async () => {});"]);
105
+ expect((await host.call(workflowCheck, { file: computed })).errors).toMatchObject([{ line: 2, code: "phases", message: expect.stringContaining("written in the declaration") }]);
106
+ }, 30_000);
107
+
108
+ /** The records of a type the host wrote. */
109
+ async function recordsOf(host: Host, type: string): Promise<StoredRecord[]> {
110
+ return (await host.records.read()).filter((row) => row.type === type);
111
+ }
112
+
113
+ test("the requested plan is all ahead before a start and stays authoritative after it", () => {
114
+ const run = RunId.parse("run-000001");
115
+ const origin = { run, args: null, file: "/script.ts" };
116
+ const rows: StoredRecord[] = [];
117
+ const write = (type: StoredRecord["type"], data: unknown) => {
118
+ const id = recordId("phase-test-" + String(rows.length + 1));
119
+ rows.push({ id, type, data, seq: seq(rows.length + 1), at: 1_700_000_000_000 as StoredRecord["at"], stream: streamId("main"), schema: 1, actor: { kind: "host" }, cause: null, root: id });
120
+ };
121
+ const journal = {
122
+ find: ({ type, field, equals, after = seq(0) }) => rows.filter((row) =>
123
+ row.type === type && row.seq > after && (field === undefined || (row.data as Record<string, unknown>)[field] === equals)),
124
+ since: () => [],
125
+ } satisfies Pick<JournalReader, "find" | "since"> as JournalReader;
126
+
127
+ write(RunRequested.name, origin);
128
+ expect(statusOf(journal, run).phases).toBeUndefined();
129
+ write(RunStarted.name, { ...origin, phases: [{ title: "Old plan" }] });
130
+ expect(statusOf(journal, run).phases).toEqual([{ title: "Old plan", state: "ahead" }]);
131
+
132
+ const plan = [{ title: "Read" }, { title: "Review", detail: "revised plan" }];
133
+ const ahead = plan.map((phase) => ({ ...phase, state: "ahead" }));
134
+ write(RunRequested.name, { ...origin, execution: run + "/revision", phases: plan });
135
+ expect(statusOf(journal, run)).toMatchObject({ phases: ahead, currentPhases: [] });
136
+ const inspection = inspectRun(journal, run);
137
+ expect(inspection?.origin.startedAt).toBeUndefined();
138
+ expect(inspection?.phases).toEqual(ahead.map((phase) => ({ ...phase, steps: [] })));
139
+ expect(runEntry(journal, run).phases).toEqual(ahead);
140
+
141
+ // The file might no longer be readable or might have changed since the request.
142
+ write(RunStarted.name, { ...origin, phases: [{ title: "Changed on disk" }] });
143
+ expect(statusOf(journal, run).phases).toEqual(ahead);
144
+ });
145
+
146
+ test("phases at the top go one after another: each entry is a record of its own, and each step is in the phase it began in", async () => {
147
+ const { host, home } = await served();
148
+ const file = await scriptIn(home, "plan.ts", [
149
+ 'export default workflow({ phases: [{ title: "Ревью" }, { title: "Фикс", detail: "чиним" }, { title: "Отчёт" }] }, async () => {',
150
+ ' await now({ label: "start" });',
151
+ ' phase("Ревью");',
152
+ ' await now({ label: "a" });',
153
+ ' phase("Фикс");',
154
+ ' await sleep("2h", { label: "nap" });',
155
+ "});",
156
+ ]);
157
+ const { run } = await host.call(workflowStart, { file });
158
+ const [requested] = await recordsOf(host, RunRequested.name);
159
+ expect(RunRequested.schema.parse(requested?.data).phases).toEqual([
160
+ { title: "Ревью" }, { title: "Фикс", detail: "чиним" }, { title: "Отчёт" },
161
+ ]);
162
+ // Entering a phase precedes the first step in it. Wait until that step is visible in the plan.
163
+ await eventually(async () => {
164
+ const { phases } = await host.call(workflowInspect, { run });
165
+ return phases.some(phase => phase.steps.some(step => step.key === "label:nap"));
166
+ }, 15_000, "the plan should show the nap step");
167
+
168
+ const entered = await recordsOf(host, PhaseEntered.name);
169
+ expect(entered.map((row) => row.data)).toEqual([
170
+ { run, branch: "", phase: "Ревью" },
171
+ { run, branch: "", phase: "Фикс" },
172
+ ]);
173
+ expect(entered.map((row) => String(row.id).split("/emit/").at(-1))).toEqual(["phase-entered:script:1", "phase-entered:script:2"]);
174
+ expect((await recordsOf(host, StepPhase.name)).map((row) => row.data)).toEqual([
175
+ { run, key: "label:a", phase: "Ревью" },
176
+ { run, key: "label:nap", phase: "Фикс" },
177
+ ]);
178
+
179
+ const inspected = await host.call(workflowInspect, { run });
180
+ expect(inspected.status.currentPhases).toEqual(["Фикс"]);
181
+ expect(inspected.status.phases).toEqual([
182
+ { title: "Ревью", state: "done" },
183
+ { title: "Фикс", detail: "чиним", state: "current" },
184
+ { title: "Отчёт", state: "ahead" },
185
+ ]);
186
+ expect(inspected.steps.map((step) => step.label)).toEqual(["start"]);
187
+ expect(inspected.phases.map((phase) => [phase.title, phase.state, phase.steps.map((step) => step.label)])).toEqual([
188
+ ["Ревью", "done", ["a"]],
189
+ ["Фикс", "current", ["nap"]],
190
+ ["Отчёт", "ahead", []],
191
+ ]);
192
+ expect(inspected.phases[1]?.steps[0]).toMatchObject({ key: "label:nap", phase: "Фикс" });
193
+ const line = (await host.call(workflowRuns, {})).runs.find((item) => item.includes(run.slice(0, 8)));
194
+ expect(line).toContain("Фикс (2/3)");
195
+ }, 30_000);
196
+
197
+ test("branches of a parallel inherit the phase they were made in and change only their own: the run is in two phases at once", async () => {
198
+ const { host, home } = await served();
199
+ const file = await scriptIn(home, "branches.ts", [
200
+ 'export default workflow({ phases: [{ title: "Ревью" }, { title: "Фикс" }, { title: "Отчёт" }] }, async () => {',
201
+ ' phase("Ревью");',
202
+ " await parallel([",
203
+ ' async () => { phase("Фикс"); await sleep("2h", { label: "fixing" }); },',
204
+ ' async () => { await sleep("2h", { label: "reviewing" }); },',
205
+ " ]);",
206
+ "});",
207
+ ]);
208
+ const { run } = await host.call(workflowStart, { file });
209
+ await eventually(async () => (await host.call(workflowInspect, { run })).phases.flatMap((phase) => phase.steps).length === 2, 15_000);
210
+
211
+ const inspected = await host.call(workflowInspect, { run });
212
+ expect(inspected.status.currentPhases).toEqual(["Ревью", "Фикс"]);
213
+ expect(inspected.status.phases?.map((phase) => phase.state)).toEqual(["current", "current", "ahead"]);
214
+ expect(inspected.phases.map((phase) => phase.steps.map((step) => step.label))).toEqual([["reviewing"], ["fixing"], []]);
215
+ // The branch that changed its phase wrote it under its own path; the one that did not is in the phase it was made in.
216
+ expect((await recordsOf(host, PhaseEntered.name)).map((row) => [String(row.id).split("/emit/").at(-1), (row.data as { phase: string }).phase])).toEqual(
217
+ expect.arrayContaining([
218
+ ["phase-entered:script:1", "Ревью"],
219
+ ["phase-entered:p1.0:0", "Ревью"],
220
+ ["phase-entered:p1.0:1", "Фикс"],
221
+ ["phase-entered:p1.1:0", "Ревью"],
222
+ ]),
223
+ );
224
+ const line = (await host.call(workflowRuns, {})).runs.find((item) => item.includes(run.slice(0, 8)));
225
+ expect(line).toContain("Ревью (1/3), Фикс (2/3)");
226
+ }, 30_000);
227
+
228
+ test("a phase a branch entered and ended is ahead while another branch has not reached it; after the join the script's phases go on", async () => {
229
+ const { host, home } = await served();
230
+ const file = await scriptIn(home, "behind.ts", [
231
+ 'export default workflow({ phases: [{ title: "Ревью" }, { title: "Фикс" }, { title: "Отчёт" }] }, async () => {',
232
+ ' phase("Ревью");',
233
+ " let fixed = () => {};",
234
+ " const ended = new Promise<void>((resolve) => { fixed = resolve; });",
235
+ " await parallel([",
236
+ ' async () => { phase("Фикс"); await now({ label: "fixed" }); fixed(); },',
237
+ ' async () => { await ended; await now({ label: "reviewed" }); await wait("test.go", { label: "reviewing" }); },',
238
+ " ]);",
239
+ ' phase("Отчёт");',
240
+ ' await sleep("2h", { label: "report" });',
241
+ "});",
242
+ ]);
243
+ const { run } = await host.call(workflowStart, { file });
244
+ await eventually(async () => (await recordsOf(host, PhaseLeft.name)).length === 1, 15_000);
245
+ let status: RunStatus = (await host.call(workflowInspect, { run })).status;
246
+ expect(status.currentPhases).toEqual(["Ревью"]);
247
+ expect(status.phases?.map((phase) => phase.state)).toEqual(["current", "ahead", "ahead"]);
248
+
249
+ // The other branch can leave before the waiter installs its intent. Send the live event only once it is listening.
250
+ await eventually(async () => (await host.call(workflowInspect, { run })).phases.some(p => p.steps.some(s => s.waitEvent === "test.go")), 15_000);
251
+ await host.emit(Go, {});
252
+ await eventually(async () => (await host.call(workflowInspect, { run })).status.currentPhases?.[0] === "Отчёт", 15_000);
253
+ status = (await host.call(workflowInspect, { run })).status;
254
+ expect(status.currentPhases).toEqual(["Отчёт"]);
255
+ expect(status.phases?.map((phase) => phase.state)).toEqual(["done", "done", "current"]);
256
+ expect((await recordsOf(host, PhaseLeft.name)).map((row) => (row.data as { branch: string }).branch).sort()).toEqual(["p1.0", "p1.1"]);
257
+ }, 30_000);
258
+
259
+ test("a run whose script declares no phases has no plan, and phase() in it is an error of the script", async () => {
260
+ const { host, home } = await served();
261
+ const file = await scriptIn(home, "plain.ts", ["export default workflow({}, async () => {", " await now();", "});"]);
262
+ const { run } = await host.call(workflowStart, { file });
263
+ const status = await host.call(workflowWait, { run, timeoutMs: 15_000 });
264
+ expect(status.state).toBe("finished");
265
+ expect(status.phases).toBeUndefined();
266
+ expect(status.currentPhases).toBeUndefined();
267
+ const inspected = await host.call(workflowInspect, { run });
268
+ expect(inspected.phases).toEqual([]);
269
+ expect(inspected.steps).toHaveLength(1);
270
+
271
+ const named = await scriptIn(home, "named.js", ["export default workflow({}, async () => {", ' phase("Ревью");', "});"]);
272
+ const paused = await host.call(workflowWait, { run: (await host.call(workflowStart, { file: named })).run, timeoutMs: 15_000 });
273
+ expect(paused.state).toBe("paused");
274
+ expect(paused.reason).toEndWith('phase("Ревью"): the script declares no phases: declare them in workflow({ phases })');
275
+ }, 30_000);
276
+
277
+ test("phase() with an undeclared title fails where it is named, and the run stops in the phase before it", async () => {
278
+ const { host, home } = await served();
279
+ // A JS script without @ts-check is not type-checked: the child is what holds the title to the declared ones.
280
+ const file = await scriptIn(home, "wrong.js", [
281
+ `export default workflow({ ${PHASES} }, async () => {`,
282
+ ' phase("Ревью");',
283
+ ' await now({ label: "first" });',
284
+ ' phase("Деплой");',
285
+ ' await now({ label: "second" });',
286
+ "});",
287
+ ]);
288
+ const { run } = await host.call(workflowStart, { file });
289
+ const status = await host.call(workflowWait, { run, timeoutMs: 15_000 });
290
+ expect(status.state).toBe("paused");
291
+ expect(status.reason).toEndWith('phase("Деплой"): the script does not declare it: it declares "Ревью", "Фикс"');
292
+ expect(status.phases).toEqual([
293
+ { title: "Ревью", state: "current" },
294
+ { title: "Фикс", detail: "чиним подтверждённое", state: "ahead" },
295
+ ]);
296
+ const steps = (await host.call(workflowInspect, { run })).phases.flatMap((phase) => phase.steps);
297
+ expect(steps.map((step) => step.label)).toEqual(["first"]);
298
+ }, 30_000);
299
+
300
+ test("a finished run has done every phase it entered; a phase it never entered stays ahead", async () => {
301
+ const { host, home } = await served();
302
+ const file = await scriptIn(home, "done.ts", [
303
+ 'export default workflow({ phases: [{ title: "A" }, { title: "B" }, { title: "C" }] }, async () => {',
304
+ ' phase("A");',
305
+ ' phase("B");',
306
+ " await now();",
307
+ "});",
308
+ ]);
309
+ const { run } = await host.call(workflowStart, { file });
310
+ const status = await host.call(workflowWait, { run, timeoutMs: 15_000 });
311
+ expect(status.state).toBe("finished");
312
+ expect(status.currentPhases).toEqual([]);
313
+ expect(status.phases?.map((phase) => phase.state)).toEqual(["done", "done", "ahead"]);
314
+ }, 30_000);
315
+
316
+ test("the declared phases are on the registered version: workflow.get and workflow.list show them", async () => {
317
+ const { host, home } = await served();
318
+ const file = await scriptIn(home, "pr.ts", [
319
+ `export default workflow({ description: "Ревью PR и фикс находок", ${PHASES} }, async () => {`,
320
+ ' phase("Ревью");',
321
+ " await now();",
322
+ "});",
323
+ ]);
324
+ const { id } = await host.call(workflowRegister, { file });
325
+ const phases = [{ title: "Ревью" }, { title: "Фикс", detail: "чиним подтверждённое" }];
326
+ expect((await host.call(workflowGet, { id })).versions[0]?.phases).toEqual(phases);
327
+ expect((await host.call(workflowList, {})).items.find((item) => item.id === id)?.phases).toEqual(phases);
328
+ // A run of the registered workflow shows the same plan.
329
+ const { run } = await host.call(workflowStart, { id });
330
+ const status = await host.call(workflowWait, { run, timeoutMs: 15_000 });
331
+ expect(status.phases?.map((phase) => [phase.title, phase.state])).toEqual([["Ревью", "done"], ["Фикс", "ahead"]]);
332
+ }, 30_000);
333
+
334
+ test("an explicit version and its subscription keep their own plan when a new version is registered", async () => {
335
+ const { host, home } = await served();
336
+ const name = "subscribed.ts";
337
+ const file = await scriptIn(home, name, [
338
+ 'export default workflow({ description: "On Go", on: ["test.go"], phases: [{ title: "Before", detail: "pinned" }] }, async () => {});',
339
+ ]);
340
+ const { id, version } = await host.call(workflowRegister, { file });
341
+ const installation = await host.call(workflowInstall, { id, description: "Go from first version" });
342
+ await scriptIn(home, name, [
343
+ 'export default workflow({ description: "On Go", on: ["test.go"], phases: [{ title: "After" }] }, async () => {});',
344
+ ]);
345
+ const newer = await host.call(workflowRegister, { id, file });
346
+ const manual = await host.call(workflowStart, { id, version });
347
+ const latest = await host.call(workflowStart, { id });
348
+ await host.emit(Go, {});
349
+ const requests = async () => (await recordsOf(host, RunRequested.name)).map((row) => RunRequested.schema.parse(row.data));
350
+ await eventually(async () => (await requests()).some((row) => row.installation === installation.id), 15_000, "the subscription should request a run");
351
+ const recorded = await requests();
352
+ const before = [{ title: "Before", detail: "pinned" }];
353
+ expect(recorded.find((row) => row.run === manual.run)).toMatchObject({ version, phases: before });
354
+ expect(recorded.find((row) => row.run === latest.run)).toMatchObject({ version: newer.version, phases: [{ title: "After" }] });
355
+ expect(recorded.find((row) => row.installation === installation.id)).toMatchObject({ version, phases: before });
356
+ }, 30_000);
357
+
358
+ test("resume and revise record the declaration from the file chosen for each new execution", async () => {
359
+ const { host, home } = await served();
360
+ const file = await scriptIn(home, "original.ts", [
361
+ 'export default workflow({ phases: [{ title: "Original" }] }, async () => {});',
362
+ ]);
363
+ const { run } = await host.call(workflowStart, { file });
364
+ expect((await host.call(workflowWait, { run, timeoutMs: 15_000 })).state).toBe("finished");
365
+ await scriptIn(home, "original.ts", [
366
+ 'export default workflow({ phases: [{ title: "Edited", detail: "same file" }] }, async () => {});',
367
+ ]);
368
+ await host.call(workflowResume, { run });
369
+ expect((await host.call(workflowWait, { run, timeoutMs: 15_000 })).state).toBe("finished");
370
+ const replacement = await scriptIn(home, "replacement.ts", [
371
+ 'export default workflow({ phases: [{ title: "Replacement" }] }, async () => {});',
372
+ ]);
373
+ await host.call(workflowRevise, { run, file: replacement });
374
+ expect((await recordsOf(host, RunRequested.name)).map((row) => RunRequested.schema.parse(row.data))).toMatchObject([
375
+ { run, file, phases: [{ title: "Original" }] },
376
+ { run, file, phases: [{ title: "Edited", detail: "same file" }] },
377
+ { run, file: replacement, phases: [{ title: "Replacement" }] },
378
+ ]);
379
+ }, 30_000);
380
+
381
+ test("the phases of branches survive a kill of the host: the replay writes the same records, and the run is in the same phases", async () => {
382
+ const home = await tempHome();
383
+ homes.push(home);
384
+ const file = join(home.path, "replay.js");
385
+ await writeFile(
386
+ file,
387
+ [
388
+ 'export default workflow({ phases: [{ title: "Ревью" }, { title: "Фикс" }, { title: "Отчёт" }], uses: ["branches.agent"], output: z.json() }, async () => {',
389
+ ' phase("Ревью");',
390
+ " const both = await parallel([",
391
+ ' async () => { phase("Фикс"); return ask({}, "b1"); },',
392
+ ' async () => { await ask({}, "c1"); return ask({}, "c2"); },',
393
+ " ]);",
394
+ ' phase("Отчёт");',
395
+ " return both;",
396
+ "});",
397
+ ].join("\n"),
398
+ );
399
+ let first: ReturnType<typeof spawnHost> | undefined = spawnHost(fileURLToPath(new URL("./fixtures/branches-host.ts", import.meta.url)), home.path);
400
+ let second: ReturnType<typeof spawnHost> | undefined;
401
+ let observer: Awaited<ReturnType<typeof watch>> | undefined;
402
+ try {
403
+ await first.ready();
404
+ observer = await watch(home.path);
405
+ const seen = observer.seen;
406
+ const client = await connectAsOwner(home.path);
407
+ const { run } = (await client.call("workflow.start" as ActionName, { file } as never)) as { run: string };
408
+ const statusOf = async (): Promise<RunStatus> => (await client.call("workflow.wait" as ActionName, { run, timeoutMs: 100 } as never)) as RunStatus;
409
+ const calls = counter(home.path, "branches.agent");
410
+ gate(home.path, "branches.gate.c1").open();
411
+ // b1 and c2 are in flight: one branch in Фикс, the other still in Ревью.
412
+ await eventually(() => calls.count() === 3, 20_000);
413
+ await eventually(async () => (await statusOf()).currentPhases?.join() === "Ревью,Фикс", 20_000);
414
+ const invocationOf = (row: StoredRecord): string => (row.actor.kind === "handler" ? String(row.actor.invocation) : "");
415
+ const before = new Set(seen.filter((row) => row.type === PhaseEntered.name).map(invocationOf));
416
+
417
+ await first.kill();
418
+ first = undefined;
419
+ await client.close().catch(() => {});
420
+ second = spawnHost(fileURLToPath(new URL("./fixtures/branches-host.ts", import.meta.url)), home.path);
421
+ await second.ready();
422
+ const again = await connectAsOwner(home.path);
423
+ const statusAgain = async (): Promise<RunStatus> => (await again.call("workflow.wait" as ActionName, { run, timeoutMs: 100 } as never)) as RunStatus;
424
+ // The replay ran: b1 and c2 were in flight at the kill, so they are made again; c1 is answered from the journal.
425
+ await eventually(() => calls.count() === 5, 20_000);
426
+ await eventually(async () => (await statusAgain()).currentPhases?.join() === "Ревью,Фикс", 20_000);
427
+
428
+ gate(home.path, "branches.gate.b1").open();
429
+ gate(home.path, "branches.gate.c2").open();
430
+ const finished = (await again.call("workflow.wait" as ActionName, { run, timeoutMs: 20_000 } as never)) as RunStatus;
431
+ expect(finished.state).toBe("finished");
432
+ expect(finished.phases?.map((phase) => phase.state)).toEqual(["done", "done", "done"]);
433
+ // The replay wrote no record of a phase twice: each key once, in the invocation the run had before the kill.
434
+ const keysOf = (type: string): string[] => seen.filter((row) => row.type === type).map((row) => String(row.id).split("/emit/").at(-1) ?? "");
435
+ await eventually(() => keysOf(PhaseLeft.name).length === 2, 10_000);
436
+ expect(keysOf(PhaseEntered.name).sort()).toEqual(["phase-entered:p1.0:0", "phase-entered:p1.0:1", "phase-entered:p1.1:0", "phase-entered:script:1", "phase-entered:script:2"]);
437
+ expect(keysOf(PhaseLeft.name).sort()).toEqual(["phase-left:p1.0", "phase-left:p1.1"]);
438
+ expect(new Set(seen.filter((row) => row.type === PhaseEntered.name).map(invocationOf))).toEqual(before);
439
+ await again.close().catch(() => {});
440
+ } finally {
441
+ await observer?.stop();
442
+ await first?.kill().catch(() => {});
443
+ await second?.kill().catch(() => {});
444
+ }
445
+ }, 90_000);
@@ -0,0 +1,59 @@
1
+ // A script imports the query builders and the helpers a plugin gives scripts by the name of the
2
+ // plugin's package: `@niwa-labs/tasks/records`, `@niwa-labs/history/flow`. A stored copy finds
3
+ // them where it finds niwa's packages, and a script process in a box may read them.
4
+
5
+ import { afterEach, expect, test } from "bun:test";
6
+ import { realpathSync } from "node:fs";
7
+ import { mkdir, symlink, writeFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+
10
+ import { createNiwa, requests, tempHome, timers } from "@niwa-labs/testing";
11
+ import type { Host } from "@niwa-labs/testing";
12
+
13
+ import { readableRoots } from "../src/installation.ts";
14
+ import { workflow, workflowCheck, workflowRegister, workflowStart, workflowWait } from "../src/index.ts";
15
+
16
+ const homes: Array<{ cleanup(): Promise<void> }> = [];
17
+ const hosts: Host[] = [];
18
+
19
+ afterEach(async () => {
20
+ for (const host of hosts.splice(0)) await host.close().catch(() => {});
21
+ for (const home of homes.splice(0)) await home.cleanup();
22
+ }, 60_000);
23
+
24
+ const SCRIPT = [
25
+ 'import { taskDone } from "@niwa-labs/tasks/records";',
26
+ 'import { sessionEnded } from "@niwa-labs/history/records";',
27
+ 'import { untilSessionEnded } from "@niwa-labs/history/flow";',
28
+ 'export default workflow({ description: "Name the end of a task and of a session", output: z.json() }, async (): Promise<any> => {',
29
+ ' const task = taskDone("task-3fa9c2");',
30
+ " return { task: [task.types[0].name, task.filter], builders: [typeof sessionEnded, typeof untilSessionEnded] };",
31
+ "});",
32
+ ].join("\n");
33
+
34
+ test("a stored script imports the query builders and helpers of tasks and history by name", async () => {
35
+ const temp = await tempHome();
36
+ homes.push(temp);
37
+ const host = createNiwa({ home: temp.path });
38
+ host.use(requests(), timers([]), workflow());
39
+ await host.serve();
40
+ hosts.push(host);
41
+ const src = join(realpathSync(temp.path), "src");
42
+ await mkdir(src, { recursive: true });
43
+ await symlink(realpathSync(join(import.meta.dir, "..", "node_modules")), join(src, "node_modules"), "dir");
44
+ const file = join(src, "ends.ts");
45
+ await writeFile(file, SCRIPT);
46
+ expect((await host.call(workflowCheck, { file })).errors).toEqual([]);
47
+ const { id } = await host.call(workflowRegister, { file });
48
+ const { run } = await host.call(workflowStart, { id });
49
+ const outcome = (await host.call(workflowWait, { run, timeoutMs: 30_000 })).outcome;
50
+ expect(outcome).toEqual({
51
+ status: "done",
52
+ result: { task: ["task.done", { task: "task-3fa9c2" }], builders: ["function", "function"] },
53
+ });
54
+ }, 60_000);
55
+
56
+ test("a script process in a box may read the tasks and history packages", () => {
57
+ const roots = readableRoots();
58
+ for (const name of ["tasks", "history"]) expect(roots).toContain(realpathSync(join(import.meta.dir, "..", "..", name)));
59
+ });