@psimona/darkf 0.0.0-stage → 0.3.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 (44) hide show
  1. package/README.md +28 -2
  2. package/bunfig.toml +13 -0
  3. package/examples/article-classifier/data/articles.ts +38 -0
  4. package/examples/article-classifier/scripts/next.ts +7 -0
  5. package/examples/article-classifier/scripts/queue.ts +33 -0
  6. package/examples/article-classifier/scripts/record.ts +9 -0
  7. package/examples/article-classifier/workflow.ts +44 -0
  8. package/examples/haiku-commit/scripts/check.ts +24 -0
  9. package/examples/haiku-commit/workflow.ts +28 -0
  10. package/examples/haiku-readme/scripts/test.ts +13 -0
  11. package/examples/haiku-readme/scripts/write.ts +10 -0
  12. package/examples/haiku-readme/workflow.ts +41 -0
  13. package/examples/task-queue/scripts/next.ts +20 -0
  14. package/examples/task-queue/scripts/record.ts +20 -0
  15. package/examples/task-queue/supervise.ts +57 -0
  16. package/examples/task-queue/workflow.ts +33 -0
  17. package/package.json +30 -4
  18. package/src/cli/detached.test.ts +557 -0
  19. package/src/cli/index.ts +1012 -0
  20. package/src/core/graph.test.ts +172 -0
  21. package/src/core/graph.ts +148 -0
  22. package/src/core/index.ts +4 -0
  23. package/src/core/journal.ts +21 -0
  24. package/src/core/mermaid.test.ts +34 -0
  25. package/src/core/mermaid.ts +95 -0
  26. package/src/core/types.ts +279 -0
  27. package/src/engine/eventLog.ts +17 -0
  28. package/src/engine/index.ts +2 -0
  29. package/src/engine/run.test.ts +1068 -0
  30. package/src/engine/run.ts +359 -0
  31. package/src/exports.ts +2 -0
  32. package/src/kit/agents/claude-code.test.ts +37 -0
  33. package/src/kit/agents/claude-code.ts +180 -0
  34. package/src/kit/agents/handoff.test.ts +128 -0
  35. package/src/kit/agents/handoff.ts +69 -0
  36. package/src/kit/agents/opencode.test.ts +136 -0
  37. package/src/kit/agents/opencode.ts +327 -0
  38. package/src/kit/registry.test.ts +386 -0
  39. package/src/kit/registry.ts +296 -0
  40. package/src/kit/status.test.ts +423 -0
  41. package/src/kit/status.ts +282 -0
  42. package/tsconfig.json +4 -0
  43. package/workflows/series-ordering/scripts/verify.ts +18 -0
  44. package/workflows/series-ordering/workflow.ts +79 -0
@@ -0,0 +1,557 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { randomUUID } from "node:crypto";
3
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { parseEventLog } from "../core/index.ts";
7
+ import {
8
+ isPidAlive,
9
+ journalPathFor,
10
+ journalTerminal,
11
+ listEntries,
12
+ readEntry,
13
+ readJournalText,
14
+ SCHEMA_VERSION,
15
+ writeEntry,
16
+ } from "../kit/registry.ts";
17
+
18
+ // --- paths (the CLI entry is spawned as a subprocess; never imported here) ---
19
+ const pkgDir = resolve(import.meta.dir, "..", "..");
20
+ const repoRoot = resolve(pkgDir, "..");
21
+ const indexTs = join(pkgDir, "src", "cli", "index.ts");
22
+ const haikuExample = join(pkgDir, "examples", "haiku-readme");
23
+
24
+ const roots: string[] = [];
25
+ const workerPids: number[] = [];
26
+ afterAll(() => {
27
+ for (const pid of workerPids) {
28
+ try {
29
+ process.kill(pid, "SIGKILL");
30
+ } catch {
31
+ // already gone
32
+ }
33
+ }
34
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
35
+ });
36
+
37
+ function makeProjectRoot(): string {
38
+ const root = mkdtempSync(join(tmpdir(), "darkf-cli-int-"));
39
+ roots.push(root);
40
+ mkdirSync(join(root, ".git"));
41
+ mkdirSync(join(root, "node_modules", "@psimona"), { recursive: true });
42
+ symlinkSync(join(repoRoot, "darkf"), join(root, "node_modules", "@psimona", "darkf"));
43
+ return root;
44
+ }
45
+
46
+ function writeFixture(root: string, name: string, files: Record<string, string>): string {
47
+ const dir = join(root, name);
48
+ for (const [rel, content] of Object.entries(files)) {
49
+ const p = join(dir, rel);
50
+ mkdirSync(dirname(p), { recursive: true });
51
+ writeFileSync(p, content);
52
+ }
53
+ return dir;
54
+ }
55
+
56
+ async function runCli(
57
+ args: string[],
58
+ cwd: string,
59
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
60
+ const proc = Bun.spawn([process.execPath, indexTs, ...args], {
61
+ cwd,
62
+ stdout: "pipe",
63
+ stderr: "pipe",
64
+ });
65
+ const [stdout, stderr, code] = await Promise.all([
66
+ new Response(proc.stdout).text(),
67
+ new Response(proc.stderr).text(),
68
+ proc.exited,
69
+ ]);
70
+ return { code, stdout, stderr };
71
+ }
72
+
73
+ function startRun(root: string, dir: string): Promise<{ runId: string; pid: number }> {
74
+ return runCli(["start", dir], root).then((res) => {
75
+ expect(res.code, `start ${dir} should exit 0, got ${res.code}: ${res.stderr}`).toBe(0);
76
+ const parsed = JSON.parse(res.stdout.trim()) as { runId: string; pid: number };
77
+ workerPids.push(parsed.pid);
78
+ return parsed;
79
+ });
80
+ }
81
+
82
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
83
+
84
+ function journalLineCount(root: string, runId: string): number {
85
+ const entry = readEntry(root, runId);
86
+ if (!entry) return 0;
87
+ return parseEventLog(readJournalText(journalPathFor(entry))).length;
88
+ }
89
+ function journalTerminalState(
90
+ root: string,
91
+ runId: string,
92
+ ): "succeeded" | "failed" | "crashed" | undefined {
93
+ const entry = readEntry(root, runId);
94
+ if (!entry) return undefined;
95
+ return journalTerminal(readJournalText(journalPathFor(entry)));
96
+ }
97
+ async function waitForTerminal(root: string, runId: string, timeoutMs: number): Promise<string> {
98
+ const deadline = Date.now() + timeoutMs;
99
+ while (Date.now() < deadline) {
100
+ const term = journalTerminalState(root, runId);
101
+ if (term) return term;
102
+ await sleep(50);
103
+ }
104
+ throw new Error(`run ${runId} did not reach a terminal state within ${timeoutMs}ms`);
105
+ }
106
+ async function waitFor(fn: () => boolean, timeoutMs: number, what: string): Promise<void> {
107
+ const deadline = Date.now() + timeoutMs;
108
+ while (Date.now() < deadline) {
109
+ if (fn()) return;
110
+ await sleep(25);
111
+ }
112
+ throw new Error(`timed out waiting for: ${what}`);
113
+ }
114
+ function killWorker(pid: number): void {
115
+ try {
116
+ process.kill(pid, "SIGKILL");
117
+ } catch {
118
+ // already gone
119
+ }
120
+ }
121
+
122
+ // --- fixtures (all use a stub agentRunner / no LLM) ---
123
+ const SUCCEED: Record<string, string> = {
124
+ "workflow.ts": `import { type AgentRunner, EXIT, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
125
+ export const agentRunner: AgentRunner = {
126
+ async run(id) {
127
+ if (id === "Plan") return { event: "approved" };
128
+ return { event: "done" };
129
+ },
130
+ };
131
+ export const workflow: WorkflowDef = {
132
+ initial: "Plan",
133
+ states: {
134
+ Plan: { type: "agent", prompt: "plan", on: { approved: "Implement" } },
135
+ Implement: {
136
+ initial: "Write",
137
+ states: {
138
+ Write: { type: "script", file: "write.ts", next: "Test" },
139
+ Test: { type: "script", file: "test.ts", on: { passed: "Review" } },
140
+ },
141
+ },
142
+ Review: { type: "agent", prompt: "review", on: { done: EXIT } },
143
+ },
144
+ };
145
+ `,
146
+ "scripts/write.ts": `import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
147
+ export default async function write(): Promise<NodeResult> {
148
+ await new Promise((r) => setTimeout(r, 600));
149
+ return {};
150
+ }
151
+ `,
152
+ "scripts/test.ts": `import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
153
+ export default function test(): NodeResult {
154
+ return { event: "passed" };
155
+ }
156
+ `,
157
+ };
158
+ const CRASH: Record<string, string> = {
159
+ "workflow.ts": `import { EXIT, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
160
+ export const workflow: WorkflowDef = {
161
+ initial: "Warmup",
162
+ states: {
163
+ Warmup: { type: "script", file: "warmup.ts", next: "Boom" },
164
+ Boom: { type: "script", file: "does-not-exist.ts", on: { ok: EXIT } },
165
+ },
166
+ };
167
+ `,
168
+ "scripts/warmup.ts": `import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
169
+ export default async function warmup(): Promise<NodeResult> {
170
+ await new Promise((r) => setTimeout(r, 600));
171
+ return {};
172
+ }
173
+ `,
174
+ };
175
+ const SLOW: Record<string, string> = {
176
+ "workflow.ts": `import { EXIT, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
177
+ export const workflow: WorkflowDef = {
178
+ initial: "S",
179
+ states: { S: { type: "script", file: "sleep.ts", on: { ok: EXIT } } },
180
+ };
181
+ `,
182
+ "scripts/sleep.ts": `import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
183
+ export default async function sleep(): Promise<NodeResult> {
184
+ await new Promise((r) => setTimeout(r, 4000));
185
+ return { event: "ok", output: "woke" };
186
+ }
187
+ `,
188
+ };
189
+ const BROKEN: Record<string, string> = {
190
+ "workflow.ts": `throw new Error("boom at module load");
191
+ export const workflow = null as never;
192
+ `,
193
+ };
194
+
195
+ // --- start ordering ---
196
+
197
+ test("start fails loudly (nonzero, no fake identity) when the worker crashes on startup", async () => {
198
+ const root = makeProjectRoot();
199
+ writeFixture(root, "broken", BROKEN);
200
+
201
+ const res = await runCli(["start", "broken"], root);
202
+ expect(res.code).not.toBe(0);
203
+ expect(res.stdout.trim()).toBe(""); // no {runId,pid} printed for a confirmed-dead worker
204
+ expect(res.stderr).toContain("exited during startup");
205
+ expect(res.stderr).toContain("boom at module load"); // worker.log tail, self-documenting
206
+
207
+ // registry-lifecycle: no "running" entry is left behind — instead, a
208
+ // self-documenting "failed-start" entry carrying the same failure detail,
209
+ // so RCA never needs a foreground reproduction.
210
+ const entries = listEntries(root);
211
+ expect(entries.length).toBe(1);
212
+ expect(entries[0]?.status).toBe("failed-start");
213
+ expect(entries[0]?.startFailureDetail).toContain("boom at module load");
214
+ expect(entries[0]?.finishedAt).not.toBeNull();
215
+ expect(entries[0]?.bootId).toBeDefined();
216
+ });
217
+
218
+ test("status and monitor report failed-start for a worker that crashed before loading the workflow", async () => {
219
+ const root = makeProjectRoot();
220
+ writeFixture(root, "broken", BROKEN);
221
+ await runCli(["start", "broken"], root);
222
+ const [entry] = listEntries(root);
223
+ expect(entry).toBeDefined();
224
+ const runId = entry!.runId;
225
+
226
+ const st = await runCli(["status", "--run", runId], root);
227
+ expect(st.code).toBe(6);
228
+ expect(st.stdout).toContain("state: failed-start");
229
+ expect(st.stdout).toContain("failed-start: true");
230
+ expect(st.stdout).toContain("boom at module load");
231
+
232
+ const mon = await runCli(["monitor", "--run", runId], root);
233
+ expect(mon.code).toBe(5);
234
+ expect(mon.stdout).toContain("failed-start: true");
235
+ });
236
+
237
+ // --- succeeded (detached run that runs past the grace window) ---
238
+
239
+ test("status and monitor report succeeded for a detached run", async () => {
240
+ const root = makeProjectRoot();
241
+ writeFixture(root, "succeed", SUCCEED);
242
+ const { runId } = await startRun(root, "succeed");
243
+
244
+ // while it is still mid-run (the fixture sleeps 600ms, start returned at
245
+ // ~250ms), a bare `status` auto-resolves the single running run
246
+ const stRunning = await runCli(["status"], root);
247
+ expect(stRunning.code).toBe(3);
248
+ expect(stRunning.stdout).toContain("state: running");
249
+
250
+ expect(await waitForTerminal(root, runId, 5000)).toBe("succeeded");
251
+
252
+ const st = await runCli(["status", "--run", runId], root);
253
+ expect(st.code).toBe(0);
254
+ expect(st.stdout).toContain("state: succeeded");
255
+ expect(st.stdout).toContain(`run: ${runId}`);
256
+
257
+ const mon = await runCli(["monitor", "--run", runId], root);
258
+ expect(mon.code).toBe(0);
259
+ expect(mon.stdout).toContain("succeeded");
260
+
261
+ // once the only run has finished, a bare `status` is "nothing to monitor"
262
+ await waitFor(
263
+ () => readEntry(root, runId)?.status === "succeeded",
264
+ 3000,
265
+ "registry to cache succeeded",
266
+ );
267
+ const bare = await runCli(["status"], root);
268
+ expect(bare.code).toBe(7);
269
+ expect(bare.stdout).toContain(runId); // mentioned as the most recent finished run
270
+ });
271
+
272
+ // --- succeeded (the actual haiku-readme example, via a real worker run) ---
273
+
274
+ test("status and monitor report succeeded for a run of the haiku-readme example", async () => {
275
+ const root = makeProjectRoot();
276
+ cpSync(haikuExample, join(root, "haiku-readme"), { recursive: true });
277
+ const runId = randomUUID();
278
+ writeEntry(root, {
279
+ schemaVersion: SCHEMA_VERSION,
280
+ runId,
281
+ pid: process.pid,
282
+ // rootDir is the invocation cwd (the project root), not the workflow dir
283
+ rootDir: root,
284
+ startedAt: Date.now(),
285
+ status: "running",
286
+ finishedAt: null,
287
+ });
288
+
289
+ const worker = await runCli(["__worker", "haiku-readme", runId], root);
290
+ expect(worker.code).toBe(0);
291
+ expect(journalTerminalState(root, runId)).toBe("succeeded");
292
+
293
+ const st = await runCli(["status", "--run", runId], root);
294
+ expect(st.code).toBe(0);
295
+ expect(st.stdout).toContain("state: succeeded");
296
+
297
+ const mon = await runCli(["monitor", "--run", runId], root);
298
+ expect(mon.code).toBe(0);
299
+ expect(mon.stdout).toContain("succeeded");
300
+ });
301
+
302
+ // --- crashed ---
303
+
304
+ test("status and monitor report crashed (with reason) for a run that crashes mid-run", async () => {
305
+ const root = makeProjectRoot();
306
+ writeFixture(root, "crash", CRASH);
307
+ const { runId } = await startRun(root, "crash");
308
+ expect(await waitForTerminal(root, runId, 5000)).toBe("crashed");
309
+
310
+ const st = await runCli(["status", "--run", runId], root);
311
+ expect(st.code).toBe(1);
312
+ expect(st.stdout).toContain("state: crashed");
313
+ expect(st.stdout).toContain("runner-error");
314
+
315
+ const mon = await runCli(["monitor", "--run", runId], root);
316
+ expect(mon.code).toBe(1);
317
+ expect(mon.stdout).toContain("crashed");
318
+ expect(mon.stdout).toContain("runner-error");
319
+ });
320
+
321
+ // --- orphan (kill the worker while it is mid-run, journal has no end marker) ---
322
+
323
+ test("status and monitor report orphaned when the worker is killed mid-run", async () => {
324
+ const root = makeProjectRoot();
325
+ writeFixture(root, "slow", SLOW);
326
+ const { runId, pid } = await startRun(root, "slow");
327
+
328
+ // wait until the journal has grown past its begin marker (last line is a
329
+ // live node's running event, not an EXIT-succeeded marker)
330
+ await waitFor(
331
+ () => journalLineCount(root, runId) >= 2,
332
+ 3000,
333
+ "journal to hold begin + a running line",
334
+ );
335
+ killWorker(pid);
336
+ await waitFor(() => !isPidAlive(pid), 3000, "worker to be confirmed dead");
337
+
338
+ const st = await runCli(["status", "--run", runId], root);
339
+ expect(st.code).toBe(2);
340
+ expect(st.stdout).toContain("state: orphaned");
341
+ expect(st.stdout).toContain("orphaned: true");
342
+
343
+ const mon = await runCli(["monitor", "--run", runId], root);
344
+ expect(mon.code).toBe(2);
345
+ expect(mon.stdout).toContain("orphaned");
346
+ });
347
+
348
+ // --- host-died (registry's bootId doesn't match the current host) ---
349
+
350
+ test("status and monitor report host-died, not orphaned, when the recorded bootId doesn't match", async () => {
351
+ const root = makeProjectRoot();
352
+ writeFixture(root, "slow", SLOW);
353
+ const { runId, pid } = await startRun(root, "slow");
354
+
355
+ await waitFor(
356
+ () => journalLineCount(root, runId) >= 2,
357
+ 3000,
358
+ "journal to hold begin + a running line",
359
+ );
360
+ killWorker(pid);
361
+ await waitFor(() => !isPidAlive(pid), 3000, "worker to be confirmed dead");
362
+
363
+ // Simulate "this entry was written on a boot that's no longer current" —
364
+ // the real trigger (an actual host reboot) can't be reproduced in a test.
365
+ const entry = readEntry(root, runId)!;
366
+ writeEntry(root, { ...entry, bootId: "not-the-real-boot-id" });
367
+
368
+ const st = await runCli(["status", "--run", runId], root);
369
+ expect(st.code).toBe(5);
370
+ expect(st.stdout).toContain("state: host-died");
371
+ expect(st.stdout).toContain("host-died: true");
372
+
373
+ const mon = await runCli(["monitor", "--run", runId], root);
374
+ expect(mon.code).toBe(4);
375
+ expect(mon.stdout).toContain("host-died: true");
376
+ });
377
+
378
+ test("status still reports orphaned (not host-died) when bootId is absent (pre-this-change entry)", async () => {
379
+ const root = makeProjectRoot();
380
+ writeFixture(root, "slow", SLOW);
381
+ const { runId, pid } = await startRun(root, "slow");
382
+
383
+ await waitFor(
384
+ () => journalLineCount(root, runId) >= 2,
385
+ 3000,
386
+ "journal to hold begin + a running line",
387
+ );
388
+ killWorker(pid);
389
+ await waitFor(() => !isPidAlive(pid), 3000, "worker to be confirmed dead");
390
+
391
+ const entry = readEntry(root, runId)!;
392
+ writeEntry(root, { ...entry, bootId: undefined });
393
+
394
+ const st = await runCli(["status", "--run", runId], root);
395
+ expect(st.code).toBe(2);
396
+ expect(st.stdout).toContain("state: orphaned");
397
+ });
398
+
399
+ // --- ambiguous (two concurrent detached runs) ---
400
+
401
+ test("status and monitor are ambiguous with two concurrent detached runs, no --run", async () => {
402
+ const root = makeProjectRoot();
403
+ writeFixture(root, "slow", SLOW);
404
+ const a = await startRun(root, "slow");
405
+ const b = await startRun(root, "slow");
406
+ try {
407
+ const st = await runCli(["status"], root);
408
+ expect(st.code).toBe(5);
409
+ expect(st.stderr).toContain(a.runId);
410
+ expect(st.stderr).toContain(b.runId);
411
+
412
+ const mon = await runCli(["monitor"], root);
413
+ expect(mon.code).toBe(5);
414
+
415
+ // but --run disambiguates and resolves to a live run
416
+ const stOne = await runCli(["status", "--run", a.runId], root);
417
+ expect(stOne.code).toBe(3); // still running
418
+ } finally {
419
+ killWorker(a.pid);
420
+ killWorker(b.pid);
421
+ }
422
+ });
423
+
424
+ // --- no such run ---
425
+
426
+ test("status and monitor report no-such-run for an unknown --run", async () => {
427
+ const root = makeProjectRoot();
428
+ const st = await runCli(["status", "--run", "does-not-exist"], root);
429
+ expect(st.code).toBe(4);
430
+ expect(st.stderr).toContain("no such run");
431
+
432
+ const mon = await runCli(["monitor", "--run", "does-not-exist"], root);
433
+ expect(mon.code).toBe(4);
434
+ });
435
+
436
+ // --- nothing to monitor ---
437
+
438
+ test("status and monitor report nothing-to-monitor with zero runs", async () => {
439
+ const root = makeProjectRoot();
440
+ const st = await runCli(["status"], root);
441
+ expect(st.code).toBe(7);
442
+ expect(st.stdout).toContain("nothing to monitor");
443
+
444
+ const mon = await runCli(["monitor"], root);
445
+ expect(mon.code).toBe(7);
446
+ });
447
+
448
+ // --- workflow reference resolution: darkf/<name> ---
449
+
450
+ test("a bare name resolves against <cwd>/darkf/<name>", async () => {
451
+ const root = makeProjectRoot();
452
+ writeFixture(root, "darkf/succeed", SUCCEED);
453
+
454
+ const res = await runCli(["render", "succeed"], root);
455
+ expect(res.code).toBe(0);
456
+ expect(res.stdout).toContain("stateDiagram-v2");
457
+ });
458
+
459
+ test("darkf workflows lists workspace entries from darkf/", async () => {
460
+ const root = makeProjectRoot();
461
+ writeFixture(root, "darkf/current-style", SUCCEED);
462
+
463
+ const res = await runCli(["workflows"], root);
464
+ expect(res.code).toBe(0);
465
+ expect(res.stdout).toContain("current-style");
466
+ });
467
+
468
+ test("the old <cwd>/.darkf/workflows/<name> location is no longer resolved — removed, not kept as a fallback", async () => {
469
+ const root = makeProjectRoot();
470
+ writeFixture(root, ".darkf/workflows/legacy-style", SUCCEED);
471
+
472
+ const res = await runCli(["render", "legacy-style"], root);
473
+ expect(res.code).not.toBe(0);
474
+ expect(res.stderr).toContain("no workflow for 'legacy-style'");
475
+
476
+ const list = await runCli(["workflows"], root);
477
+ expect(list.stdout).not.toContain("legacy-style");
478
+ });
479
+
480
+ // --- start-time dirty-workflow-config guard ---
481
+
482
+ function git(args: string[], cwd: string): void {
483
+ const res = Bun.spawnSync(["git", ...args], {
484
+ cwd,
485
+ env: {
486
+ ...process.env,
487
+ GIT_AUTHOR_NAME: "t",
488
+ GIT_AUTHOR_EMAIL: "t@t",
489
+ GIT_COMMITTER_NAME: "t",
490
+ GIT_COMMITTER_EMAIL: "t@t",
491
+ },
492
+ });
493
+ if (!res.success) {
494
+ throw new Error(`git ${args.join(" ")} failed: ${new TextDecoder().decode(res.stderr)}`);
495
+ }
496
+ }
497
+
498
+ function makeRealGitRoot(): string {
499
+ const root = mkdtempSync(join(tmpdir(), "darkf-cli-git-int-"));
500
+ roots.push(root);
501
+ git(["init", "-q"], root);
502
+ mkdirSync(join(root, "node_modules", "@psimona"), { recursive: true });
503
+ symlinkSync(join(repoRoot, "darkf"), join(root, "node_modules", "@psimona", "darkf"));
504
+ return root;
505
+ }
506
+
507
+ test("start refuses to launch when darkf/ has uncommitted changes, names the files", async () => {
508
+ const root = makeRealGitRoot();
509
+ writeFixture(root, "darkf/succeed", SUCCEED);
510
+ git(["add", "-A"], root);
511
+ git(["commit", "-q", "-m", "init"], root);
512
+
513
+ // Dirty an already-committed workflow file.
514
+ writeFileSync(join(root, "darkf/succeed/workflow.ts"), "// edited, uncommitted\n");
515
+
516
+ const res = await runCli(["start", "darkf/succeed"], root);
517
+ expect(res.code).toBe(1);
518
+ expect(res.stderr).toContain("uncommitted changes");
519
+ expect(res.stderr).toContain("workflow.ts");
520
+ expect(res.stderr).toContain("--allow-dirty-workflow");
521
+ expect(listEntries(root)).toEqual([]); // refused before ever spawning a worker
522
+ });
523
+
524
+ test("--allow-dirty-workflow overrides the guard", async () => {
525
+ const root = makeRealGitRoot();
526
+ writeFixture(root, "darkf/succeed", SUCCEED);
527
+ git(["add", "-A"], root);
528
+ git(["commit", "-q", "-m", "init"], root);
529
+ writeFileSync(
530
+ join(root, "darkf/succeed/workflow.ts"),
531
+ `${SUCCEED["workflow.ts"]}\n// uncommitted edit\n`,
532
+ );
533
+
534
+ const res = await runCli(["start", "darkf/succeed", "--allow-dirty-workflow"], root);
535
+ expect(res.code).toBe(0);
536
+ const parsed = JSON.parse(res.stdout.trim()) as { runId: string; pid: number };
537
+ workerPids.push(parsed.pid);
538
+ });
539
+
540
+ // --- detached survival ---
541
+
542
+ test("the detached worker keeps running (and the journal grows) after the launcher exits", async () => {
543
+ const root = makeProjectRoot();
544
+ writeFixture(root, "slow", SLOW);
545
+ const { runId, pid } = await startRun(root, "slow"); // the `start` process has already exited here
546
+
547
+ // the launcher is gone, but the worker is still alive and past its begin marker
548
+ expect(isPidAlive(pid)).toBe(true);
549
+ await waitFor(
550
+ () => journalLineCount(root, runId) >= 2,
551
+ 3000,
552
+ "journal to grow past the begin marker",
553
+ );
554
+
555
+ // it completes on its own once the launcher is no longer around
556
+ expect(await waitForTerminal(root, runId, 8000)).toBe("succeeded");
557
+ });