@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,486 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import {
6
+ checkRegistry,
7
+ isDue,
8
+ isNewer,
9
+ readState,
10
+ type UpdateDeps,
11
+ updateGate,
12
+ upgradeCmd,
13
+ writeState,
14
+ } from "./update.ts";
15
+
16
+ // --- fixtures: injectable clock, fetch, spawner, temp state file ---
17
+
18
+ const NOW = 1_793_000_000_000; // fixed epoch ms; every test's "today"
19
+ const INSTALLED = "0.3.0";
20
+ const HOUR_MS = 60 * 60 * 1000;
21
+
22
+ const roots: string[] = [];
23
+ afterAll(() => {
24
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
25
+ });
26
+
27
+ function tempDir(): string {
28
+ const dir = mkdtempSync(join(tmpdir(), "darkf-update-"));
29
+ roots.push(dir);
30
+ return dir;
31
+ }
32
+
33
+ function tempStateFile(): string {
34
+ // Parent deliberately absent — writeState must mkdir -p it.
35
+ return join(tempDir(), "state", "darkf", "last-update-check.json");
36
+ }
37
+
38
+ function seedState(file: string, state: object): void {
39
+ mkdirSync(dirname(file), { recursive: true });
40
+ writeFileSync(file, JSON.stringify(state));
41
+ }
42
+
43
+ function rawFile(file: string): string | null {
44
+ try {
45
+ return readFileSync(file, "utf8");
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ function deps(overrides: Partial<UpdateDeps> = {}): UpdateDeps {
52
+ return {
53
+ now: () => NOW,
54
+ fetchImpl: (async () => {
55
+ throw new Error("unexpected registry access");
56
+ }) as unknown as typeof fetch,
57
+ spawnImpl: (() => {
58
+ throw new Error("unexpected spawn");
59
+ }) as unknown as typeof Bun.spawnSync,
60
+ stateFile: tempStateFile(),
61
+ installed: INSTALLED,
62
+ ...overrides,
63
+ };
64
+ }
65
+
66
+ /** 200-with-body fetch unless a status is given; records the requested URLs. */
67
+ function fetchReturning(body: string, status = 200): { fetchImpl: typeof fetch; urls: string[] } {
68
+ const urls: string[] = [];
69
+ const fetchImpl = (async (input: unknown) => {
70
+ urls.push(String(input));
71
+ return new Response(body, { status });
72
+ }) as unknown as typeof fetch;
73
+ return { fetchImpl, urls };
74
+ }
75
+
76
+ function fetchCounting(
77
+ body: string,
78
+ status = 200,
79
+ ): { fetchImpl: typeof fetch; count: () => number } {
80
+ let calls = 0;
81
+ const fetchImpl = (async () => {
82
+ calls += 1;
83
+ return new Response(body, { status });
84
+ }) as unknown as typeof fetch;
85
+ return { fetchImpl, count: () => calls };
86
+ }
87
+
88
+ /** Hangs until the caller's AbortSignal fires — honors the signal like real fetch. */
89
+ const hangingFetch = ((_input: unknown, init?: RequestInit) =>
90
+ new Promise<Response>((_resolve, reject) => {
91
+ const signal = init?.signal;
92
+ signal?.addEventListener("abort", () => reject(signal.reason));
93
+ })) as typeof fetch;
94
+
95
+ interface SpawnReply {
96
+ exitCode: number;
97
+ stdout?: string;
98
+ }
99
+
100
+ /** Scripted spawnSync: the reply fn answers each command; unscripted ones throw. */
101
+ function spawnStub(script: (cmd: string[]) => SpawnReply | undefined): {
102
+ spawnImpl: typeof Bun.spawnSync;
103
+ calls: string[][];
104
+ } {
105
+ const calls: string[][] = [];
106
+ const spawnImpl = ((cmd: unknown, _opts?: unknown) => {
107
+ const argv = [...(cmd as string[])];
108
+ calls.push(argv);
109
+ const reply = script(argv);
110
+ if (!reply) throw new Error(`unexpected spawn: ${argv.join(" ")}`);
111
+ return {
112
+ exitCode: reply.exitCode,
113
+ success: reply.exitCode === 0,
114
+ stdout: Buffer.from(reply.stdout ?? ""),
115
+ stderr: Buffer.from(""),
116
+ };
117
+ }) as unknown as typeof Bun.spawnSync;
118
+ return { spawnImpl, calls };
119
+ }
120
+
121
+ async function captured<T>(fn: () => Promise<T> | T): Promise<{
122
+ result: T;
123
+ out: string[];
124
+ err: string[];
125
+ }> {
126
+ const out: string[] = [];
127
+ const err: string[] = [];
128
+ const { log, error } = console;
129
+ console.log = (...args: unknown[]) => void out.push(args.map(String).join(" "));
130
+ console.error = (...args: unknown[]) => void err.push(args.map(String).join(" "));
131
+ try {
132
+ return { result: await fn(), out, err };
133
+ } finally {
134
+ console.log = log;
135
+ console.error = error;
136
+ }
137
+ }
138
+
139
+ async function withOptOut<T>(fn: () => Promise<T> | T): Promise<T> {
140
+ const prev = process.env.DARKF_NO_UPDATE_CHECK;
141
+ process.env.DARKF_NO_UPDATE_CHECK = "1";
142
+ try {
143
+ return await fn();
144
+ } finally {
145
+ if (prev === undefined) delete process.env.DARKF_NO_UPDATE_CHECK;
146
+ else process.env.DARKF_NO_UPDATE_CHECK = prev;
147
+ }
148
+ }
149
+
150
+ // --- comparison and due-ness ---
151
+
152
+ test("isNewer: older, equal, newer, prerelease", () => {
153
+ expect(isNewer("0.3.0", "0.4.0")).toBe(true);
154
+ expect(isNewer("0.3.0", "0.3.0")).toBe(false);
155
+ expect(isNewer("0.4.0", "0.3.0")).toBe(false);
156
+ expect(isNewer("0.3.0", "0.4.0-beta.1")).toBe(true);
157
+ });
158
+
159
+ test("isDue: missing, corrupt, fresh, and the 24h boundary", () => {
160
+ expect(isDue({}, NOW)).toBe(true);
161
+ expect(isDue({ lastCheck: "not a timestamp" }, NOW)).toBe(true);
162
+ expect(isDue({ lastCheck: new Date(NOW - 23 * HOUR_MS).toISOString() }, NOW)).toBe(false);
163
+ // Data model: now - lastCheck >= 24h — exactly one day is due again.
164
+ expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS).toISOString() }, NOW)).toBe(true);
165
+ expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS + 1000).toISOString() }, NOW)).toBe(false);
166
+ });
167
+
168
+ // --- state file ---
169
+
170
+ test("readState: absent, corrupt, and wrong-shaped files all read as empty", () => {
171
+ expect(readState(join(tempDir(), "does-not-exist.json"))).toEqual({});
172
+ const dir = tempDir();
173
+ const corrupt = join(dir, "state.json");
174
+ writeFileSync(corrupt, "{not json");
175
+ expect(readState(corrupt)).toEqual({});
176
+ const array = join(dir, "array.json");
177
+ writeFileSync(array, "[1,2,3]");
178
+ expect(readState(array)).toEqual({});
179
+ const wrongTypes = join(dir, "types.json");
180
+ writeFileSync(wrongTypes, JSON.stringify({ lastCheck: 5, latestSeen: true }));
181
+ expect(readState(wrongTypes)).toEqual({});
182
+ });
183
+
184
+ test("writeState round-trips and creates missing parent directories", () => {
185
+ const file = tempStateFile();
186
+ writeState(file, { lastCheck: "2026-10-30T08:00:00.000Z", latestSeen: "0.4.0" });
187
+ expect(readState(file)).toEqual({
188
+ lastCheck: "2026-10-30T08:00:00.000Z",
189
+ latestSeen: "0.4.0",
190
+ });
191
+ });
192
+
193
+ test("writeState swallows an unwritable location (REQ-4)", () => {
194
+ const dir = tempDir();
195
+ const blocker = join(dir, "blocker");
196
+ writeFileSync(blocker, "a file, not a directory");
197
+ expect(() => writeState(join(blocker, "darkf", "state.json"), {})).not.toThrow();
198
+ });
199
+
200
+ // --- checkRegistry ---
201
+
202
+ test("checkRegistry: 200 with a semver-shaped latest returns it, at the pinned endpoint", async () => {
203
+ const { fetchImpl, urls } = fetchReturning('{"latest":"0.4.0","next":"0.5.0-rc.1"}');
204
+ expect(await checkRegistry(fetchImpl)).toBe("0.4.0");
205
+ expect(urls).toEqual(["https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags"]);
206
+ });
207
+
208
+ test("checkRegistry: non-200, malformed JSON, and non-semver latest all return null", async () => {
209
+ expect(await checkRegistry(fetchReturning('{"latest":"9.9.9"}', 503).fetchImpl)).toBeNull();
210
+ expect(await checkRegistry(fetchReturning("not json at all").fetchImpl)).toBeNull();
211
+ expect(await checkRegistry(fetchReturning('{"latest":"banana"}').fetchImpl)).toBeNull();
212
+ expect(await checkRegistry(fetchReturning('{"latest":123}').fetchImpl)).toBeNull();
213
+ expect(await checkRegistry(fetchReturning("{}").fetchImpl)).toBeNull();
214
+ });
215
+
216
+ test("checkRegistry: a fetch that rejects (no network) returns null, never throws", async () => {
217
+ const rejecting = (async () => {
218
+ throw new TypeError("fetch failed");
219
+ }) as unknown as typeof fetch;
220
+ expect(await checkRegistry(rejecting)).toBeNull();
221
+ });
222
+
223
+ test("checkRegistry: a hanging request returns null at the 2s abort (NFR-1)", async () => {
224
+ const start = Date.now();
225
+ expect(await checkRegistry(hangingFetch)).toBeNull();
226
+ expect(Date.now() - start).toBeGreaterThanOrEqual(1900);
227
+ });
228
+
229
+ // --- startup gate ---
230
+
231
+ test("gate on a due day: one request, stamped, newer latestSeen recorded, one notice line", async () => {
232
+ const file = tempStateFile();
233
+ const { fetchImpl, urls } = fetchReturning('{"latest":"9.9.9"}');
234
+ const { out, err } = await captured(() =>
235
+ updateGate("status", deps({ stateFile: file, fetchImpl })),
236
+ );
237
+
238
+ expect(urls).toEqual(["https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags"]);
239
+ expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
240
+ expect(err).toEqual([]);
241
+ expect(readState(file)).toEqual({
242
+ lastCheck: new Date(NOW).toISOString(),
243
+ latestSeen: "9.9.9",
244
+ });
245
+ });
246
+
247
+ test("gate same-day re-run: no request, notice still printed from the record (REQ-2, REQ-11)", async () => {
248
+ const file = tempStateFile();
249
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
250
+ await captured(() => updateGate("run", deps({ stateFile: file, fetchImpl })));
251
+ expect(count()).toBe(1);
252
+
253
+ const later = await captured(() =>
254
+ updateGate("run", deps({ stateFile: file, fetchImpl, now: () => NOW + 3 * HOUR_MS })),
255
+ );
256
+ expect(count()).toBe(1); // no second request within 24 h
257
+ expect(later.out).toEqual([
258
+ `darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`,
259
+ ]);
260
+ });
261
+
262
+ test("gate: a failed check still stamps and prints nothing (REQ-2, REQ-4)", async () => {
263
+ const file = tempStateFile();
264
+ const { out, err } = await captured(() => updateGate("status", deps({ stateFile: file })));
265
+
266
+ expect(out).toEqual([]);
267
+ expect(err).toEqual([]);
268
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() });
269
+ });
270
+
271
+ test("gate: a stale notice survives a failed check (REQ-11)", async () => {
272
+ const file = tempStateFile();
273
+ seedState(file, { lastCheck: new Date(NOW - 48 * HOUR_MS).toISOString(), latestSeen: "9.9.9" });
274
+
275
+ const { out } = await captured(() => updateGate("status", deps({ stateFile: file })));
276
+
277
+ expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
278
+ expect(readState(file)).toEqual({
279
+ lastCheck: new Date(NOW).toISOString(), // restamped by the failed attempt
280
+ latestSeen: "9.9.9", // untouched by the null result
281
+ });
282
+ });
283
+
284
+ test("gate: finding the installed version clears the record (REQ-11)", async () => {
285
+ const file = tempStateFile();
286
+ seedState(file, { lastCheck: new Date(NOW - 48 * HOUR_MS).toISOString(), latestSeen: "9.9.9" });
287
+ const { fetchImpl } = fetchReturning(`{"latest":"${INSTALLED}"}`);
288
+
289
+ const { out } = await captured(() => updateGate("status", deps({ stateFile: file, fetchImpl })));
290
+
291
+ expect(out).toEqual([]);
292
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() });
293
+ });
294
+
295
+ test("gate: DARKF_NO_UPDATE_CHECK returns before any state read, request, or print (REQ-5)", async () => {
296
+ const file = tempStateFile();
297
+ const sentinel = '{"lastCheck":"kept-untouched"}';
298
+ mkdirSync(dirname(file), { recursive: true });
299
+ writeFileSync(file, sentinel);
300
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
301
+
302
+ const { out, err } = await withOptOut(() =>
303
+ captured(() => updateGate("status", deps({ stateFile: file, fetchImpl }))),
304
+ );
305
+
306
+ expect(count()).toBe(0);
307
+ expect(out).toEqual([]);
308
+ expect(err).toEqual([]);
309
+ expect(rawFile(file)).toBe(sentinel); // not even a state read side effect
310
+ });
311
+
312
+ test("gate: `upgrade` is skipped — the command fetches on its own", async () => {
313
+ const file = tempStateFile();
314
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
315
+
316
+ const { out, err } = await captured(() =>
317
+ updateGate("upgrade", deps({ stateFile: file, fetchImpl })),
318
+ );
319
+
320
+ expect(count()).toBe(0);
321
+ expect(out).toEqual([]);
322
+ expect(err).toEqual([]);
323
+ expect(rawFile(file)).toBeNull(); // no state written for the upgrade command
324
+ });
325
+
326
+ // --- upgrade ---
327
+
328
+ test("upgrade: already-current prints current and exits 0 (REQ-6)", async () => {
329
+ const file = tempStateFile();
330
+ const { fetchImpl } = fetchReturning(`{"latest":"${INSTALLED}"}`);
331
+ const { spawnImpl, calls } = spawnStub(() => undefined);
332
+
333
+ const { result, out, err } = await captured(() =>
334
+ upgradeCmd(deps({ stateFile: file, fetchImpl, spawnImpl })),
335
+ );
336
+
337
+ expect(result).toBe(0);
338
+ expect(out).toEqual([`darkf is current (installed ${INSTALLED})`]);
339
+ expect(err).toEqual([]);
340
+ expect(calls).toEqual([]); // no probe, no installer
341
+ });
342
+
343
+ test("upgrade: registry failure prints a reason and exits 1 (REQ-10)", async () => {
344
+ const { result, out, err } = await captured(() => upgradeCmd(deps()));
345
+ expect(result).toBe(1);
346
+ expect(out).toEqual([]);
347
+ expect(err).toHaveLength(1);
348
+ expect(err[0]).toContain("update check failed");
349
+ });
350
+
351
+ test("upgrade: no manager lists the package — exit 1, no installer run (REQ-9)", async () => {
352
+ const { spawnImpl, calls } = spawnStub(() => ({ exitCode: 1, stdout: "nothing here" }));
353
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
354
+
355
+ const { result, out, err } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
356
+
357
+ expect(result).toBe(1);
358
+ expect(out).toEqual([]); // never claims to upgrade
359
+ expect(err).toEqual([
360
+ "cannot determine how this darkf was installed — not managed by bun or npm",
361
+ ]);
362
+ expect(calls.every((cmd) => cmd[1] !== "install")).toBe(true);
363
+ });
364
+
365
+ test("upgrade: bun is probed first and wins the install (design: D-4)", async () => {
366
+ const { spawnImpl, calls } = spawnStub((cmd) => {
367
+ if (cmd[0] === "bun" && cmd[1] === "pm")
368
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
369
+ if (cmd[0] === "npm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
370
+ if (cmd[0] === "bun" && cmd[1] === "install") return { exitCode: 0 };
371
+ return undefined;
372
+ });
373
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
374
+
375
+ const { result, out } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
376
+
377
+ expect(result).toBe(0);
378
+ expect(out).toEqual([`upgrading ${INSTALLED} → 9.9.9`]);
379
+ expect(calls[0]).toEqual(["bun", "pm", "ls", "-g"]);
380
+ expect(calls[1]).toEqual(["bun", "install", "-g", "@psimona/darkf@9.9.9"]);
381
+ expect(calls.some((cmd) => cmd[0] === "npm")).toBe(false); // npm never consulted
382
+ });
383
+
384
+ test("upgrade: falls back to npm when bun does not list the package", async () => {
385
+ const { spawnImpl, calls } = spawnStub((cmd) => {
386
+ if (cmd[0] === "bun" && cmd[1] === "pm") return { exitCode: 0, stdout: "nothing relevant" };
387
+ if (cmd[0] === "npm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
388
+ if (cmd[0] === "npm" && cmd[1] === "install") return { exitCode: 0 };
389
+ return undefined;
390
+ });
391
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
392
+
393
+ const { result } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
394
+
395
+ expect(result).toBe(0);
396
+ expect(calls.some((cmd) => cmd[0] === "npm" && cmd[1] === "install")).toBe(true);
397
+ expect(calls[calls.length - 1]).toEqual(["npm", "install", "-g", "@psimona/darkf@9.9.9"]);
398
+ });
399
+
400
+ test("upgrade: installer failure propagates its exit code and writes no state", async () => {
401
+ const file = tempStateFile();
402
+ const { spawnImpl } = spawnStub((cmd) => {
403
+ if (cmd[1] === "install") return { exitCode: 7 };
404
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
405
+ });
406
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
407
+
408
+ const { result } = await captured(() =>
409
+ upgradeCmd(deps({ stateFile: file, spawnImpl, fetchImpl })),
410
+ );
411
+
412
+ expect(result).toBe(7);
413
+ expect(rawFile(file)).toBeNull(); // a failed install leaves no record
414
+ });
415
+
416
+ test("upgrade: success clears latestSeen so no stale notice survives (REQ-7, REQ-8)", async () => {
417
+ const file = tempStateFile();
418
+ seedState(file, { lastCheck: new Date(NOW - HOUR_MS).toISOString(), latestSeen: "9.9.9" });
419
+ const { spawnImpl, calls } = spawnStub((cmd) => {
420
+ if (cmd[1] === "install") return { exitCode: 0 };
421
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
422
+ });
423
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
424
+
425
+ const { result } = await captured(() =>
426
+ upgradeCmd(deps({ stateFile: file, spawnImpl, fetchImpl, now: () => NOW })),
427
+ );
428
+
429
+ expect(result).toBe(0);
430
+ expect(calls[calls.length - 1]).toEqual(["bun", "install", "-g", "@psimona/darkf@9.9.9"]);
431
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() }); // latestSeen gone
432
+ });
433
+
434
+ // --- smoke: the real CLI entrypoint (no network; state seeded or opted out) ---
435
+
436
+ const pkgDir = resolve(import.meta.dir, "..", "..");
437
+ const indexTs = join(pkgDir, "src", "cli", "index.ts");
438
+ const installedVersion = (
439
+ JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as {
440
+ version: string;
441
+ }
442
+ ).version;
443
+
444
+ async function runRealCli(
445
+ args: string[],
446
+ stateHome: string,
447
+ extraEnv: Record<string, string> = {},
448
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
449
+ const proc = Bun.spawn([process.execPath, indexTs, ...args], {
450
+ cwd: tempDir(),
451
+ stdout: "pipe",
452
+ stderr: "pipe",
453
+ env: { ...process.env, XDG_STATE_HOME: stateHome, ...extraEnv },
454
+ });
455
+ const [stdout, stderr, code] = await Promise.all([
456
+ new Response(proc.stdout).text(),
457
+ new Response(proc.stderr).text(),
458
+ proc.exited,
459
+ ]);
460
+ return { code, stdout, stderr };
461
+ }
462
+
463
+ test("real CLI with the opt-out: no notice line and no state file (REQ-5, wiring)", async () => {
464
+ const stateHome = tempDir();
465
+ const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "1" });
466
+ expect(res.code).toBe(0);
467
+ expect(res.stdout).not.toContain("available");
468
+ expect(rawFile(join(stateHome, "darkf", "last-update-check.json"))).toBeNull();
469
+ });
470
+
471
+ test("real CLI with a fresh not-due record: the notice is the first stdout line, no request (REQ-3, REQ-11, NFR-3)", async () => {
472
+ const stateHome = tempDir();
473
+ seedState(join(stateHome, "darkf", "last-update-check.json"), {
474
+ // Fresh stamp: the gate must print from the record without any registry request.
475
+ lastCheck: new Date().toISOString(),
476
+ latestSeen: "99.0.0",
477
+ });
478
+
479
+ const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "" });
480
+
481
+ expect(res.code).toBe(0);
482
+ const firstLine = res.stdout.split("\n")[0];
483
+ expect(firstLine).toBe(
484
+ `darkf 99.0.0 available (installed ${installedVersion}) — run 'darkf upgrade'`,
485
+ );
486
+ });
@@ -0,0 +1,191 @@
1
+ // CLI self-update (docs/specs/self-update): a daily startup version check and
2
+ // the `darkf upgrade` command. Every dependency arrives via UpdateDeps, so the
3
+ // whole module runs in tests without network, a real clock, or a real package
4
+ // manager. No module-level mutable state.
5
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+
8
+ const PACKAGE_SPEC = "@psimona/darkf";
9
+ const REGISTRY_URL = "https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags";
10
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
11
+ const CHECK_TIMEOUT_MS = 2_000;
12
+ // Design-originated: no REQ covers probe duration; the cap bounds a hung
13
+ // package manager.
14
+ const PROBE_TIMEOUT_MS = 10_000;
15
+ // Trust boundary: the registry response is untrusted input. `latest` must
16
+ // match this before any argv uses it (design: Security Considerations).
17
+ const SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
18
+
19
+ export interface UpdateState {
20
+ lastCheck?: string; // ISO timestamp of the last check attempt
21
+ latestSeen?: string; // newest version known to exist; drives the notice
22
+ }
23
+
24
+ export interface UpdateDeps {
25
+ now(): number; // injectable clock
26
+ fetchImpl: typeof fetch; // injectable registry access
27
+ spawnImpl: typeof Bun.spawnSync; // injectable probes and installer
28
+ stateFile: string; // injectable state location
29
+ installed: string; // version from the package package.json
30
+ }
31
+
32
+ /** Absent or corrupt file returns {}. Never throws. */
33
+ export function readState(file: string): UpdateState {
34
+ try {
35
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
36
+ if (typeof parsed !== "object" || parsed === null) return {};
37
+ const rec = parsed as Record<string, unknown>;
38
+ const state: UpdateState = {};
39
+ if (typeof rec.lastCheck === "string") state.lastCheck = rec.lastCheck;
40
+ if (typeof rec.latestSeen === "string") state.latestSeen = rec.latestSeen;
41
+ return state;
42
+ } catch {
43
+ return {};
44
+ }
45
+ }
46
+
47
+ /** mkdir -p on the parent; best-effort — swallow write errors (REQ-4). */
48
+ export function writeState(file: string, state: UpdateState): void {
49
+ try {
50
+ mkdirSync(dirname(file), { recursive: true });
51
+ writeFileSync(file, JSON.stringify(state));
52
+ } catch {
53
+ // An unwritable state location degrades to re-checking next invocation.
54
+ }
55
+ }
56
+
57
+ /** True when lastCheck is missing, unparseable, or older than 24 h. */
58
+ export function isDue(state: UpdateState, now: number): boolean {
59
+ if (state.lastCheck === undefined) return true;
60
+ const last = Date.parse(state.lastCheck);
61
+ if (Number.isNaN(last)) return true;
62
+ return now - last >= CHECK_INTERVAL_MS;
63
+ }
64
+
65
+ /** Bun.semver.order(installed, latest) < 0. */
66
+ export function isNewer(installed: string, latest: string): boolean {
67
+ return Bun.semver.order(installed, latest) < 0;
68
+ }
69
+
70
+ /**
71
+ * GET the dist-tags endpoint with AbortSignal.timeout(2000). Returns `latest`
72
+ * when it is a semver-shaped string, else null. Never throws.
73
+ */
74
+ export async function checkRegistry(fetchImpl: typeof fetch): Promise<string | null> {
75
+ try {
76
+ const res = await fetchImpl(REGISTRY_URL, { signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
77
+ if (res.status !== 200) return null;
78
+ const tags: unknown = await res.json();
79
+ const latest =
80
+ typeof tags === "object" && tags !== null
81
+ ? (tags as Record<string, unknown>).latest
82
+ : undefined;
83
+ return typeof latest === "string" && SEMVER_RE.test(latest) ? latest : null;
84
+ } catch {
85
+ // Rejects, aborts, and malformed JSON are all the same silent no-op.
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The startup path, called from main() before command dispatch. Sends at most
92
+ * one registry request per invocation, bounded to one per 24 h across
93
+ * invocations (REQ-1, REQ-2). Silent by contract: every failure continues the
94
+ * started command with no added output (REQ-4).
95
+ */
96
+ export async function updateGate(cmd: string | undefined, deps: UpdateDeps): Promise<void> {
97
+ // `upgrade` fetches on its own; the opt-out never blocks it.
98
+ if (cmd === "upgrade") return;
99
+ // Opt-out (REQ-5): no state read, no request, no print.
100
+ if (process.env.DARKF_NO_UPDATE_CHECK) return;
101
+
102
+ const state = readState(deps.stateFile);
103
+ if (isDue(state, deps.now())) {
104
+ const latest = await checkRegistry(deps.fetchImpl);
105
+ // null (failed check): leave latestSeen untouched — a stale notice survives.
106
+ if (latest !== null) {
107
+ if (isNewer(deps.installed, latest)) state.latestSeen = latest;
108
+ else delete state.latestSeen;
109
+ }
110
+ // Stamp on attempt (REQ-2): a failed check counts as a check.
111
+ state.lastCheck = new Date(deps.now()).toISOString();
112
+ writeState(deps.stateFile, state);
113
+ }
114
+ // Notice from the record: no registry request (REQ-11), exactly one line,
115
+ // printed before dispatch so it is the first line of stdout (NFR-3).
116
+ if (state.latestSeen !== undefined && isNewer(deps.installed, state.latestSeen)) {
117
+ console.log(
118
+ `darkf ${state.latestSeen} available (installed ${deps.installed}) — run 'darkf upgrade'`,
119
+ );
120
+ }
121
+ }
122
+
123
+ /** Marker shared by `bun pm ls -g` and `npm ls -g --depth=0` output. */
124
+ const INSTALLED_MARKER = `${PACKAGE_SPEC}@`;
125
+
126
+ /** False when the manager fails, times out, or does not list the package. */
127
+ function probeManager(spawnImpl: typeof Bun.spawnSync, cmd: string[]): boolean {
128
+ let out: { exitCode: number; stdout: Buffer };
129
+ try {
130
+ out = spawnImpl(cmd, { timeout: PROBE_TIMEOUT_MS });
131
+ } catch {
132
+ return false;
133
+ }
134
+ if (out.exitCode !== 0) return false;
135
+ return new TextDecoder().decode(out.stdout).includes(INSTALLED_MARKER);
136
+ }
137
+
138
+ /**
139
+ * bun first (the darkf bin runs under bun by construction), then npm when
140
+ * present — so a pack:local snapshot resolves to bun (design: D-4).
141
+ */
142
+ function pickManager(spawnImpl: typeof Bun.spawnSync): "bun" | "npm" | null {
143
+ if (probeManager(spawnImpl, ["bun", "pm", "ls", "-g"])) return "bun";
144
+ if (Bun.which("npm") !== null && probeManager(spawnImpl, ["npm", "ls", "-g", "--depth=0"])) {
145
+ return "npm";
146
+ }
147
+ return null;
148
+ }
149
+
150
+ /**
151
+ * The `darkf upgrade` command. Loud where the startup gate is silent: registry
152
+ * and provenance failures print a one-line stderr reason and exit non-zero
153
+ * (REQ-9, REQ-10). Returns the process exit code.
154
+ */
155
+ export async function upgradeCmd(deps: UpdateDeps): Promise<number> {
156
+ const latest = await checkRegistry(deps.fetchImpl);
157
+ if (latest === null) {
158
+ console.error(
159
+ `update check failed: could not read the latest version of ${PACKAGE_SPEC} from the npm registry`,
160
+ );
161
+ return 1;
162
+ }
163
+ // Current, or a local snapshot newer than the published release: no
164
+ // downgrade (REQ-6).
165
+ if (Bun.semver.order(deps.installed, latest) >= 0) {
166
+ console.log(`darkf is current (installed ${deps.installed})`);
167
+ return 0;
168
+ }
169
+ const pm = pickManager(deps.spawnImpl);
170
+ if (pm === null) {
171
+ console.error("cannot determine how this darkf was installed — not managed by bun or npm");
172
+ return 1;
173
+ }
174
+ // The before/after line REQ-7 requires, printed before anything changes.
175
+ console.log(`upgrading ${deps.installed} → ${latest}`);
176
+ if (!SEMVER_RE.test(latest)) {
177
+ console.error(`registry returned a malformed version: ${JSON.stringify(latest)}`);
178
+ return 1;
179
+ }
180
+ // Argv array, never a shell string; stdio inherited so the installer's own
181
+ // output flows through (REQ-8, design: Security Considerations).
182
+ const install = deps.spawnImpl([pm, "install", "-g", `${PACKAGE_SPEC}@${latest}`], {
183
+ stdio: ["inherit", "inherit", "inherit"],
184
+ });
185
+ const code = install.exitCode;
186
+ // On success clear any stale record so no notice survives the upgrade.
187
+ if (code === 0) {
188
+ writeState(deps.stateFile, { lastCheck: new Date(deps.now()).toISOString() });
189
+ }
190
+ return code;
191
+ }