@psimona/darkf 0.3.0 → 0.5.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.
@@ -0,0 +1,29 @@
1
+ # Run feedback — self-update dev-loop run
2
+
3
+ - **Date:** 2026-10-30
4
+ - **Engine/workflow:** darkf dev-loop
5
+ - **Run:** c078c63d-399e-41b1-b0d3-90edccdec766
6
+ - **Final outcome:** Merged. `feature/self-update` squashed to master as `feat: self-update (self-update)` (2651989); branch deleted. Every state succeeded on attempt 1.
7
+ - **Scopes:** Shipped `darkf/src/cli/update.ts` and its test suite (24h gate, `DARKF_NO_UPDATE_CHECK` opt-out, one-line notice before dispatch, `upgrade` command), wired into `index.ts`, plus specs under `docs/specs/self-update/`.
8
+
9
+ ## What worked
10
+
11
+ - The full loop ran clean: Begin → Implement → Check → Review → Finish, one attempt per state, no retries.
12
+ - Implement detected the working tree already matched `docs/specs/self-update/design.md` and verified instead of rewriting.
13
+ - All gates passed on the first pass: 25/25 in `update.test.ts`, 162/162 across the full suite, secret-scan, typecheck, lint, arch-check clean.
14
+ - Coverage held at 95.61% funcs / 95.72% lines; `update.ts` at 100% funcs.
15
+ - Zero new dependencies; only `fetch`, `Bun.semver`, `node:fs`, `Bun.spawnSync`; `bun.lock` untouched.
16
+ - Review independently re-ran the tests and mapped REQ-1 through REQ-5 to code-level line references before approving.
17
+ - The real-CLI smoke tests keep the suite network-free by setting `DARKF_NO_UPDATE_CHECK=1`.
18
+
19
+ ## Failures and root causes
20
+
21
+ none observed
22
+
23
+ ## Notes
24
+
25
+ - The dev-loop workflow itself (`darkf/workflows/dev-loop/`) is untracked. It sits outside the self-update design scope, so the merge did not include it. Commit it separately so future runs are reproducible.
26
+ - This run's Implement step shortcut worked because the working tree already held the implementation. A run from a clean checkout will pay the full implementation cost; plan attempts accordingly.
27
+ - Total wall clock was about 3 minutes; heartbeats show roughly 30-60s of agent idle time per agent state (Implement, Review). Harmless, but it is most of the run time.
28
+ - `update.ts` lines 131 and 177-178 stay uncovered: a defensive semver re-check already guaranteed by `checkRegistry`. The reviewer accepted this; do not chase it.
29
+ - The implementer shipped two real-CLI smoke tests where the design says "one optional smoke test may". Permissive wording, no action needed.
@@ -0,0 +1,26 @@
1
+ # Run feedback — task-list-json
2
+
3
+ - **Date:** 2026-10-31
4
+ - **Engine/workflow:** darkf dev-loop
5
+ - **Run:** 7f95d772-b147-42d8-b40a-1e40b9ce51d5
6
+ - **Final outcome:** merged. Squashed `feature/task-list-json` to master as `feat: task-list-json (task-list-json)`; branch deleted. Confirmed in git log as `02a7aa2`.
7
+ - **Scopes:** TaskList support shipped end to end: `Task`/`TaskList` types in core, hand-written zero-dependency `parseTaskList`, `foldTaskList` in the kit, and a new tasks tab (absent/invalid/valid views, strict done/total, stall warning) in the opencode plugin overlay.
8
+
9
+ ## What worked
10
+
11
+ - One pass through the loop: Implement → Check → Fix → Check → Review approved → merged. No retry loops.
12
+ - All gates green at merge: secret-scan, typecheck, lint, arch-check, darkf 179 tests, plugin 12 tests, coverage at ~96% lines.
13
+ - Implementation matched the spec field for field (`docs/specs/task-list-json/spec.md`); the reviewer verified types, decisions, and tests against it and approved with no change requests.
14
+ - `parseTaskList` narrowing is proven by tests: legacy `moscow` and task-side `requirements` are dropped, bad unions and non-object roots rejected with path-prefixed errors.
15
+ - The plugin reads `tasks.json` via the existing 1s poll plus an `fs.watch` with the same retry-until-exists pattern as the journal watcher; teardown cleans up both.
16
+
17
+ ## Failures and root causes
18
+
19
+ 1. First Check gate failed on a biome format error in `darkf/workflows/dev-loop/scripts/finish.ts:17` (the `ALLOWED` array needed multi-line formatting). Root cause: this feature's own retarget commit (a054445) edited the finish script and committed it unformatted. The Implement summary then mislabeled it as "pre-existing and outside allowed paths". Cost: one extra Fix → Check cycle, about 3 minutes per journal timestamps (fail at 1793474949114, pass at 1793475128840).
20
+
21
+ ## Notes
22
+
23
+ - The dev-loop finish script (`darkf/workflows/dev-loop/scripts/finish.ts`) sits in the lint path. Any run that retargets it must format it before committing, or the Check gate will fail.
24
+ - When a failing file is outside the feature's allowed paths, check `git log`/`git blame` before calling it pre-existing. Here the implementing agent's claim was wrong and the fix step had to re-derive the cause.
25
+ - The spec's mention of item-loop.ts refers to the separate, not-yet-implemented item-loop-convention spec. No migration was required for this run. Future item-loop work will need it.
26
+ - No tasks.json was produced by this run itself; the feature only adds the consumer side. Exercise the producer path in a later run.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psimona/darkf",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "A small, typed workflow engine for agent + script state graphs.",
5
5
  "license": "MIT",
6
6
  "author": "Patrizio Simona <patriziosimona@gmail.com>",
@@ -61,6 +61,9 @@ async function runCli(
61
61
  cwd,
62
62
  stdout: "pipe",
63
63
  stderr: "pipe",
64
+ // Self-update gate: real-CLI spawns stay off the network and notice-free
65
+ // (no stdio changes to parse around), per the suite's no-network doctrine.
66
+ env: { ...process.env, DARKF_NO_UPDATE_CHECK: "1" },
64
67
  });
65
68
  const [stdout, stderr, code] = await Promise.all([
66
69
  new Response(proc.stdout).text(),
package/src/cli/index.ts CHANGED
@@ -4,6 +4,7 @@ import { closeSync, existsSync, openSync, readdirSync, readFileSync } from "node
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import packageJson from "../../package.json";
7
8
  import {
8
9
  type AgentRunner,
9
10
  buildRegistry,
@@ -47,6 +48,7 @@ import {
47
48
  stallWarning,
48
49
  type TerminalState,
49
50
  } from "../kit/status.ts";
51
+ import { type UpdateDeps, updateGate, upgradeCmd } from "./update.ts";
50
52
 
51
53
  const INDEX_PATH = fileURLToPath(import.meta.url);
52
54
  // Fixed, not yet measured against a cold `bun` import on real hosts — see
@@ -342,7 +344,7 @@ function parseRunArgs(args: string[]): {
342
344
 
343
345
  // Start-time config guard (registry-lifecycle, lesson-2 companion): a
344
346
  // workflow config edit left uncommitted *will* be swept into a run commit or
345
- // reset away by the run itself — blueprint lost config edits both ways.
347
+ // reset away by the run itself — a consumer repo lost config edits both ways.
346
348
  // Scoped to the bare `darkf/` directory — the user/consumer-repo convention
347
349
  // for versioned workflow config — never `.darkf` (dot-prefixed), which is
348
350
  // darkf's own runtime/run-storage directory (registry, journals, this very
@@ -438,7 +440,7 @@ async function runCmd(dir: string, message?: string): Promise<void> {
438
440
  if (result.node.phase === "succeeded" || result.node.phase === "failed") {
439
441
  console.log("output:", result.node.result.output);
440
442
  }
441
- console.log(`journal: ${resolve(dir, ".darkf", "run", result.runId, "journal.jsonl")}`);
443
+ console.log(`journal: ${join(rootDir, ".darkf", "run", result.runId, "journal.jsonl")}`);
442
444
 
443
445
  const lastState = result.trace.at(-1)?.state;
444
446
  if (lastState) {
@@ -786,7 +788,7 @@ function isHeartbeatEvent(events: NodeEvent[], index: number): boolean {
786
788
 
787
789
  // Dwell hint (P2): flag an open dispatch whose elapsed time exceeds 3× the
788
790
  // median of that node's completed visits (floor 2 min) — the supervisor's
789
- // cue to inspect or `steer`, printed once per visit. Blueprint E8.5b: a
791
+ // cue to inspect or `steer`, printed once per visit. An unattended run: a
790
792
  // GREEN agent thrashed for 35 minutes before anyone looked; a hint at
791
793
  // minute 10 would have surfaced it. Purely advisory — never exits.
792
794
  function dwellHint(events: NodeEvent[], runId: string, hinted: Set<string>): void {
@@ -964,9 +966,35 @@ async function monitorCmd(args: string[]): Promise<number> {
964
966
  }
965
967
  }
966
968
 
969
+ // Per-install state location for the self-update feature (self-update D-2):
970
+ // XDG state semantics, not `.darkf/` (NG-5 — nothing per-project). The first
971
+ // candidate whose defining environment variable exists wins; tests point
972
+ // elsewhere by injecting `stateFile` through UpdateDeps.
973
+ function updateStateFile(): string {
974
+ const xdg = process.env.XDG_STATE_HOME;
975
+ if (xdg) return join(xdg, "darkf", "last-update-check.json");
976
+ return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
977
+ }
978
+
967
979
  async function main(): Promise<void> {
968
980
  const [cmd, ...rest] = process.argv.slice(2);
969
981
 
982
+ // Self-update gate (REQ-1..REQ-5, REQ-11): runs before every dispatch, so
983
+ // its notice is the first line of stdout (NFR-3). The gate itself skips
984
+ // `upgrade`, which fetches on its own. Silent by contract (REQ-4).
985
+ const updateDeps: UpdateDeps = {
986
+ now: () => Date.now(),
987
+ fetchImpl: fetch,
988
+ spawnImpl: Bun.spawnSync,
989
+ stateFile: updateStateFile(),
990
+ installed: packageJson.version,
991
+ };
992
+ await updateGate(cmd, updateDeps);
993
+
994
+ if (cmd === "upgrade") {
995
+ process.exit(await upgradeCmd(updateDeps));
996
+ return;
997
+ }
970
998
  if (cmd === "workflows") {
971
999
  workflowsCmd();
972
1000
  return;
@@ -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
+ });