@psimona/darkf 0.0.0-stage → 0.4.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 (51) 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/feedback/2026-10-30-self-update.md +29 -0
  18. package/package.json +30 -4
  19. package/src/cli/detached.test.ts +560 -0
  20. package/src/cli/index.ts +1040 -0
  21. package/src/cli/update.test.ts +486 -0
  22. package/src/cli/update.ts +191 -0
  23. package/src/core/graph.test.ts +172 -0
  24. package/src/core/graph.ts +148 -0
  25. package/src/core/index.ts +4 -0
  26. package/src/core/journal.ts +21 -0
  27. package/src/core/mermaid.test.ts +34 -0
  28. package/src/core/mermaid.ts +95 -0
  29. package/src/core/types.ts +279 -0
  30. package/src/engine/eventLog.ts +17 -0
  31. package/src/engine/index.ts +2 -0
  32. package/src/engine/run.test.ts +1068 -0
  33. package/src/engine/run.ts +359 -0
  34. package/src/exports.ts +2 -0
  35. package/src/kit/agents/claude-code.test.ts +37 -0
  36. package/src/kit/agents/claude-code.ts +180 -0
  37. package/src/kit/agents/handoff.test.ts +128 -0
  38. package/src/kit/agents/handoff.ts +69 -0
  39. package/src/kit/agents/opencode.test.ts +136 -0
  40. package/src/kit/agents/opencode.ts +327 -0
  41. package/src/kit/registry.test.ts +386 -0
  42. package/src/kit/registry.ts +296 -0
  43. package/src/kit/status.test.ts +423 -0
  44. package/src/kit/status.ts +282 -0
  45. package/tsconfig.json +4 -0
  46. package/workflows/dev-loop/scripts/begin.ts +22 -0
  47. package/workflows/dev-loop/scripts/check.ts +19 -0
  48. package/workflows/dev-loop/scripts/finish.ts +114 -0
  49. package/workflows/dev-loop/workflow.ts +135 -0
  50. package/workflows/series-ordering/scripts/verify.ts +18 -0
  51. package/workflows/series-ordering/workflow.ts +80 -0
@@ -0,0 +1,386 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { type CrashReason, EXIT, FAILED, type NodeEvent, type NodeResult } from "../core/index.ts";
6
+ import {
7
+ detectSupervisorSignal,
8
+ isPidAlive,
9
+ journalPathFor,
10
+ journalTerminal,
11
+ listEntries,
12
+ projectRoot,
13
+ type RegistryEntry,
14
+ type RunResolution,
15
+ readEntry,
16
+ resolveRun,
17
+ SCHEMA_VERSION,
18
+ writeEntry,
19
+ } from "./registry.ts";
20
+
21
+ const tmpRoot = mkdtempSync(join(tmpdir(), "darkf-registry-test-"));
22
+ afterAll(() => rmSync(tmpRoot, { recursive: true, force: true }));
23
+
24
+ // A pid that is guaranteed gone by the time the matrix runs: spawn a child,
25
+ // await its exit, reuse its (now-dead) pid.
26
+ const deadChild = Bun.spawn(["bun", "-e", "setTimeout(()=>{},20)"]);
27
+ await deadChild.exited;
28
+ const deadPid: number = deadChild.pid;
29
+ const livePid = process.pid;
30
+
31
+ let scenario = 0;
32
+ function freshRoot(): string {
33
+ const root = join(tmpRoot, `s${scenario++}`);
34
+ mkdirSync(root, { recursive: true });
35
+ return root;
36
+ }
37
+
38
+ function makeEntry(
39
+ runId: string,
40
+ pid: number,
41
+ rootDir: string,
42
+ overrides?: Partial<RegistryEntry>,
43
+ ): RegistryEntry {
44
+ return {
45
+ schemaVersion: SCHEMA_VERSION,
46
+ runId,
47
+ pid,
48
+ rootDir,
49
+ startedAt: Date.now(),
50
+ status: "running",
51
+ finishedAt: null,
52
+ ...overrides,
53
+ };
54
+ }
55
+
56
+ const R = "run-id";
57
+ function begin(seed: NodeResult = {}): NodeEvent {
58
+ return {
59
+ runId: R,
60
+ state: EXIT,
61
+ scopePath: [],
62
+ status: { phase: "succeeded", result: seed },
63
+ timestamp: 1000,
64
+ };
65
+ }
66
+ function end(final: NodeResult = {}): NodeEvent {
67
+ return {
68
+ runId: R,
69
+ state: EXIT,
70
+ scopePath: [],
71
+ status: { phase: "succeeded", result: final },
72
+ timestamp: 3000,
73
+ };
74
+ }
75
+ function running(state: string, ts: number, attempt = 1): NodeEvent {
76
+ return {
77
+ runId: R,
78
+ state,
79
+ scopePath: [],
80
+ status: { phase: "running", attempt, startedAt: ts, lastHeartbeat: ts },
81
+ timestamp: ts,
82
+ };
83
+ }
84
+ function succeeded(state: string, ts: number, result: NodeResult = {}): NodeEvent {
85
+ return { runId: R, state, scopePath: [], status: { phase: "succeeded", result }, timestamp: ts };
86
+ }
87
+ function failedEnd(result: NodeResult = {}): NodeEvent {
88
+ return {
89
+ runId: R,
90
+ state: FAILED,
91
+ scopePath: [],
92
+ status: { phase: "failed", result },
93
+ timestamp: 3000,
94
+ };
95
+ }
96
+ function crashed(state: string, ts: number, reason: CrashReason, attempt = 1): NodeEvent {
97
+ return {
98
+ runId: R,
99
+ state,
100
+ scopePath: [],
101
+ status: { phase: "crashed", reason, attempt },
102
+ timestamp: ts,
103
+ };
104
+ }
105
+ function writeJournal(rootDir: string, runId: string, events: NodeEvent[]): string {
106
+ const dir = join(rootDir, ".darkf", "run", runId);
107
+ mkdirSync(dir, { recursive: true });
108
+ const path = join(dir, "journal.jsonl");
109
+ writeFileSync(
110
+ path,
111
+ events.map((e) => JSON.stringify(e)).join("\n") + (events.length ? "\n" : ""),
112
+ );
113
+ return path;
114
+ }
115
+ // entry + journal wired together under one scenario root
116
+ function seeded(
117
+ runId: string,
118
+ pid: number,
119
+ events: NodeEvent[],
120
+ overrides?: Partial<RegistryEntry>,
121
+ ): {
122
+ root: string;
123
+ entry: RegistryEntry;
124
+ } {
125
+ const root = freshRoot();
126
+ const rootDir = join(root, "wf");
127
+ const entry = makeEntry(runId, pid, rootDir, overrides);
128
+ writeEntry(root, entry);
129
+ writeJournal(rootDir, runId, events);
130
+ return { root, entry };
131
+ }
132
+
133
+ test("projectRoot walks up to the nearest ancestor with a .git, else returns cwd", () => {
134
+ const proj = join(tmpRoot, "proj");
135
+ mkdirSync(join(proj, ".git"), { recursive: true });
136
+ const deep = join(proj, "a", "b", "c");
137
+ mkdirSync(deep, { recursive: true });
138
+ expect(projectRoot(deep)).toBe(proj);
139
+ expect(projectRoot(proj)).toBe(proj);
140
+ // no .git anywhere up from an os tmpdir path -> fall back to the given dir
141
+ const lone = join(tmpRoot, "no-git-here");
142
+ mkdirSync(lone, { recursive: true });
143
+ expect(projectRoot(lone)).toBe(lone);
144
+ });
145
+
146
+ test("registry entry round-trips through write/read, listEntries includes it", () => {
147
+ const root = freshRoot();
148
+ const entry = makeEntry("r1", livePid, "/some/root", { message: "hello" });
149
+ writeEntry(root, entry);
150
+ expect(readEntry(root, "r1")).toEqual(entry);
151
+ expect(listEntries(root)).toEqual([entry]);
152
+ // an entry without a message round-trips with message undefined, not ""
153
+ writeEntry(root, makeEntry("r2", livePid, "/r2"));
154
+ const r2 = readEntry(root, "r2");
155
+ expect(r2?.message).toBeUndefined();
156
+ expect(
157
+ listEntries(root)
158
+ .map((e) => e.runId)
159
+ .sort(),
160
+ ).toEqual(["r1", "r2"]);
161
+ });
162
+
163
+ test("readEntry returns undefined for a missing runId", () => {
164
+ const root = freshRoot();
165
+ writeEntry(root, makeEntry("present", livePid, "/p"));
166
+ expect(readEntry(root, "absent")).toBeUndefined();
167
+ });
168
+
169
+ test("unknown schemaVersion is skipped with a warning, not a crash", () => {
170
+ const root = freshRoot();
171
+ const dir = join(root, ".darkf", "registry");
172
+ mkdirSync(dir, { recursive: true });
173
+ writeFileSync(
174
+ join(dir, "old.json"),
175
+ JSON.stringify({ schemaVersion: 2, runId: "old", pid: 1, rootDir: "/x" }),
176
+ );
177
+ writeEntry(root, makeEntry("new", livePid, "/n"));
178
+
179
+ const orig = console.warn;
180
+ let warned = "";
181
+ console.warn = (msg: string) => {
182
+ warned += msg;
183
+ };
184
+ let entries: RegistryEntry[] = [];
185
+ try {
186
+ entries = listEntries(root);
187
+ } finally {
188
+ console.warn = orig;
189
+ }
190
+ expect(entries.map((e) => e.runId)).toEqual(["new"]);
191
+ expect(readEntry(root, "old")).toBeUndefined();
192
+ expect(warned).toContain("schemaVersion");
193
+ });
194
+
195
+ test("listEntries skips malformed JSON and structurally-bad entries without crashing", () => {
196
+ const root = freshRoot();
197
+ const dir = join(root, ".darkf", "registry");
198
+ mkdirSync(dir, { recursive: true });
199
+ writeFileSync(join(dir, "garbage.json"), "{not json at all");
200
+ writeFileSync(
201
+ join(dir, "badshape.json"),
202
+ JSON.stringify({ schemaVersion: SCHEMA_VERSION, runId: 42, pid: 1, rootDir: "/x" }),
203
+ );
204
+ writeEntry(root, makeEntry("good", livePid, "/g"));
205
+ expect(listEntries(root).map((e) => e.runId)).toEqual(["good"]);
206
+ });
207
+
208
+ test("listEntries returns [] when the registry directory does not exist", () => {
209
+ expect(listEntries(join(tmpRoot, "never-created"))).toEqual([]);
210
+ });
211
+
212
+ test("isPidAlive is true for a live pid and false for a dead one", () => {
213
+ expect(isPidAlive(livePid)).toBe(true);
214
+ expect(isPidAlive(deadPid)).toBe(false);
215
+ });
216
+
217
+ function journal(events: NodeEvent[]): string {
218
+ return events.map((e) => JSON.stringify(e)).join("\n") + (events.length ? "\n" : "");
219
+ }
220
+
221
+ test("journalTerminal reads the last line: EXIT-succeeded, crashed, else undefined", () => {
222
+ expect(journalTerminal(journal([end({ output: "done" })]))).toBe("succeeded");
223
+ expect(
224
+ journalTerminal(
225
+ journal([begin(), crashed("Solo", 2000, { kind: "no-transition", state: "Solo" })]),
226
+ ),
227
+ ).toBe("crashed");
228
+ expect(journalTerminal(journal([begin(), running("Solo", 2000)]))).toBeUndefined();
229
+ expect(journalTerminal("")).toBeUndefined();
230
+ // A journal whose last line is an EXIT-succeeded marker reads as succeeded —
231
+ // position, not a field, is what the spec keys off. (A run that only ever
232
+ // wrote its begin marker therefore reads "succeeded" here; the orphan test
233
+ // below avoids that degenerate shape by killing after the journal has grown.)
234
+ expect(journalTerminal(journal([begin()]))).toBe("succeeded");
235
+ });
236
+
237
+ test("journalTerminal reads a FAILED-tagged last line as failed, not crashed", () => {
238
+ expect(
239
+ journalTerminal(journal([begin(), succeeded("RunFailure", 2000), failedEnd({ output: "x" })])),
240
+ ).toBe("failed");
241
+ });
242
+
243
+ // --- the full 9-case resolution matrix ---
244
+
245
+ test("case 1: no registry dir / empty -> nothing to monitor", () => {
246
+ expect(resolveRun(join(tmpRoot, "no-such-dir"))).toEqual({
247
+ kind: "none",
248
+ recentFinished: undefined,
249
+ });
250
+ const empty = freshRoot();
251
+ mkdirSync(join(empty, ".darkf", "registry"), { recursive: true });
252
+ expect(resolveRun(empty)).toEqual({ kind: "none", recentFinished: undefined });
253
+ });
254
+
255
+ test("case 2: --run given, no matching entry -> no such run", () => {
256
+ const { root } = seeded("a", livePid, [begin(), running("S", 2000)]);
257
+ expect(resolveRun(root, "missing")).toEqual({ kind: "noSuchRun" });
258
+ });
259
+
260
+ test("case 3: --run matches and is already terminal -> short-circuit (even with a dead PID)", () => {
261
+ const ok = seeded("ok", deadPid, [
262
+ begin(),
263
+ succeeded("S", 2500, { output: "x" }),
264
+ end({ output: "x" }),
265
+ ]);
266
+ expect(resolveRun(ok.root, "ok").kind).toBe("terminal");
267
+ const okRes = resolveRun(ok.root, "ok");
268
+ if (okRes.kind === "terminal") expect(okRes.outcome).toBe("succeeded");
269
+
270
+ const bad = seeded("bad", deadPid, [
271
+ begin(),
272
+ crashed("S", 2500, { kind: "runner-error", error: "boom" }),
273
+ ]);
274
+ const badRes = resolveRun(bad.root, "bad");
275
+ expect(badRes.kind).toBe("terminal");
276
+ if (badRes.kind === "terminal") expect(badRes.outcome).toBe("crashed");
277
+
278
+ const failed = seeded("failed-run", deadPid, [
279
+ begin(),
280
+ succeeded("RunFailure", 2500, { output: "x" }),
281
+ failedEnd({ output: "x" }),
282
+ ]);
283
+ const failedRes = resolveRun(failed.root, "failed-run");
284
+ expect(failedRes.kind).toBe("terminal");
285
+ if (failedRes.kind === "terminal") expect(failedRes.outcome).toBe("failed");
286
+ });
287
+
288
+ test("case 4: --run, cached running, dead PID, journal not EXIT-succeeded -> orphaned", () => {
289
+ const { root } = seeded("orphan", deadPid, [begin(), running("S", 2000)]);
290
+ expect(resolveRun(root, "orphan")).toEqual({
291
+ kind: "orphaned",
292
+ entry: expect.anything(),
293
+ journalPath: expect.anything(),
294
+ } as never);
295
+ });
296
+
297
+ test("case 5: no --run, entries exist but none running -> nothing, mentioning most recent finished", () => {
298
+ const root = freshRoot();
299
+ const done = makeEntry("done", deadPid, "/d", { status: "succeeded", finishedAt: 9999 });
300
+ writeEntry(root, done);
301
+ const res = resolveRun(root);
302
+ expect(res.kind).toBe("none");
303
+ if (res.kind === "none") expect(res.recentFinished?.runId).toBe("done");
304
+ });
305
+
306
+ test("case 6: no --run, exactly one cached running with a live PID -> resolve to it", () => {
307
+ const { root, entry } = seeded("live", livePid, [begin(), running("S", 2000)]);
308
+ const res = resolveRun(root);
309
+ expect(res.kind).toBe("resolved");
310
+ if (res.kind === "resolved") expect(res.entry.runId).toBe(entry.runId);
311
+ });
312
+
313
+ test("case 7: no --run, one cached running, dead PID -> journal decides (succeeded / crashed / orphaned)", () => {
314
+ const ok = seeded("ok", deadPid, [begin(), succeeded("S", 2500, {}), end({})]);
315
+ const okRes = resolveRun(ok.root);
316
+ expect(okRes.kind).toBe("terminal");
317
+ if (okRes.kind === "terminal") expect(okRes.outcome).toBe("succeeded");
318
+
319
+ const bad = seeded("bad", deadPid, [
320
+ begin(),
321
+ crashed("S", 2500, { kind: "no-transition", state: "S" }),
322
+ ]);
323
+ const badRes = resolveRun(bad.root);
324
+ expect(badRes.kind).toBe("terminal");
325
+ if (badRes.kind === "terminal") expect(badRes.outcome).toBe("crashed");
326
+
327
+ const gone = seeded("gone", deadPid, [begin(), running("S", 2000)]);
328
+ expect(resolveRun(gone.root).kind).toBe("orphaned");
329
+ });
330
+
331
+ test("case 8: no --run, 2+ cached running with live PIDs -> ambiguous, listing the live ones", () => {
332
+ const root = freshRoot();
333
+ const a = makeEntry("a", livePid, "/a");
334
+ const b = makeEntry("b", livePid, "/b");
335
+ writeEntry(root, a);
336
+ writeEntry(root, b);
337
+ const res = resolveRun(root);
338
+ expect(res.kind).toBe("ambiguous");
339
+ if (res.kind === "ambiguous") expect(res.entries.map((e) => e.runId).sort()).toEqual(["a", "b"]);
340
+ });
341
+
342
+ test("case 9: no --run, 2+ cached running, only one live -> resolve to the live one, warn about the rest", () => {
343
+ const root = freshRoot();
344
+ writeEntry(root, makeEntry("dead-one", deadPid, "/d"));
345
+ writeEntry(root, makeEntry("live-one", livePid, "/l"));
346
+ writeJournal(join(root, "/l"), "live-one", [begin(), running("S", 2000)]);
347
+ const orig = console.warn;
348
+ let warned = "";
349
+ console.warn = (msg: string) => {
350
+ warned += msg;
351
+ };
352
+ let res: RunResolution;
353
+ try {
354
+ res = resolveRun(root);
355
+ } finally {
356
+ console.warn = orig;
357
+ }
358
+ expect(res.kind).toBe("resolved");
359
+ if (res.kind === "resolved") expect(res.entry.runId).toBe("live-one");
360
+ expect(warned).toContain("dead-one");
361
+ });
362
+
363
+ test("no --run, 2+ cached running, none live -> ambiguous (refuse to guess between dead runs)", () => {
364
+ const root = freshRoot();
365
+ writeEntry(root, makeEntry("d1", deadPid, "/d1"));
366
+ writeEntry(root, makeEntry("d2", deadPid, "/d2"));
367
+ const res = resolveRun(root);
368
+ expect(res.kind).toBe("ambiguous");
369
+ if (res.kind === "ambiguous")
370
+ expect(res.entries.map((e) => e.runId).sort()).toEqual(["d1", "d2"]);
371
+ });
372
+
373
+ test("journalPathFor points at the run's journal under its rootDir", () => {
374
+ const entry = makeEntry("r1", livePid, "/root");
375
+ expect(journalPathFor(entry)).toBe(join("/root", ".darkf", "run", "r1", "journal.jsonl"));
376
+ });
377
+
378
+ test("detectSupervisorSignal matches CLAUDE_CODE_SESSION_ID, else leaves both fields unset", () => {
379
+ expect(detectSupervisorSignal({ CLAUDE_CODE_SESSION_ID: "sess-abc" })).toEqual({
380
+ supervisorSessionID: "sess-abc",
381
+ supervisorHarness: "claude-code",
382
+ });
383
+ expect(detectSupervisorSignal({})).toEqual({});
384
+ expect(detectSupervisorSignal({ CLAUDE_CODE_SESSION_ID: "" })).toEqual({});
385
+ expect(detectSupervisorSignal({ SOME_OTHER_VAR: "x" })).toEqual({});
386
+ });
@@ -0,0 +1,296 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { DONE, FAILED, parseEventLog } from "../core/index.ts";
4
+
5
+ export const SCHEMA_VERSION = 1;
6
+
7
+ export type RegistryStatus = "running" | "succeeded" | "failed" | "crashed" | "failed-start";
8
+
9
+ // A pointer to a detached run, never a source of truth for its outcome — the
10
+ // journal is. `status`/`finishedAt` are a best-effort cache a worker updates
11
+ // on completion; they are never trusted alone once the PID is found dead.
12
+ export interface RegistryEntry {
13
+ schemaVersion: number;
14
+ runId: string;
15
+ pid: number;
16
+ rootDir: string;
17
+ startedAt: number;
18
+ message?: string;
19
+ status: RegistryStatus;
20
+ finishedAt: number | null;
21
+ /** Absolute path to the resolved workflow directory (contains
22
+ * `workflow.ts`) this run was started from. Optional so entries written
23
+ * before this field existed still parse. Lets a later process (e.g. a
24
+ * visualizer) load the same `WorkflowDef` this run is executing without
25
+ * having been the one that resolved the workflow reference itself. */
26
+ workflowDir?: string;
27
+ /** `AgentRunner.kind` of the runner this run was started with, copied at
28
+ * `startCmd`/`runCmd` time. Unset if the workflow has no agent nodes, or
29
+ * its runner doesn't self-identify. */
30
+ agentRunnerKind?: string;
31
+ /** The external session (if any) that invoked `darkf start`/`run`, and
32
+ * which harness it was — detected once, at invocation time, via
33
+ * `SUPERVISOR_ENV_SIGNALS`. Both unset if no signal matched. */
34
+ supervisorSessionID?: string;
35
+ supervisorHarness?: string;
36
+ /** `/proc/sys/kernel/random/boot_id`, recorded at `start`/`run` time —
37
+ * lets a later `status` tell "this host rebooted since the run started"
38
+ * (`host-died`) apart from "the process just died" (`orphaned`). Absent
39
+ * on entries written before this field existed, or on a non-Linux host
40
+ * (`currentBootId()` returns `undefined` there) — both degrade to
41
+ * today's `orphaned` wording, never a false `host-died`. See
42
+ * docs/specs/_built/registry-lifecycle/spec.md. */
43
+ bootId?: string;
44
+ /** Set only when `status` is `"failed-start"`: the last lines of
45
+ * `worker.log` — the worker process's own captured stderr — so the
46
+ * failure self-documents without a foreground reproduction. */
47
+ startFailureDetail?: string;
48
+ }
49
+
50
+ // Small, extensible table of "this env var means we're running under harness
51
+ // X" signals, checked once at invocation time (`startCmd`/`runCmd`). First
52
+ // match in `process.env` wins. Growing this table (e.g. adding opencode's
53
+ // row once `verify-opencode-session-env` confirms a version floor) never
54
+ // needs a schema change — just another row.
55
+ export const SUPERVISOR_ENV_SIGNALS: Array<{ env: string; harness: string }> = [
56
+ { env: "CLAUDE_CODE_SESSION_ID", harness: "claude-code" },
57
+ ];
58
+
59
+ export interface SupervisorSignal {
60
+ supervisorSessionID?: string;
61
+ supervisorHarness?: string;
62
+ }
63
+
64
+ // No match degrades to both fields unset — same "nothing shown" philosophy
65
+ // as everywhere else this plugin reads optional external signals.
66
+ export function detectSupervisorSignal(
67
+ env: Record<string, string | undefined> = process.env,
68
+ ): SupervisorSignal {
69
+ for (const { env: name, harness } of SUPERVISOR_ENV_SIGNALS) {
70
+ const value = env[name];
71
+ if (value) return { supervisorSessionID: value, supervisorHarness: harness };
72
+ }
73
+ return {};
74
+ }
75
+
76
+ export function projectRoot(cwd: string = process.cwd()): string {
77
+ let dir = cwd;
78
+ for (;;) {
79
+ if (existsSync(join(dir, ".git"))) return dir;
80
+ const parent = dirname(dir);
81
+ if (parent === dir) return cwd;
82
+ dir = parent;
83
+ }
84
+ }
85
+
86
+ export function registryDir(root: string): string {
87
+ return join(root, ".darkf", "registry");
88
+ }
89
+
90
+ export function entryPath(root: string, runId: string): string {
91
+ return join(registryDir(root), `${runId}.json`);
92
+ }
93
+
94
+ export function journalPathFor(entry: RegistryEntry): string {
95
+ return join(entry.rootDir, ".darkf", "run", entry.runId, "journal.jsonl");
96
+ }
97
+
98
+ // These three take `(rootDir, runId)` directly, not a `RegistryEntry` — the
99
+ // readiness-gating in `startCmd` needs them *before* any entry exists.
100
+ export function runArtifactsDir(rootDir: string, runId: string): string {
101
+ return join(rootDir, ".darkf", "run", runId);
102
+ }
103
+
104
+ /** Written by the worker (`workerCmd`) once the workflow module has
105
+ * loaded — see docs/specs/_built/registry-lifecycle/spec.md. Its mere
106
+ * existence is the proof `start` waits for; contents are never read. */
107
+ export function readyPath(rootDir: string, runId: string): string {
108
+ return join(runArtifactsDir(rootDir, runId), "ready");
109
+ }
110
+
111
+ /** The detached worker's own stderr, captured here instead of discarded —
112
+ * every startup failure self-documents without a foreground
113
+ * reproduction. */
114
+ export function workerLogPath(rootDir: string, runId: string): string {
115
+ return join(runArtifactsDir(rootDir, runId), "worker.log");
116
+ }
117
+
118
+ /** `undefined` on a non-Linux host, or if the file can't be read — both
119
+ * degrade `hostDiedSince` to `false` (never a false `host-died`). */
120
+ export function currentBootId(): string | undefined {
121
+ try {
122
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ }
127
+
128
+ /** True only when the entry recorded a boot id AND the current host's own
129
+ * boot id is readable AND they differ — every other case (no `bootId` on
130
+ * the entry, non-Linux host) degrades to `false`, i.e. today's `orphaned`
131
+ * wording, never a guess. */
132
+ export function hostDiedSince(entry: RegistryEntry): boolean {
133
+ if (entry.bootId === undefined) return false;
134
+ const current = currentBootId();
135
+ if (current === undefined) return false;
136
+ return current !== entry.bootId;
137
+ }
138
+
139
+ // `process.kill(pid, 0)` never signals the target. It throws ESRCH only when
140
+ // no such process exists; any other throw (e.g. EPERM) means a process IS
141
+ // there, just unreachable — count that as alive. Verified against Bun.
142
+ export function isPidAlive(pid: number): boolean {
143
+ try {
144
+ process.kill(pid, 0);
145
+ return true;
146
+ } catch (err) {
147
+ return (err as NodeJS.ErrnoException).code !== "ESRCH";
148
+ }
149
+ }
150
+
151
+ export function writeEntry(root: string, entry: RegistryEntry): void {
152
+ mkdirSync(registryDir(root), { recursive: true });
153
+ writeFileSync(entryPath(root, entry.runId), `${JSON.stringify(entry, null, 2)}\n`);
154
+ }
155
+
156
+ function parseEntry(raw: string): RegistryEntry | null {
157
+ let obj: unknown;
158
+ try {
159
+ obj = JSON.parse(raw);
160
+ } catch {
161
+ return null;
162
+ }
163
+ if (typeof obj !== "object" || obj === null) return null;
164
+ const e = obj as Record<string, unknown>;
165
+ if (e.schemaVersion !== SCHEMA_VERSION) {
166
+ console.warn(
167
+ `darkf: skipping registry entry with unknown schemaVersion ${String(e.schemaVersion)}`,
168
+ );
169
+ return null;
170
+ }
171
+ if (typeof e.runId !== "string" || typeof e.pid !== "number" || typeof e.rootDir !== "string") {
172
+ return null;
173
+ }
174
+ return e as unknown as RegistryEntry;
175
+ }
176
+
177
+ export function readEntry(root: string, runId: string): RegistryEntry | undefined {
178
+ let raw: string;
179
+ try {
180
+ raw = readFileSync(entryPath(root, runId), "utf8");
181
+ } catch {
182
+ return undefined;
183
+ }
184
+ return parseEntry(raw) ?? undefined;
185
+ }
186
+
187
+ export function listEntries(root: string): RegistryEntry[] {
188
+ let names: string[];
189
+ try {
190
+ names = readdirSync(registryDir(root));
191
+ } catch {
192
+ return [];
193
+ }
194
+ const entries: RegistryEntry[] = [];
195
+ for (const name of names) {
196
+ if (!name.endsWith(".json")) continue;
197
+ let raw: string;
198
+ try {
199
+ raw = readFileSync(join(registryDir(root), name), "utf8");
200
+ } catch {
201
+ continue;
202
+ }
203
+ const entry = parseEntry(raw);
204
+ if (entry) entries.push(entry);
205
+ }
206
+ return entries;
207
+ }
208
+
209
+ export function readJournalText(journalPath: string): string {
210
+ try {
211
+ return readFileSync(journalPath, "utf8");
212
+ } catch {
213
+ return "";
214
+ }
215
+ }
216
+
217
+ // The journal's authoritative terminal outcome, read from its last line only.
218
+ // A `DONE`-tagged `succeeded` last line means the run's end marker; a
219
+ // `FAILED`-tagged `failed` last line means `run_failure` routed the graph to
220
+ // its failure terminal; a `crashed` last line is the crashing leaf's own
221
+ // terminal emit. Anything else means the run had not reached a terminal state
222
+ // in the journal.
223
+ export type TerminalOutcome = "succeeded" | "failed" | "crashed";
224
+
225
+ export function journalTerminal(journalText: string): TerminalOutcome | undefined {
226
+ const last = parseEventLog(journalText).at(-1);
227
+ if (!last) return undefined;
228
+ if (last.state === DONE && last.status.phase === "succeeded") return "succeeded";
229
+ if (last.state === FAILED && last.status.phase === "failed") return "failed";
230
+ if (last.status.phase === "crashed") return "crashed";
231
+ return undefined;
232
+ }
233
+
234
+ export type RunResolution =
235
+ | { kind: "none"; recentFinished?: RegistryEntry }
236
+ | { kind: "noSuchRun" }
237
+ | { kind: "ambiguous"; entries: RegistryEntry[] }
238
+ | { kind: "terminal"; entry: RegistryEntry; outcome: TerminalOutcome; journalPath: string }
239
+ | { kind: "orphaned"; entry: RegistryEntry; journalPath: string }
240
+ | { kind: "resolved"; entry: RegistryEntry; journalPath: string };
241
+
242
+ function classifyResolved(entry: RegistryEntry): RunResolution {
243
+ const journalPath = journalPathFor(entry);
244
+ const outcome = journalTerminal(readJournalText(journalPath));
245
+ if (outcome) return { kind: "terminal", entry, outcome, journalPath };
246
+ if (isPidAlive(entry.pid)) return { kind: "resolved", entry, journalPath };
247
+ return { kind: "orphaned", entry, journalPath };
248
+ }
249
+
250
+ function mostRecentFinished(entries: RegistryEntry[]): RegistryEntry | undefined {
251
+ let best: RegistryEntry | undefined;
252
+ let bestTime = -Infinity;
253
+ for (const e of entries) {
254
+ if (e.status === "running") continue;
255
+ const t = e.finishedAt ?? e.startedAt;
256
+ if (t > bestTime) {
257
+ bestTime = t;
258
+ best = e;
259
+ }
260
+ }
261
+ return best;
262
+ }
263
+
264
+ // The 9-case "which run" resolution shared by `status` and `monitor`. `root` is
265
+ // the project root (see projectRoot), `runId` the `--run` value when given.
266
+ export function resolveRun(root: string, runId?: string): RunResolution {
267
+ const entries = listEntries(root);
268
+
269
+ if (runId !== undefined) {
270
+ const entry = entries.find((e) => e.runId === runId);
271
+ if (!entry) return { kind: "noSuchRun" };
272
+ return classifyResolved(entry);
273
+ }
274
+
275
+ if (entries.length === 0) return { kind: "none" };
276
+
277
+ const running = entries.filter((e) => e.status === "running");
278
+ if (running.length === 0) return { kind: "none", recentFinished: mostRecentFinished(entries) };
279
+
280
+ const live = running.filter((e) => isPidAlive(e.pid));
281
+ if (live.length >= 2) return { kind: "ambiguous", entries: live };
282
+ if (live.length === 1) {
283
+ for (const other of running) {
284
+ if (other.runId === live[0]!.runId) continue;
285
+ console.warn(
286
+ `darkf: run ${other.runId} (${other.rootDir}) is cached "running" but its PID ${other.pid} is gone`,
287
+ );
288
+ }
289
+ return classifyResolved(live[0]!);
290
+ }
291
+
292
+ // Every cached-"running" entry is dead. One of them is unambiguous; several
293
+ // still are, so refuse to guess and require --run.
294
+ if (running.length === 1) return classifyResolved(running[0]!);
295
+ return { kind: "ambiguous", entries: running };
296
+ }