@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
@@ -1,6 +1,14 @@
1
1
  import { afterAll, expect, test } from "bun:test";
2
2
  import { randomUUID } from "node:crypto";
3
- import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import {
4
+ cpSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readFileSync,
8
+ rmSync,
9
+ symlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
4
12
  import { tmpdir } from "node:os";
5
13
  import { dirname, join, resolve } from "node:path";
6
14
  import { parseEventLog } from "../core/index.ts";
@@ -19,6 +27,9 @@ import {
19
27
  const pkgDir = resolve(import.meta.dir, "..", "..");
20
28
  const repoRoot = resolve(pkgDir, "..");
21
29
  const indexTs = join(pkgDir, "src", "cli", "index.ts");
30
+ const installedVersion = (
31
+ JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as { version: string }
32
+ ).version;
22
33
  const haikuExample = join(pkgDir, "examples", "haiku-readme");
23
34
 
24
35
  const roots: string[] = [];
@@ -40,6 +51,10 @@ function makeProjectRoot(): string {
40
51
  mkdirSync(join(root, ".git"));
41
52
  mkdirSync(join(root, "node_modules", "@psimona"), { recursive: true });
42
53
  symlinkSync(join(repoRoot, "darkf"), join(root, "node_modules", "@psimona", "darkf"));
54
+ // A real install of @psimona/darkf pulls its one runtime dependency (zod)
55
+ // into the project's node_modules; the shipped examples' schema files
56
+ // import it, so the simulated root needs it too.
57
+ symlinkSync(join(repoRoot, "darkf", "node_modules", "zod"), join(root, "node_modules", "zod"));
43
58
  return root;
44
59
  }
45
60
 
@@ -134,7 +149,7 @@ export const agentRunner: AgentRunner = {
134
149
  export const workflow: WorkflowDef = {
135
150
  initial: "Plan",
136
151
  states: {
137
- Plan: { type: "agent", agent: { model: "test-model" }, prompt: "plan", on: { approved: "Implement" } },
152
+ Plan: { type: "agent", agent: { model: "test-model" }, prompt: "plan", outputType: { safeParse: () => ({ success: true }) }, on: { approved: "Implement" } },
138
153
  Implement: {
139
154
  initial: "Write",
140
155
  states: {
@@ -142,7 +157,7 @@ export const workflow: WorkflowDef = {
142
157
  Test: { type: "script", file: "test.ts", on: { passed: "Review" } },
143
158
  },
144
159
  },
145
- Review: { type: "agent", agent: { model: "test-model" }, prompt: "review", on: { done: EXIT } },
160
+ Review: { type: "agent", agent: { model: "test-model" }, prompt: "review", outputType: { safeParse: () => ({ success: true }) }, on: { done: EXIT } },
146
161
  },
147
162
  };
148
163
  `,
@@ -256,6 +271,13 @@ test("status and monitor report succeeded for a detached run", async () => {
256
271
  expect(st.code).toBe(0);
257
272
  expect(st.stdout).toContain("state: succeeded");
258
273
  expect(st.stdout).toContain(`run: ${runId}`);
274
+ // The engine that started the run is stamped and printed (2026-12-05).
275
+ expect(readEntry(root, runId)?.engineVersion).toBe(installedVersion);
276
+ expect(st.stdout).toContain(`engine: ${installedVersion}`);
277
+
278
+ const rep = await runCli(["report", "--run", runId], root);
279
+ expect(rep.code).toBe(0);
280
+ expect(rep.stdout).toContain(`engine: ${installedVersion}`);
259
281
 
260
282
  const mon = await runCli(["monitor", "--run", runId], root);
261
283
  expect(mon.code).toBe(0);
@@ -320,8 +342,8 @@ export const agentRunners: Record<string, AgentRunner> = {
320
342
  export const workflow: WorkflowDef = {
321
343
  initial: "A",
322
344
  states: {
323
- A: { type: "agent", agent: { model: "test-model" }, prompt: "a", next: "B" },
324
- B: { type: "agent", runner: "other", agent: { model: "test-model" }, prompt: "b", next: EXIT },
345
+ A: { type: "agent", agent: { model: "test-model" }, prompt: "a", outputType: { safeParse: () => ({ success: true }) }, next: "B" },
346
+ B: { type: "agent", runner: "other", agent: { model: "test-model" }, prompt: "b", outputType: { safeParse: () => ({ success: true }) }, next: EXIT },
325
347
  },
326
348
  };
327
349
  `,
@@ -22,6 +22,11 @@ const pkgDir = resolve(import.meta.dir, "..", "..");
22
22
  const indexTs = join(pkgDir, "src", "cli", "index.ts");
23
23
  const bundledDir = join(pkgDir, "skills");
24
24
  const SKILLS = ["darkf-usage", "darkf-writing-workflows"];
25
+ // The CLI's own version — the engine side of the doctor skew check.
26
+ const installedVersion = (
27
+ JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as { version: string }
28
+ ).version;
29
+ const skewMajorMinor = installedVersion.split(".").slice(0, 2).join(".");
25
30
 
26
31
  const roots: string[] = [];
27
32
  afterAll(() => {
@@ -152,6 +157,60 @@ test("doctor reports a missing copy and fails the exit code", async () => {
152
157
  );
153
158
  expect(res.code).toBe(1);
154
159
  });
160
+ test("doctor reports no skew line failure when the repo has no darkf dependency", async () => {
161
+ const env = makeEnv({ git: true });
162
+ const res = await runCli(["doctor"], env);
163
+ const line = lines(res.stdout).find((l) => l.includes("darkf version skew"));
164
+ expect(line).toBeDefined();
165
+ expect(line).toContain("no @psimona/darkf dependency here");
166
+ });
167
+
168
+ test("doctor reports matching engine and dependency versions as ok", async () => {
169
+ const env = makeEnv({ git: true });
170
+ const depDir = join(env.cwd, "node_modules", "@psimona", "darkf");
171
+ mkdirSync(depDir, { recursive: true });
172
+ writeFileSync(
173
+ join(depDir, "package.json"),
174
+ JSON.stringify({ name: "@psimona/darkf", version: `${skewMajorMinor}.99` }),
175
+ );
176
+
177
+ const res = await runCli(["doctor"], env);
178
+ const line = lines(res.stdout).find((l) => l.includes("darkf version skew"));
179
+ expect(line).toContain(`engine ${installedVersion}, dependency ${skewMajorMinor}.99`);
180
+ expect(line?.startsWith("ok")).toBe(true);
181
+ });
182
+
183
+ test("doctor FAILs when the dependency minor drifts from the engine", async () => {
184
+ const env = makeEnv({ git: true });
185
+ const depDir = join(env.cwd, "node_modules", "@psimona", "darkf");
186
+ mkdirSync(depDir, { recursive: true });
187
+ const [maj, min] = skewMajorMinor.split(".");
188
+ writeFileSync(
189
+ join(depDir, "package.json"),
190
+ JSON.stringify({ name: "@psimona/darkf", version: `${maj}.${Number(min) + 1}.0` }),
191
+ );
192
+
193
+ const res = await runCli(["doctor"], env);
194
+ const line = lines(res.stdout).find((l) => l.includes("darkf version skew"));
195
+ expect(line).toContain("engine and dependency minor versions drift");
196
+ expect(line?.startsWith("FAIL")).toBe(true);
197
+ expect(res.code).toBe(1);
198
+ });
199
+
200
+ test("doctor names a published newer release from the update record", async () => {
201
+ const env = makeEnv({ git: true });
202
+ const updateState = join(env.stateHome, "darkf", "last-update-check.json");
203
+ mkdirSync(join(updateState, ".."), { recursive: true });
204
+ writeFileSync(
205
+ updateState,
206
+ JSON.stringify({ lastCheck: new Date().toISOString(), latestSeen: "99.0.0" }),
207
+ );
208
+
209
+ const res = await runCli(["doctor"], env);
210
+ const line = lines(res.stdout).find((l) => l.includes("darkf version skew"));
211
+ expect(line).toContain("published 99.0.0 available — run: darkf upgrade");
212
+ });
213
+
155
214
  test("doctor <ref> prints the new usage and exits 1", async () => {
156
215
  const env = makeEnv({ git: true });
157
216
  const res = await runCli(["doctor", "my-workflow"], env);
@@ -184,7 +243,7 @@ test("validate inherits the workflow checks: happy path, same lines, exit 0", as
184
243
  const dir = writeFixture(
185
244
  env,
186
245
  "happy",
187
- `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", on: { done: EXIT } }`,
246
+ `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) }, on: { done: EXIT } }`,
188
247
  );
189
248
 
190
249
  const res = await runCli(["validate", dir], env);
@@ -206,7 +265,7 @@ test("validate reports unresolved targets", async () => {
206
265
  const dir = writeFixture(
207
266
  env,
208
267
  "unresolved",
209
- `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", on: { done: "nope" } }`,
268
+ `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) }, on: { done: "nope" } }`,
210
269
  );
211
270
  const res = await runCli(["validate", dir], env);
212
271
  expect(lines(res.stdout)).toContain('FAIL workflow structure — A -> "nope": no such state');
@@ -218,7 +277,7 @@ test("validate reports an agent state with no model, and accepts the workflow de
218
277
  const bare = writeFixture(
219
278
  env,
220
279
  "no-model",
221
- `A: { type: "agent", prompt: "p", on: { done: EXIT } }`,
280
+ `A: { type: "agent", prompt: "p", outputType: { safeParse: () => ({ success: true }) }, on: { done: EXIT } }`,
222
281
  );
223
282
 
224
283
  const res = await runCli(["validate", bare], env);
@@ -231,7 +290,7 @@ test("validate reports an agent state with no model, and accepts the workflow de
231
290
  const defaulted = writeFixture(
232
291
  env,
233
292
  "default-model",
234
- `A: { type: "agent", prompt: "p", on: { done: EXIT } }`,
293
+ `A: { type: "agent", prompt: "p", outputType: { safeParse: () => ({ success: true }) }, on: { done: EXIT } }`,
235
294
  `agent: { model: "claude-test-model" },`,
236
295
  );
237
296
  expect((await runCli(["validate", defaulted], env)).code).toBe(0);
@@ -254,7 +313,7 @@ function writeRunnerFixture(env: Env, name: string, exports: string, states: str
254
313
 
255
314
  function agentState(runner?: string, next = "EXIT"): string {
256
315
  const selected = runner === undefined ? "" : `runner: "${runner}", `;
257
- return `{ type: "agent", ${selected}agent: { model: "claude-test-model" }, prompt: "p", next: ${next} }`;
316
+ return `{ type: "agent", ${selected}agent: { model: "claude-test-model" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) }, next: ${next} }`;
258
317
  }
259
318
 
260
319
  test("validate reports an unknown runner name with the state and the known names", async () => {
@@ -345,7 +404,7 @@ function fakeOpencode(script: string): Record<string, string> {
345
404
 
346
405
  function writeModelFixture(env: Env): string {
347
406
  const state = (model: string, next: string, runner = "") =>
348
- `{ type: "agent", ${runner}agent: { model: "${model}" }, prompt: "p", next: ${next} }`;
407
+ `{ type: "agent", ${runner}agent: { model: "${model}" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) }, next: ${next} }`;
349
408
  return writeRunnerFixture(
350
409
  env,
351
410
  "models",
@@ -412,7 +471,7 @@ test("validate reports dead-end leaves", async () => {
412
471
  const dir = writeFixture(
413
472
  env,
414
473
  "dead-end",
415
- `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p" }`,
474
+ `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) } }`,
416
475
  );
417
476
  const res = await runCli(["validate", dir], env);
418
477
  expect(lines(res.stdout)).toContain('FAIL workflow structure — "A": dead end, no on/next');
@@ -466,7 +525,7 @@ test("validate does not check skills — stale copies never touch its verdict",
466
525
  const dir = writeFixture(
467
526
  env,
468
527
  "happy",
469
- `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", on: { done: EXIT } }`,
528
+ `A: { type: "agent", agent: { model: "claude-test-model" }, prompt: "p", outputType: { safeParse: () => ({ success: true }) }, on: { done: EXIT } }`,
470
529
  );
471
530
 
472
531
  const res = await runCli(["validate", dir], env);
@@ -0,0 +1,92 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { COMMANDS, resolveHelp } from "./help.ts";
6
+
7
+ // docs/specs/_built/cli-help/spec.md
8
+
9
+ test("--help, -h, and help print every command and exit 0 (REQ-1)", () => {
10
+ for (const argv of [["--help"], ["-h"], ["help"]]) {
11
+ const res = resolveHelp(argv)!;
12
+ expect(res.code).toBe(0);
13
+ expect(res.stderr).toBe("");
14
+ for (const c of COMMANDS) expect(res.stdout).toContain(c.name);
15
+ }
16
+ });
17
+
18
+ test("help <command> and <command> --help print that command's usage (REQ-2)", () => {
19
+ const viaHelp = resolveHelp(["help", "run"])!;
20
+ const viaFlag = resolveHelp(["run", "--help"])!;
21
+ expect(viaHelp.code).toBe(0);
22
+ expect(viaHelp.stdout).toContain("usage: darkf");
23
+ expect(viaFlag.stdout).toBe(viaHelp.stdout);
24
+ expect(resolveHelp(["start", "-h"])!.stdout).toContain("--allow-dirty-workflow");
25
+ expect(resolveHelp(["monitor", "--help"])!.stdout).toContain("--window");
26
+ });
27
+
28
+ test("a leading dash is never a workflow reference (REQ-3)", () => {
29
+ const res = resolveHelp(["--bogus"])!;
30
+ expect(res.code).not.toBe(0);
31
+ expect(res.stderr).toContain("--bogus");
32
+ expect(res.stdout).toBe("");
33
+ });
34
+
35
+ test("help <name> for a non-command says so and does not resolve a workflow (REQ-6)", () => {
36
+ const res = resolveHelp(["help", "nope"])!;
37
+ expect(res.code).toBe(1);
38
+ expect(res.stderr).toContain("unknown command 'nope'");
39
+ });
40
+
41
+ test("everything else is left to the CLI: a bare darkf, a path, a command with args", () => {
42
+ expect(resolveHelp([])).toBeNull();
43
+ expect(resolveHelp(["./my-workflow"])).toBeNull();
44
+ expect(resolveHelp(["run", "./dir", "a message"])).toBeNull();
45
+ expect(resolveHelp(["__worker", "--help"])).toBeNull();
46
+ });
47
+
48
+ test("a word that is not a command is not run as a workflow (REQ-7)", () => {
49
+ const home = mkdtempSync(join(tmpdir(), "darkf-bare-"));
50
+ try {
51
+ const r = Bun.spawnSync(["bun", join(import.meta.dir, "index.ts"), "my-workflow"], {
52
+ cwd: home,
53
+ env: { ...process.env, HOME: home, XDG_CONFIG_HOME: join(home, "cfg") },
54
+ });
55
+ expect(r.exitCode).toBe(2);
56
+ expect(r.stderr.toString()).toContain("darkf run my-workflow");
57
+ } finally {
58
+ rmSync(home, { recursive: true, force: true });
59
+ }
60
+ });
61
+
62
+ test("the help table and the command dispatch name the same commands (REQ-5)", () => {
63
+ const source = readFileSync(join(import.meta.dir, "index.ts"), "utf8");
64
+ const dispatched = [...source.matchAll(/^\s{2}if \(cmd === "([\w-]+)"\)/gm)]
65
+ .map((m) => m[1]!)
66
+ .filter((n) => n !== "__worker");
67
+ const listed = COMMANDS.map((c) => c.name);
68
+ expect(dispatched.length).toBeGreaterThan(5); // the scan finds the chain it exists for
69
+ expect([...listed].sort()).toEqual([...dispatched].sort());
70
+ });
71
+
72
+ test("--help runs offline and writes no state (REQ-4)", () => {
73
+ const home = mkdtempSync(join(tmpdir(), "darkf-help-"));
74
+ try {
75
+ const proc = Bun.spawnSync(["bun", join(import.meta.dir, "index.ts"), "--help"], {
76
+ env: {
77
+ PATH: process.env.PATH ?? "",
78
+ HOME: home,
79
+ XDG_STATE_HOME: join(home, "state"),
80
+ XDG_CONFIG_HOME: join(home, "cfg"),
81
+ },
82
+ cwd: home,
83
+ });
84
+ expect(proc.exitCode).toBe(0);
85
+ expect(proc.stdout.toString()).toContain("usage: darkf");
86
+ // `.bun` is the Bun runtime's own folder. Anything else would be darkf
87
+ // state: the update stamp, the skills probe stamp, or a config file.
88
+ expect(readdirSync(home).filter((n) => n !== ".bun")).toEqual([]);
89
+ } finally {
90
+ rmSync(home, { recursive: true, force: true });
91
+ }
92
+ });
@@ -0,0 +1,164 @@
1
+ // `darkf --help`, `darkf help <command>`, `darkf <command> --help`
2
+ // (docs/specs/_built/cli-help/spec.md). Pure: it turns argv into text and an exit
3
+ // code, or returns null when argv is not a help request. `main()` calls it
4
+ // before the update gate and the skills probe, so help stays offline and
5
+ // writes no state. The dispatch chain in index.ts stays as it is; a test
6
+ // compares its command names with this table (REQ-5).
7
+
8
+ export interface CommandHelp {
9
+ name: string;
10
+ /** One line for the overview. */
11
+ summary: string;
12
+ /** The usage line. */
13
+ usage: string;
14
+ /** Flags and arguments worth naming, one `[token, meaning]` pair each. */
15
+ details?: Array<[string, string]>;
16
+ }
17
+
18
+ export const COMMANDS: CommandHelp[] = [
19
+ {
20
+ name: "run",
21
+ summary: "Run a workflow in the foreground.",
22
+ usage: "darkf run [<ref-or-dir>] [<message>]",
23
+ details: [
24
+ ["<ref-or-dir>", "a workflow name, or a path to a folder with a workflow.ts (default: .)"],
25
+ ["<message>", "a note recorded with the run"],
26
+ ],
27
+ },
28
+ {
29
+ name: "start",
30
+ summary: "Start a workflow detached and return at once.",
31
+ usage: "darkf start [<ref-or-dir>] [<message>] [--allow-dirty-workflow]",
32
+ details: [
33
+ ["<ref-or-dir>", "a workflow name, or a path to a folder with a workflow.ts (default: .)"],
34
+ ["<message>", "a note recorded with the run"],
35
+ ["--allow-dirty-workflow", "start even when the darkf/ folder has uncommitted changes"],
36
+ ],
37
+ },
38
+ {
39
+ name: "status",
40
+ summary: "Show the state of a run (the latest by default).",
41
+ usage: "darkf status [--run <runId>]",
42
+ details: [
43
+ [
44
+ "exit code",
45
+ "0 succeeded, 1 crashed, 2 orphaned, 3 running, 4 failed, 5 host-died, 6 failed-start",
46
+ ],
47
+ ],
48
+ },
49
+ {
50
+ name: "monitor",
51
+ summary: "Wait on a run and print what changes.",
52
+ usage: "darkf monitor [--run <runId>] [--window <seconds>] [--once]",
53
+ details: [
54
+ ["--window <seconds>", "how long to wait before returning (default: 30)"],
55
+ ["--once", "check once and return"],
56
+ ],
57
+ },
58
+ {
59
+ name: "report",
60
+ summary: "Print the report of a run, finished runs included.",
61
+ usage: "darkf report [--run <runId>]",
62
+ },
63
+ {
64
+ name: "render",
65
+ summary: "Print the workflow as a Mermaid diagram.",
66
+ usage: "darkf render [<ref-or-dir>]",
67
+ },
68
+ {
69
+ name: "validate",
70
+ summary: "Check one workflow: it resolves, loads, and is well formed.",
71
+ usage: "darkf validate <ref-or-path>",
72
+ },
73
+ {
74
+ name: "doctor",
75
+ summary: "Check this machine: agent binaries, the folder, the skills, and version skew.",
76
+ usage: "darkf doctor",
77
+ },
78
+ {
79
+ name: "workflows",
80
+ summary: "List the workflows darkf can resolve by name.",
81
+ usage: "darkf workflows",
82
+ },
83
+ {
84
+ name: "changelog",
85
+ summary: "Print what changed in the installed release.",
86
+ usage: "darkf changelog",
87
+ },
88
+ {
89
+ name: "setup",
90
+ summary: "Install or refresh the darkf skills for the agents on this machine.",
91
+ usage: "darkf setup",
92
+ },
93
+ {
94
+ name: "upgrade",
95
+ summary: "Install the latest darkf release and refresh the skills.",
96
+ usage: "darkf upgrade",
97
+ },
98
+ ];
99
+
100
+ export interface HelpResult {
101
+ stdout: string;
102
+ stderr: string;
103
+ code: number;
104
+ }
105
+
106
+ const HELP_FLAGS = new Set(["--help", "-h"]);
107
+
108
+ function overview(): string {
109
+ const width = Math.max(...COMMANDS.map((c) => c.name.length));
110
+ const lines = COMMANDS.map((c) => ` ${c.name.padEnd(width)} ${c.summary}`);
111
+ return [
112
+ "usage: darkf <command> [arguments]",
113
+ "",
114
+ "commands:",
115
+ ...lines,
116
+ "",
117
+ "darkf help <command> show the usage of one command",
118
+ "",
119
+ ].join("\n");
120
+ }
121
+
122
+ function commandHelp(c: CommandHelp): string {
123
+ const lines = [`usage: ${c.usage}`, "", c.summary];
124
+ if (c.details?.length) {
125
+ const width = Math.max(...c.details.map(([token]) => token.length));
126
+ lines.push("", ...c.details.map(([token, meaning]) => ` ${token.padEnd(width)} ${meaning}`));
127
+ }
128
+ return `${lines.join("\n")}\n`;
129
+ }
130
+
131
+ /** The help answer for argv, or null when argv is not a help request. */
132
+ export function resolveHelp(argv: string[]): HelpResult | null {
133
+ const [cmd, ...rest] = argv;
134
+ if (cmd === undefined) return null; // a bare `darkf` keeps its behavior (NG-3)
135
+
136
+ if (cmd === "--help" || cmd === "-h" || cmd === "help") {
137
+ const name = cmd === "help" ? rest[0] : undefined;
138
+ if (name === undefined) return { stdout: overview(), stderr: "", code: 0 };
139
+ const found = COMMANDS.find((c) => c.name === name);
140
+ if (!found) {
141
+ return {
142
+ stdout: "",
143
+ stderr: `darkf: unknown command '${name}'. Run: darkf --help\n`,
144
+ code: 1,
145
+ };
146
+ }
147
+ return { stdout: commandHelp(found), stderr: "", code: 0 };
148
+ }
149
+
150
+ const found = COMMANDS.find((c) => c.name === cmd);
151
+ if (found && rest.some((a) => HELP_FLAGS.has(a))) {
152
+ return { stdout: commandHelp(found), stderr: "", code: 0 };
153
+ }
154
+
155
+ // A leading dash is never a workflow reference (REQ-3).
156
+ if (cmd.startsWith("-")) {
157
+ return {
158
+ stdout: "",
159
+ stderr: `darkf: unknown option '${cmd}'. Run: darkf --help\n`,
160
+ code: 2,
161
+ };
162
+ }
163
+ return null;
164
+ }