@psimona/darkf 0.8.0 → 0.10.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 (43) hide show
  1. package/docs/concepts/failure-modes.md +13 -3
  2. package/docs/concepts/handoff.md +5 -1
  3. package/docs/concepts/node-types.md +7 -5
  4. package/docs/guides/pick-an-agent-runner.md +24 -3
  5. package/docs/guides/plan-with-a-task-queue.md +15 -0
  6. package/docs/guides/run-detached-and-monitor.md +2 -1
  7. package/docs/guides/write-your-first-workflow.md +19 -3
  8. package/docs/reference/cli-commands.md +19 -0
  9. package/docs/reference/core-types.md +17 -2
  10. package/docs/start-here/quickstart.md +19 -0
  11. package/package.json +1 -1
  12. package/skills/darkf-usage/SKILL.md +17 -0
  13. package/skills/darkf-writing-workflows/SKILL.md +16 -18
  14. package/src/cli/changelog.test.ts +44 -0
  15. package/src/cli/changelog.ts +26 -0
  16. package/src/cli/detached.test.ts +27 -5
  17. package/src/cli/doctor.test.ts +67 -8
  18. package/src/cli/help.test.ts +92 -0
  19. package/src/cli/help.ts +164 -0
  20. package/src/cli/index.ts +119 -3
  21. package/src/cli/tarball.test.ts +8 -2
  22. package/src/cli/update.test.ts +85 -17
  23. package/src/cli/update.ts +41 -7
  24. package/src/core/graph.test.ts +154 -13
  25. package/src/core/graph.ts +13 -3
  26. package/src/core/types.ts +21 -1
  27. package/src/engine/identity-guard.test.ts +47 -0
  28. package/src/engine/run.test.ts +268 -25
  29. package/src/engine/run.ts +4 -4
  30. package/src/kit/agents/handoff.ts +1 -1
  31. package/src/kit/agents/opencode.test.ts +89 -12
  32. package/src/kit/agents/opencode.ts +73 -8
  33. package/src/kit/registry.ts +5 -0
  34. package/src/kit/specs.test.ts +2 -2
  35. package/src/kit/specs.ts +3 -6
  36. package/src/test/ok-output.ts +11 -0
  37. package/workflows/dev-loop/output-types.ts +43 -0
  38. package/workflows/dev-loop/scripts/begin.ts +2 -2
  39. package/workflows/dev-loop/scripts/dispatch.ts +3 -5
  40. package/workflows/dev-loop/scripts/finish.ts +2 -36
  41. package/workflows/dev-loop/workflow.ts +26 -14
  42. package/workflows/series-ordering/output-types.ts +9 -0
  43. package/workflows/series-ordering/workflow.ts +3 -0
package/src/cli/index.ts CHANGED
@@ -51,6 +51,8 @@ import {
51
51
  stallWarning,
52
52
  type TerminalState,
53
53
  } from "../kit/status.ts";
54
+ import { changelogHead } from "./changelog.ts";
55
+ import { resolveHelp } from "./help.ts";
54
56
  import {
55
57
  describeFailure,
56
58
  failingSkills,
@@ -60,7 +62,7 @@ import {
60
62
  skillsProbeGate,
61
63
  syncAll,
62
64
  } from "./setup.ts";
63
- import { type UpdateDeps, updateGate, upgradeWithSkills } from "./update.ts";
65
+ import { readState, type UpdateDeps, updateGate, upgradeWithSkills } from "./update.ts";
64
66
 
65
67
  const INDEX_PATH = fileURLToPath(import.meta.url);
66
68
  // Fixed, not yet measured against a cold `bun` import on real hosts — see
@@ -178,6 +180,7 @@ async function reportCmd(args: string[]): Promise<void> {
178
180
  const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;
179
181
  console.log(`run: ${entry.runId}`);
180
182
  console.log(`message: ${entry.message ?? "(none)"}`);
183
+ if (entry.engineVersion) console.log(`engine: ${entry.engineVersion}`);
181
184
  console.log(`span: ${seconds(report.spanMs)}, ${report.dispatches.length} dispatches`);
182
185
  const visits = Object.entries(report.visits);
183
186
  if (visits.length) console.log(`visits: ${JSON.stringify(Object.fromEntries(visits))}`);
@@ -248,6 +251,8 @@ function describeValidationError(err: WorkflowValidationError): string {
248
251
  return `"${err.state}": names no runner and the workflow has no default agentRunner`;
249
252
  case "missing-model":
250
253
  return `"${err.state}": no model, pin agent: { model } on the state or, without a runner, on the workflow`;
254
+ case "missing-output-type":
255
+ return `"${err.state}": agent leaf has no outputType — declare the schema of its handoff output (OutputSchema, see output-validation)`;
251
256
  }
252
257
  }
253
258
 
@@ -442,9 +447,65 @@ function doctorCmd(args: string[]): number {
442
447
  }
443
448
  }
444
449
 
450
+ // 4. version skew (self-update 2026-12-05): this CLI vs the @psimona/darkf
451
+ // this repo resolves, vs the newest release the update gate has recorded.
452
+ // The workflow code imports the project copy while the engine executing it
453
+ // is this CLI — a minor-version drift between them means validate and the
454
+ // run can disagree about structure rules. Offline: the published-newest
455
+ // side reads the recorded `latestSeen`, never the network.
456
+ const { installed, latestSeen } = updateVersions();
457
+ const published =
458
+ latestSeen !== undefined && Bun.semver.order(installed, latestSeen) < 0
459
+ ? `, published ${latestSeen} available — run: darkf upgrade`
460
+ : "";
461
+ const depVersion = readProjectDarkfVersion(projectRoot());
462
+ if (depVersion === undefined) {
463
+ check(
464
+ "darkf version skew",
465
+ true,
466
+ `engine ${installed}${published ? `${published}, no @psimona/darkf dependency here` : " current, no @psimona/darkf dependency here"}`,
467
+ );
468
+ } else {
469
+ const skew = skewBetween(installed, depVersion);
470
+ const detail = `engine ${installed}, dependency ${depVersion}${published}`;
471
+ check(
472
+ "darkf version skew",
473
+ skew === undefined,
474
+ skew === undefined ? detail : `${detail} — ${skew}`,
475
+ );
476
+ }
477
+
445
478
  return failed() ? 1 : 0;
446
479
  }
447
480
 
481
+ /** The version of the @psimona/darkf this repo resolves, or undefined when
482
+ * there is none (or its package.json is unreadable). */
483
+ function readProjectDarkfVersion(root: string): string | undefined {
484
+ try {
485
+ const pkg = JSON.parse(
486
+ readFileSync(join(root, "node_modules", "@psimona", "darkf", "package.json"), "utf8"),
487
+ ) as { version?: unknown };
488
+ return typeof pkg.version === "string" ? pkg.version : undefined;
489
+ } catch {
490
+ return undefined;
491
+ }
492
+ }
493
+
494
+ /** The engine's own version and the newest recorded published release. */
495
+ function updateVersions(): { installed: string; latestSeen?: string } {
496
+ return {
497
+ installed: packageJson.version,
498
+ latestSeen: readState(updateStateFile()).latestSeen,
499
+ };
500
+ }
501
+
502
+ /** Why the engine and the dependency versions disagree, or undefined when
503
+ * they agree on major.minor (patch drift is normal under a caret range). */
504
+ function skewBetween(engine: string, dep: string): string | undefined {
505
+ const mm = (v: string) => v.split(".").slice(0, 2).join(".");
506
+ return mm(engine) === mm(dep) ? undefined : "engine and dependency minor versions drift";
507
+ }
508
+
448
509
  function workflowsCmd(): void {
449
510
  const workflows = listWorkflows();
450
511
  if (workflows.length === 0) {
@@ -456,6 +517,20 @@ function workflowsCmd(): void {
456
517
  for (const w of workflows) console.log(`${w.name.padEnd(24)} ${w.source}`);
457
518
  }
458
519
 
520
+ /** The newest section of the installed package's changelog — the answer the
521
+ * upgrade notice points at. Read-only; a missing file prints one line, it
522
+ * never fails the command. */
523
+ function changelogCmd(): void {
524
+ let text: string;
525
+ try {
526
+ text = readFileSync(installedChangelogPath(), "utf8");
527
+ } catch {
528
+ console.log(`no changelog found at ${installedChangelogPath()}`);
529
+ return;
530
+ }
531
+ console.log(changelogHead(text));
532
+ }
533
+
459
534
  async function renderCmd(dir: string): Promise<void> {
460
535
  const { workflow } = await loadWorkflow(dir);
461
536
  console.log(renderMermaid(workflow));
@@ -531,6 +606,7 @@ async function runCmd(dir: string, message?: string): Promise<void> {
531
606
  status: "running",
532
607
  finishedAt: null,
533
608
  agentRunnerKind: agentRunner?.kind,
609
+ engineVersion: packageJson.version,
534
610
  ...detectSupervisorSignal(),
535
611
  });
536
612
 
@@ -667,6 +743,7 @@ async function startCmd(
667
743
  finishedAt: Date.now(),
668
744
  startFailureDetail: tail,
669
745
  bootId,
746
+ engineVersion: packageJson.version,
670
747
  ...detectSupervisorSignal(),
671
748
  });
672
749
  return 1;
@@ -696,6 +773,7 @@ async function startCmd(
696
773
  status: "running",
697
774
  finishedAt: null,
698
775
  bootId,
776
+ engineVersion: packageJson.version,
699
777
  ...detectSupervisorSignal(),
700
778
  });
701
779
 
@@ -799,6 +877,7 @@ function printDigest(entry: RegistryEntry, state: TerminalState, journalText: st
799
877
  console.log(`run: ${entry.runId}`);
800
878
  console.log(`root: ${entry.rootDir}`);
801
879
  if (entry.message) console.log(`message: ${entry.message}`);
880
+ if (entry.engineVersion) console.log(`engine: ${entry.engineVersion}`);
802
881
  console.log(`state: ${state}`);
803
882
  if (digest.current) {
804
883
  console.log(`current node: ${digest.current.state} (${digest.current.phase})`);
@@ -1125,6 +1204,21 @@ function updateStateFile(): string {
1125
1204
  return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
1126
1205
  }
1127
1206
 
1207
+ // The update cadence tunable (self-update 2026-12-05): XDG config semantics —
1208
+ // `~/.config/darkf/config.json`, `{"checkIntervalHours": 24}` restores the
1209
+ // once-per-interval check for hosts that must not pay a registry request per
1210
+ // command. Absent file = check every invocation.
1211
+ function updateConfigFile(): string {
1212
+ const xdg = process.env.XDG_CONFIG_HOME;
1213
+ if (xdg) return join(xdg, "darkf", "config.json");
1214
+ return join(process.env.HOME ?? "", ".config", "darkf", "config.json");
1215
+ }
1216
+
1217
+ // The installed package's own changelog, for `darkf changelog`.
1218
+ function installedChangelogPath(): string {
1219
+ return resolve(dirname(INDEX_PATH), "..", "..", "CHANGELOG.md");
1220
+ }
1221
+
1128
1222
  // Same XDG state scheme, for the daily skills probe (skill-setup spec).
1129
1223
  function skillsProbeStateFile(): string {
1130
1224
  const xdg = process.env.XDG_STATE_HOME;
@@ -1150,6 +1244,15 @@ function probeDeps(): ProbeDeps {
1150
1244
  async function main(): Promise<void> {
1151
1245
  const [cmd, ...rest] = process.argv.slice(2);
1152
1246
 
1247
+ // Help (docs/specs/_built/cli-help/spec.md): answered before the gates below, so
1248
+ // it stays offline and writes no state (REQ-4).
1249
+ const help = resolveHelp(process.argv.slice(2));
1250
+ if (help) {
1251
+ if (help.stdout) process.stdout.write(help.stdout);
1252
+ if (help.stderr) process.stderr.write(help.stderr);
1253
+ process.exit(help.code);
1254
+ }
1255
+
1153
1256
  // Self-update gate (REQ-1..REQ-5, REQ-11): runs before every dispatch, so
1154
1257
  // its notice is the first line of stdout (NFR-3). The gate itself skips
1155
1258
  // `upgrade`, which fetches on its own. Silent by contract (REQ-4).
@@ -1158,6 +1261,7 @@ async function main(): Promise<void> {
1158
1261
  fetchImpl: fetch,
1159
1262
  spawnImpl: Bun.spawnSync,
1160
1263
  stateFile: updateStateFile(),
1264
+ configFile: updateConfigFile(),
1161
1265
  installed: packageJson.version,
1162
1266
  };
1163
1267
  await updateGate(cmd, updateDeps);
@@ -1184,6 +1288,10 @@ async function main(): Promise<void> {
1184
1288
  workflowsCmd();
1185
1289
  return;
1186
1290
  }
1291
+ if (cmd === "changelog") {
1292
+ changelogCmd();
1293
+ return;
1294
+ }
1187
1295
  if (cmd === "report") {
1188
1296
  await reportCmd(rest);
1189
1297
  return;
@@ -1222,8 +1330,16 @@ async function main(): Promise<void> {
1222
1330
  await workerCmd(rest[0] ?? ".", rest[1] ?? "", rest[2]);
1223
1331
  return;
1224
1332
  }
1225
- // back-compat: `darkf <dir>` defaults to run
1226
- await runCmd(resolveWorkflowDir(cmd ?? "."), undefined);
1333
+ // A bare `darkf` keeps running the workflow in the current directory.
1334
+ // Any other unknown word is not a workflow reference: `darkf run` is the
1335
+ // only way to run one.
1336
+ if (cmd === undefined) {
1337
+ await runCmd(resolveWorkflowDir("."), undefined);
1338
+ return;
1339
+ }
1340
+ console.error(`darkf: unknown command '${cmd}'. To run a workflow: darkf run ${cmd}`);
1341
+ console.error(" list the commands: darkf --help");
1342
+ process.exit(2);
1227
1343
  }
1228
1344
 
1229
1345
  // Dispatch only when this file is the process entry point — the `darkf` bin,
@@ -13,8 +13,14 @@ const pkgDir = resolve(import.meta.dir, "..", "..");
13
13
 
14
14
  test("tarball smoke: allowlist ships the runtime dirs and the installed CLI works", async () => {
15
15
  const npm = Bun.which("npm");
16
- if (!npm) {
17
- console.warn("npm not on PATH — skipping tarball smoke test");
16
+ // Some boxes carry an npm shim that only forwards run/test/build to bun
17
+ // (node/npm not installed). The smoke test needs a real `npm pack`, so a
18
+ // shim that cannot even report a version skips it, same as no npm.
19
+ const probe = npm
20
+ ? Bun.spawnSync([npm, "--version"], { stdout: "pipe", stderr: "pipe" })
21
+ : undefined;
22
+ if (!npm || probe?.exitCode !== 0) {
23
+ console.warn("npm not usable — skipping tarball smoke test");
18
24
  return;
19
25
  }
20
26
 
@@ -8,6 +8,7 @@ import {
8
8
  isDue,
9
9
  isNewer,
10
10
  readState,
11
+ readUpdateConfig,
11
12
  type UpdateDeps,
12
13
  updateGate,
13
14
  upgradeCmd,
@@ -21,6 +22,10 @@ const NOW = 1_793_000_000_000; // fixed epoch ms; every test's "today"
21
22
  const INSTALLED = "0.3.0";
22
23
  const HOUR_MS = 60 * 60 * 1000;
23
24
 
25
+ // The one notice line (REQ-3), with the changelog pointer (2026-12-05).
26
+ const NOTICE = (latest: string) =>
27
+ `darkf ${latest} available (installed ${INSTALLED}) — run 'darkf upgrade'; 'darkf changelog' shows what changed`;
28
+
24
29
  const roots: string[] = [];
25
30
  afterAll(() => {
26
31
  for (const root of roots) rmSync(root, { recursive: true, force: true });
@@ -60,11 +65,17 @@ function deps(overrides: Partial<UpdateDeps> = {}): UpdateDeps {
60
65
  throw new Error("unexpected spawn");
61
66
  }) as unknown as typeof Bun.spawnSync,
62
67
  stateFile: tempStateFile(),
68
+ configFile: join(tempDir(), "config", "darkf", "config.json"), // absent by default
63
69
  installed: INSTALLED,
64
70
  ...overrides,
65
71
  };
66
72
  }
67
73
 
74
+ function seedConfig(file: string, body: string): void {
75
+ mkdirSync(dirname(file), { recursive: true });
76
+ writeFileSync(file, body);
77
+ }
78
+
68
79
  /** 200-with-body fetch unless a status is given; records the requested URLs. */
69
80
  function fetchReturning(body: string, status = 200): { fetchImpl: typeof fetch; urls: string[] } {
70
81
  const urls: string[] = [];
@@ -158,13 +169,43 @@ test("isNewer: older, equal, newer, prerelease", () => {
158
169
  expect(isNewer("0.3.0", "0.4.0-beta.1")).toBe(true);
159
170
  });
160
171
 
161
- test("isDue: missing, corrupt, fresh, and the 24h boundary", () => {
172
+ test("isDue: no interval (default config) — every invocation is due", () => {
162
173
  expect(isDue({}, NOW)).toBe(true);
163
- expect(isDue({ lastCheck: "not a timestamp" }, NOW)).toBe(true);
164
- expect(isDue({ lastCheck: new Date(NOW - 23 * HOUR_MS).toISOString() }, NOW)).toBe(false);
165
- // Data model: now - lastCheck >= 24h — exactly one day is due again.
166
- expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS).toISOString() }, NOW)).toBe(true);
167
- expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS + 1000).toISOString() }, NOW)).toBe(false);
174
+ const fresh = { lastCheck: new Date(NOW - 1000).toISOString() };
175
+ expect(isDue(fresh, NOW)).toBe(true);
176
+ expect(isDue(fresh, NOW, 0)).toBe(true);
177
+ });
178
+
179
+ test("isDue: with a configured interval, the 24h boundary governs", () => {
180
+ const day = 24 * HOUR_MS * 1000;
181
+ expect(isDue({}, NOW, day)).toBe(true);
182
+ expect(isDue({ lastCheck: "not a timestamp" }, NOW, day)).toBe(true);
183
+ expect(isDue({ lastCheck: new Date(NOW - 23 * HOUR_MS).toISOString() }, NOW, day)).toBe(false);
184
+ // Data model: now - lastCheck >= interval — exactly one day is due again.
185
+ expect(isDue({ lastCheck: new Date(NOW - day).toISOString() }, NOW, day)).toBe(true);
186
+ expect(isDue({ lastCheck: new Date(NOW - day + 1000).toISOString() }, NOW, day)).toBe(false);
187
+ });
188
+
189
+ // --- config file ---
190
+
191
+ test("readUpdateConfig: absent, corrupt, and wrong-shaped files read as no interval", () => {
192
+ expect(readUpdateConfig(join(tempDir(), "absent.json"))).toEqual({});
193
+ const dir = tempDir();
194
+ const corrupt = join(dir, "config.json");
195
+ writeFileSync(corrupt, "{not json");
196
+ expect(readUpdateConfig(corrupt)).toEqual({});
197
+ const wrong = join(dir, "wrong.json");
198
+ writeFileSync(wrong, JSON.stringify({ checkIntervalHours: "24" }));
199
+ expect(readUpdateConfig(wrong)).toEqual({});
200
+ const zero = join(dir, "zero.json");
201
+ writeFileSync(zero, JSON.stringify({ checkIntervalHours: 0 }));
202
+ expect(readUpdateConfig(zero)).toEqual({});
203
+ });
204
+
205
+ test("readUpdateConfig: a positive interval round-trips", () => {
206
+ const file = join(tempDir(), "config.json");
207
+ seedConfig(file, JSON.stringify({ checkIntervalHours: 24 }));
208
+ expect(readUpdateConfig(file)).toEqual({ checkIntervalHours: 24 });
168
209
  });
169
210
 
170
211
  // --- state file ---
@@ -238,7 +279,7 @@ test("gate on a due day: one request, stamped, newer latestSeen recorded, one no
238
279
  );
239
280
 
240
281
  expect(urls).toEqual(["https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags"]);
241
- expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
282
+ expect(out).toEqual([NOTICE("9.9.9")]);
242
283
  expect(err).toEqual([]);
243
284
  expect(readState(file)).toEqual({
244
285
  lastCheck: new Date(NOW).toISOString(),
@@ -246,19 +287,32 @@ test("gate on a due day: one request, stamped, newer latestSeen recorded, one no
246
287
  });
247
288
  });
248
289
 
249
- test("gate same-day re-run: no request, notice still printed from the record (REQ-2, REQ-11)", async () => {
290
+ test("gate with the default config: every invocation checks", async () => {
250
291
  const file = tempStateFile();
251
292
  const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
252
293
  await captured(() => updateGate("run", deps({ stateFile: file, fetchImpl })));
253
294
  expect(count()).toBe(1);
254
295
 
255
296
  const later = await captured(() =>
256
- updateGate("run", deps({ stateFile: file, fetchImpl, now: () => NOW + 3 * HOUR_MS })),
297
+ updateGate("run", deps({ stateFile: file, fetchImpl, now: () => NOW + 1000 })),
257
298
  );
258
- expect(count()).toBe(1); // no second request within 24 h
259
- expect(later.out).toEqual([
260
- `darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`,
261
- ]);
299
+ expect(count()).toBe(2); // no 24h gate without a configured interval
300
+ expect(later.out).toEqual([NOTICE("9.9.9")]);
301
+ });
302
+
303
+ test("gate with a configured 24h interval: one request per day, notice from the record between checks", async () => {
304
+ const file = tempStateFile();
305
+ const config = join(tempDir(), "config.json");
306
+ seedConfig(config, JSON.stringify({ checkIntervalHours: 24 }));
307
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
308
+ const base = deps({ stateFile: file, configFile: config, fetchImpl });
309
+
310
+ await captured(() => updateGate("run", base));
311
+ expect(count()).toBe(1);
312
+
313
+ const later = await captured(() => updateGate("run", { ...base, now: () => NOW + 3 * HOUR_MS }));
314
+ expect(count()).toBe(1); // no second request within the configured interval
315
+ expect(later.out).toEqual([NOTICE("9.9.9")]);
262
316
  });
263
317
 
264
318
  test("gate: a failed check still stamps and prints nothing (REQ-2, REQ-4)", async () => {
@@ -276,7 +330,7 @@ test("gate: a stale notice survives a failed check (REQ-11)", async () => {
276
330
 
277
331
  const { out } = await captured(() => updateGate("status", deps({ stateFile: file })));
278
332
 
279
- expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
333
+ expect(out).toEqual([NOTICE("9.9.9")]);
280
334
  expect(readState(file)).toEqual({
281
335
  lastCheck: new Date(NOW).toISOString(), // restamped by the failed attempt
282
336
  latestSeen: "9.9.9", // untouched by the null result
@@ -470,23 +524,37 @@ test("real CLI with the opt-out: no notice line and no state file (REQ-5, wiring
470
524
  expect(rawFile(join(stateHome, "darkf", "last-update-check.json"))).toBeNull();
471
525
  });
472
526
 
473
- 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 () => {
527
+ test("real CLI, configured interval, fresh record: the notice is the first stdout line, no request (REQ-3, REQ-11, NFR-3)", async () => {
474
528
  const stateHome = tempDir();
529
+ const configHome = tempDir();
475
530
  seedState(join(stateHome, "darkf", "last-update-check.json"), {
476
531
  // Fresh stamp: the gate must print from the record without any registry request.
477
532
  lastCheck: new Date().toISOString(),
478
533
  latestSeen: "99.0.0",
479
534
  });
535
+ // The 24h interval keeps the real CLI off the network — the seeded record
536
+ // drives the notice. This also proves the config file wiring end to end.
537
+ seedConfig(join(configHome, "darkf", "config.json"), JSON.stringify({ checkIntervalHours: 24 }));
480
538
 
481
- const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "" });
539
+ const res = await runRealCli(["workflows"], stateHome, {
540
+ DARKF_NO_UPDATE_CHECK: "",
541
+ XDG_CONFIG_HOME: configHome,
542
+ });
482
543
 
483
544
  expect(res.code).toBe(0);
484
545
  const firstLine = res.stdout.split("\n")[0];
485
546
  expect(firstLine).toBe(
486
- `darkf 99.0.0 available (installed ${installedVersion}) — run 'darkf upgrade'`,
547
+ `darkf 99.0.0 available (installed ${installedVersion}) — run 'darkf upgrade'; 'darkf changelog' shows what changed`,
487
548
  );
488
549
  });
489
550
 
551
+ test("real CLI, no config: the gate checks and the record notice still names the changelog command", async () => {
552
+ const stateHome = tempDir();
553
+ const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "1" });
554
+ expect(res.code).toBe(0);
555
+ expect(res.stdout.split("\n")[0]).not.toContain("available");
556
+ });
557
+
490
558
  // --- upgrade + skills sync (skill-setup spec) ---
491
559
 
492
560
  const SKILL_BUNDLED = "bundled skill body\n";
package/src/cli/update.ts CHANGED
@@ -1,14 +1,19 @@
1
- // CLI self-update (docs/specs/_built/self-update): a daily startup version check and
1
+ // CLI self-update (docs/specs/_built/self-update): a startup version check and
2
2
  // the `darkf upgrade` command. Every dependency arrives via UpdateDeps, so the
3
3
  // whole module runs in tests without network, a real clock, or a real package
4
4
  // manager. No module-level mutable state.
5
+ //
6
+ // 2026-12-05 revision: the check runs on EVERY invocation by default (a
7
+ // release lands, and the very next darkf command knows about it). A config
8
+ // file can restore the old once-per-24h cadence for hosts that must not pay
9
+ // the registry request per command (`updateCheckIntervalHours`). The notice
10
+ // itself never needs the network — it prints from the recorded `latestSeen`.
5
11
  import { readFileSync } from "node:fs";
6
12
  import { type SkillsDeps, syncAll } from "./setup.ts";
7
13
  import { writeJsonState } from "./state-file.ts";
8
14
 
9
15
  const PACKAGE_SPEC = "@psimona/darkf";
10
16
  const REGISTRY_URL = "https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags";
11
- const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
12
17
  const CHECK_TIMEOUT_MS = 2_000;
13
18
  // Design-originated: no REQ covers probe duration; the cap bounds a hung
14
19
  // package manager.
@@ -22,11 +27,19 @@ export interface UpdateState {
22
27
  latestSeen?: string; // newest version known to exist; drives the notice
23
28
  }
24
29
 
30
+ /** The one tunable. Absent, zero, or corrupt → check every invocation.
31
+ * A positive value restores the once-per-interval cadence (24 h in the
32
+ * pre-2026-12-05 releases). */
33
+ export interface UpdateConfig {
34
+ checkIntervalHours?: number;
35
+ }
36
+
25
37
  export interface UpdateDeps {
26
38
  now(): number; // injectable clock
27
39
  fetchImpl: typeof fetch; // injectable registry access
28
40
  spawnImpl: typeof Bun.spawnSync; // injectable probes and installer
29
41
  stateFile: string; // injectable state location
42
+ configFile: string; // injectable config location
30
43
  installed: string; // version from the package package.json
31
44
  }
32
45
 
@@ -45,17 +58,36 @@ export function readState(file: string): UpdateState {
45
58
  }
46
59
  }
47
60
 
61
+ /** Absent, corrupt, or wrong-shaped config reads as "no interval set". */
62
+ export function readUpdateConfig(file: string): UpdateConfig {
63
+ try {
64
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
65
+ if (typeof parsed !== "object" || parsed === null) return {};
66
+ const rec = parsed as Record<string, unknown>;
67
+ const value = rec.checkIntervalHours;
68
+ return typeof value === "number" && Number.isFinite(value) && value > 0
69
+ ? { checkIntervalHours: value }
70
+ : {};
71
+ } catch {
72
+ return {};
73
+ }
74
+ }
75
+
48
76
  /** mkdir -p on the parent; best-effort — swallow write errors (REQ-4). */
49
77
  export function writeState(file: string, state: UpdateState): void {
50
78
  writeJsonState(file, state);
51
79
  }
52
80
 
53
- /** True when lastCheck is missing, unparseable, or older than 24 h. */
54
- export function isDue(state: UpdateState, now: number): boolean {
81
+ /** True when the check should run now. With `intervalMs` 0 (the default
82
+ * config) every invocation is due. With a positive interval, the first
83
+ * invocation ever, an unparseable stamp, and an interval-old stamp are due
84
+ * — exactly one day is due again. */
85
+ export function isDue(state: UpdateState, now: number, intervalMs = 0): boolean {
86
+ if (intervalMs <= 0) return true;
55
87
  if (state.lastCheck === undefined) return true;
56
88
  const last = Date.parse(state.lastCheck);
57
89
  if (Number.isNaN(last)) return true;
58
- return now - last >= CHECK_INTERVAL_MS;
90
+ return now - last >= intervalMs;
59
91
  }
60
92
 
61
93
  /** Bun.semver.order(installed, latest) < 0. */
@@ -95,8 +127,10 @@ export async function updateGate(cmd: string | undefined, deps: UpdateDeps): Pro
95
127
  // Opt-out (REQ-5): no state read, no request, no print.
96
128
  if (process.env.DARKF_NO_UPDATE_CHECK) return;
97
129
 
130
+ const config = readUpdateConfig(deps.configFile);
131
+ const intervalMs = (config.checkIntervalHours ?? 0) * 60 * 60 * 1000;
98
132
  const state = readState(deps.stateFile);
99
- if (isDue(state, deps.now())) {
133
+ if (isDue(state, deps.now(), intervalMs)) {
100
134
  const latest = await checkRegistry(deps.fetchImpl);
101
135
  // null (failed check): leave latestSeen untouched — a stale notice survives.
102
136
  if (latest !== null) {
@@ -111,7 +145,7 @@ export async function updateGate(cmd: string | undefined, deps: UpdateDeps): Pro
111
145
  // printed before dispatch so it is the first line of stdout (NFR-3).
112
146
  if (state.latestSeen !== undefined && isNewer(deps.installed, state.latestSeen)) {
113
147
  console.log(
114
- `darkf ${state.latestSeen} available (installed ${deps.installed}) — run 'darkf upgrade'`,
148
+ `darkf ${state.latestSeen} available (installed ${deps.installed}) — run 'darkf upgrade'; 'darkf changelog' shows what changed`,
115
149
  );
116
150
  }
117
151
  }