@psimona/darkf 0.9.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.
@@ -11,6 +11,18 @@ filesystem path, or a bare name resolved against
11
11
  `.darkf/` (dot-prefixed) is a different directory entirely: darkf's own
12
12
  runtime/run-storage, gitignore it wholesale.
13
13
 
14
+ `darkf run` is the only way to run a workflow. A word that is not a command,
15
+ as in `darkf my-workflow`, prints an error that names `darkf run my-workflow`
16
+ and exits `2`. An option that starts with `-` and that darkf does not know
17
+ also exits `2`.
18
+
19
+ ### `darkf help [command]`
20
+
21
+ `darkf --help`, `darkf -h`, and `darkf help` list every command with one line
22
+ of purpose. `darkf help <command>` and `darkf <command> --help` print the
23
+ usage of one command and do not run it. Help runs offline and writes no state.
24
+ Exits `0`. `darkf help <name>` for a name that is not a command exits `1`.
25
+
14
26
  ### `darkf render <dir>`
15
27
 
16
28
  Prints the workflow's mermaid `stateDiagram-v2` to stdout. Never executes
@@ -121,3 +133,8 @@ no-op. Takes no flags. Exits `0` on success, `1` if a copy failed.
121
133
  Lists every workflow darkf can resolve by bare name, from both
122
134
  `<cwd>/darkf/` and the darkf package's own `workflows/`,
123
135
  tagged `workspace` or `built-in`.
136
+
137
+ ### `darkf changelog`
138
+
139
+ Prints the newest section of the installed release's changelog. The update
140
+ notice points here. A missing changelog prints one line and does not fail.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psimona/darkf",
3
- "version": "0.9.0",
3
+ "version": "0.10.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>",
@@ -193,14 +193,14 @@ If a node needs a concrete artifact derived from the spec, add a dedicated pair
193
193
 
194
194
  Once you have a `TaskList` (previous section), don't hand it whole to one agent and ask it to work through every task in a single dispatch. That hides the per-task state inside one agent's own judgment about what it already finished, has no node any run status can point at ("which task is this run on right now?"), and a crash mid-plan loses track of exactly where it was.
195
195
 
196
- This is the `item-loop-convention` shape (a design doc, not shipped `darkf-core`/`kit` code as of this writing; hand-roll its algorithm directly in your own `scripts/` rather than importing a module that doesn't exist yet):
196
+ This is the item-loop shape. darkf ships no helper for it, so hand-roll the algorithm in your own `scripts/`:
197
197
 
198
198
  - **Dispatch** (a script) is the node that walks the plan. It reads the persisted `TaskList`, picks the first task whose status is not yet `"done"` (`"pending"` normally; an `"in-progress"` one found on resume means a crash interrupted it — dispatch that same one again, no special case needed), flips it `"in-progress"`, writes the file back, and hands that one task to the next node as its `output`. If every task is `"done"`, route to whatever follows the loop. If any are `"failed"` with none left `"pending"`, that's a distinct blocked outcome, not "exhausted."
199
199
  - The lane that follows (implement, test, fix, review — whatever one task's own work needs) operates on that single task only. It gets the task directly via the one-hop handoff from Dispatch if it's the very next node; anything further downstream (e.g. a reviewer several hops past Dispatch, past a fix-retry loop) rediscovers the right task by reading the plan file itself and finding the one still `"in-progress"` — never by relying on a value threaded through every intervening node.
200
200
  - Only flip a task to `"done"` once its result is independently confirmed, not when the implementing step merely claims it finished. If judgment is needed to confirm that (a reviewer checking the claim against the working tree), split it into the judging agent (which never touches the file) and a small script right after it that does the actual write — same agent/script split as everywhere else in this document.
201
201
  - The lane's last node routes back to Dispatch by its state id — a flat edge, which is fine even across composite boundaries (`buildRegistry` is one flat map keyed by state id; routing doesn't care which composite either side lives in). Dispatch gets re-entered once per task until the plan is exhausted.
202
202
  - **Keep Dispatch outside the lane's composite.** Wrap only the lane (implement, test, fix, review, mark-done) in its own composite; Dispatch sits as that composite's sibling, not inside it. This is what makes the lane's `maxCycles` budget one task's worst case, not the whole plan's: the engine resets a composite's cycle counter whenever the dispatch immediately before it did not already carry that composite in its scope (`CompositeStateDef.maxCycles`'s doc, `src/core/types.ts`). Every hand-off from Dispatch into the lane is such a reset, because Dispatch itself lives outside it.
203
- - Size the lane's `maxCycles` by hand for one task's worst case only: `dispatches per task in the worst case`, with slack (roughly ×1.5) for an occasional extra fix round. Never multiply by the expected task count — `WorkflowDef` is static and built before the real task count is known, so a budget sized against an assumed total crashes the whole run the first time a real plan comes out bigger, even when no single task is anywhere near a runaway. Put no `maxCycles` on Dispatch itself; the engine-wide `maxSteps` is the only backstop needed on the item-to-item loop, matching `item-loop-convention`'s own non-goal of not wiring this automatically.
203
+ - Size the lane's `maxCycles` by hand for one task's worst case only: `dispatches per task in the worst case`, with slack (roughly ×1.5) for an occasional extra fix round. Never multiply by the expected task count — `WorkflowDef` is static and built before the real task count is known, so a budget sized against an assumed total crashes the whole run the first time a real plan comes out bigger, even when no single task is anywhere near a runaway. Put no `maxCycles` on Dispatch itself; the engine-wide `maxSteps` is the only backstop needed on the item-to-item loop.
204
204
  - This loop and the plan-generation loop from the previous section are two separate composites with two separate `maxCycles` budgets, not one — they bound unrelated things (a small, fixed number of generation retries vs. one task's worst case), per the Bounded loops rule above.
205
205
 
206
206
  ## Event design
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { changelogHead } from "./changelog.ts";
3
+
4
+ const CHANGELOG = [
5
+ "# Changelog",
6
+ "",
7
+ "## 1.2.0",
8
+ "",
9
+ "### Added",
10
+ "",
11
+ "- the newest feature.",
12
+ "",
13
+ "## 1.1.0",
14
+ "",
15
+ "### Fixed",
16
+ "",
17
+ "- an older fix.",
18
+ "",
19
+ ].join("\n");
20
+
21
+ describe("changelogHead", () => {
22
+ test("prints everything before the second ## heading", () => {
23
+ expect(changelogHead(CHANGELOG)).toBe(
24
+ ["# Changelog", "", "## 1.2.0", "", "### Added", "", "- the newest feature."].join("\n"),
25
+ );
26
+ });
27
+
28
+ test("a file with one heading prints to the end", () => {
29
+ expect(changelogHead("# Changelog\n\n## 1.0.0\n\n- all of it.")).toBe(
30
+ "# Changelog\n\n## 1.0.0\n\n- all of it.",
31
+ );
32
+ });
33
+
34
+ test("a heading-less file prints its head, capped", () => {
35
+ const body = Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n");
36
+ const head = changelogHead(body);
37
+ expect(head.split("\n")).toHaveLength(80);
38
+ expect(head).toContain("line 0");
39
+ });
40
+
41
+ test("trailing blank lines are trimmed", () => {
42
+ expect(changelogHead("## 1.0.0\n\n- x.\n\n\n")).toBe("## 1.0.0\n\n- x.");
43
+ });
44
+ });
@@ -0,0 +1,26 @@
1
+ // `darkf changelog` (self-update spec, 2026-12-05): print what changed in
2
+ // the installed release, so the upgrade notice can point at a real answer
3
+ // instead of a version number alone. Pure here: the section extraction is
4
+ // testable without the file; `index.ts` owns the path and the print.
5
+
6
+ const MAX_LINES = 80;
7
+
8
+ /** The newest changelog section: everything before the second `## ` heading
9
+ * (the first heading is the newest release or `Unreleased`), capped so a
10
+ * pathologically long section still prints as a digest. Never returns an
11
+ * empty string — a heading-less file prints its head lines. */
12
+ export function changelogHead(text: string): string {
13
+ const lines = text.split("\n");
14
+ const out: string[] = [];
15
+ let headings = 0;
16
+ for (const line of lines) {
17
+ if (line.startsWith("## ")) {
18
+ headings += 1;
19
+ if (headings === 2) break;
20
+ }
21
+ out.push(line);
22
+ if (out.length >= MAX_LINES) break;
23
+ }
24
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
25
+ return out.join("\n");
26
+ }
@@ -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[] = [];
@@ -260,6 +271,13 @@ test("status and monitor report succeeded for a detached run", async () => {
260
271
  expect(st.code).toBe(0);
261
272
  expect(st.stdout).toContain("state: succeeded");
262
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}`);
263
281
 
264
282
  const mon = await runCli(["monitor", "--run", runId], root);
265
283
  expect(mon.code).toBe(0);
@@ -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);
@@ -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
+ }