@llman-sdd/cli 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.
@@ -1,22 +1,25 @@
1
- import { relative } from 'node:path';
1
+ import { relative, resolve } from 'node:path';
2
2
 
3
3
  import {
4
4
  buildDuplicatesFor,
5
5
  checkGlobalChangeIdUniqueness,
6
+ collectChangeIdValues,
6
7
  collectChanges,
8
+ computeCrossRootCollisions,
7
9
  currentBranch,
8
10
  defaultBranch,
9
11
  discoverRoots,
10
12
  formatTotals,
11
13
  renderMachine,
12
- resolveInstanceRoot,
13
14
  runHarnessForSpecs,
14
15
  specIdOf,
15
16
  STAGE_ORDER,
16
17
  validateCapability,
17
18
  validateChange,
18
19
  type ChangeIssue,
20
+ type CrossRootCollision,
19
21
  type HarnessGate,
22
+ type RootNamespaceValues,
20
23
  } from '@llman-sdd/core';
21
24
  import type { Command } from 'commander';
22
25
 
@@ -27,13 +30,16 @@ import {
27
30
  cliMaxScanDepth,
28
31
  exitWith,
29
32
  loadCliConfig,
30
- loadSpecEntries,
31
- newIo,
33
+ loadRootSpecEntries,
34
+ reRootContext,
35
+ addSpecDirOption,
36
+ specsPrefixFor,
32
37
  resolveChangeIdOrExit,
33
38
  resolveOutMode,
39
+ type CliContext,
34
40
  } from '../cli-shared.ts';
35
41
  import { makeCliHarnessRunner } from '../harness.ts';
36
- import { makeCliGit } from '../io.ts';
42
+ import { makeIo } from '../io.ts';
37
43
 
38
44
  interface VItem {
39
45
  id: string;
@@ -49,20 +55,23 @@ function compareItems(a: VItem, b: VItem): number {
49
55
  return a.id < b.id ? -1 : a.id > b.id ? 1 : a.type.localeCompare(b.type);
50
56
  }
51
57
 
58
+ /**
59
+ * r115: `entries` is required — spec validation MUST run on the resolved
60
+ * instance's own registry, never on a silently ambient-cwd default.
61
+ */
52
62
  function specV1Items(
53
63
  opts: {
54
64
  harness?: HarnessGate;
55
65
  harnessOnlyIds?: string[];
56
66
  },
57
- entries: ReturnType<typeof loadSpecEntries> = loadSpecEntries(),
67
+ entries: ReturnType<typeof loadRootSpecEntries>,
58
68
  ): VItem[] {
59
- const io = newIo();
60
69
  const duplicatesFor = buildDuplicatesFor(entries);
61
70
 
62
71
  const items: VItem[] = [];
63
72
  for (const entry of entries) {
64
73
  const cap = specIdOf(entry);
65
- const verdict = validateCapability(entry as never, duplicatesFor, io);
74
+ const verdict = validateCapability(entry as never, duplicatesFor);
66
75
  const issues: ChangeIssue[] = verdict.items.map((i) => ({
67
76
  level: i.level,
68
77
  path: i.id,
@@ -103,21 +112,30 @@ function specV1Items(
103
112
  return items;
104
113
  }
105
114
 
106
- function changeV1Items(names: string[], opts: { stage?: string; strict?: boolean }): VItem[] {
107
- const io = newIo();
108
- const git = makeCliGit(process.cwd());
109
- const config = loadCliConfig();
115
+ function changeV1Items(
116
+ ctx: CliContext,
117
+ names: string[],
118
+ opts: { stage?: string; strict?: boolean },
119
+ ): VItem[] {
120
+ const { io, root, git } = ctx;
121
+ const config = loadCliConfig(root);
110
122
  const items: VItem[] = [];
111
123
  for (const name of names) {
112
124
  const res = validateChange(
113
125
  io,
114
- process.cwd(),
126
+ root,
115
127
  name,
116
128
  {
117
129
  strict_defer: config?.archive?.strict_defer ?? null,
118
130
  change_id_pattern: config?.change_id?.pattern ?? null,
119
131
  },
120
- { stage: opts.stage as never, strict: opts.strict === true, git },
132
+ {
133
+ stage: opts.stage as never,
134
+ strict: opts.strict === true,
135
+ git,
136
+ // r119: specs-landing judged under this instance's prefix.
137
+ specsPrefix: specsPrefixFor(ctx),
138
+ },
121
139
  );
122
140
  items.push({
123
141
  id: name,
@@ -132,7 +150,7 @@ function changeV1Items(names: string[], opts: { stage?: string; strict?: boolean
132
150
  // active change item when the active change is being validated; archive↔
133
151
  // archive / frozen-only collisions surface as synthetic items (no active
134
152
  // counterpart to carry the ERROR).
135
- const duplicates = checkGlobalChangeIdUniqueness(io, `${process.cwd()}/llmanspec/changes`);
153
+ const duplicates = checkGlobalChangeIdUniqueness(io, `${root}/llmanspec/changes`);
136
154
  const byId = new Map(items.map((i) => [i.id, i]));
137
155
  for (const dup of duplicates) {
138
156
  const issue: ChangeIssue = {
@@ -175,9 +193,28 @@ function renderValidateText(items: VItem[]): void {
175
193
  console.log(formatTotals(passed, failed, items.length));
176
194
  }
177
195
 
178
- function gitToplevelOrCwd(): string {
179
- const toplevel = makeCliGit(process.cwd()).runOpt(['rev-parse', '--show-toplevel']);
180
- return toplevel ?? process.cwd();
196
+ /**
197
+ * r91/r114 human form: the cross-root observation section, closing with the
198
+ * `--directory` remediation hint. Machine formats carry the data only (no
199
+ * hint line) — the hint is a human-presentation artifact.
200
+ */
201
+ function renderCrossRootCollisions(collisions: readonly CrossRootCollision[]): void {
202
+ if (collisions.length === 0) {
203
+ console.log('Cross-root id collisions: none');
204
+ } else {
205
+ console.log('Cross-root id collisions (same id under multiple roots is legal):');
206
+ for (const collision of collisions) {
207
+ console.log(` ${collision.namespace}/${collision.value}: ${collision.roots.join(', ')}`);
208
+ }
209
+ }
210
+ console.log(
211
+ 'Use --directory <path> to target one instance root; collisions never affect the exit code.',
212
+ );
213
+ }
214
+
215
+ function gitToplevelOrCwd(ctx: CliContext): string {
216
+ const toplevel = ctx.git.runOpt(['rev-parse', '--show-toplevel']);
217
+ return toplevel ?? ctx.root;
181
218
  }
182
219
 
183
220
  interface RootReport {
@@ -225,8 +262,8 @@ const CHANGE_NEXT_STEPS = [
225
262
  ];
226
263
 
227
264
  /** r63: default-branch dirty live specs — workspace-level guard, once per run. */
228
- function warnDirtySpecsOnDefaultBranch(): void {
229
- const git = makeCliGit(process.cwd());
265
+ function warnDirtySpecsOnDefaultBranch(ctx: CliContext): void {
266
+ const { git } = ctx;
230
267
  const current = currentBranch(git);
231
268
  if (current === null || current !== defaultBranch(git)) return;
232
269
  const out = git.runOpt(['status', '--porcelain', '--', 'llmanspec/specs']) ?? '';
@@ -245,8 +282,8 @@ let harnessBannerShown = false;
245
282
  * logic never touches process.env. Commander binary state:
246
283
  * --check → check=true, absent → undefined.
247
284
  */
248
- function makeHarnessGate(options: { check?: boolean }): HarnessGate {
249
- const runCommand = loadCliConfig()?.specs?.check_command ?? null;
285
+ function makeHarnessGate(ctx: CliContext, options: { check?: boolean }): HarnessGate {
286
+ const runCommand = loadCliConfig(ctx.root)?.specs?.check_command ?? null;
250
287
  const configured = runCommand !== null && runCommand !== '';
251
288
  return {
252
289
  nested: process.env.LLMAN_SDD_HARNESS_ACTIVE === '1',
@@ -257,7 +294,7 @@ function makeHarnessGate(options: { check?: boolean }): HarnessGate {
257
294
  check: options.check === true ? 'on' : 'off',
258
295
  runner: configured ? makeCliHarnessRunner() : undefined,
259
296
  runCommand,
260
- cwd: process.cwd(),
297
+ cwd: ctx.root,
261
298
  onBeforeFirstRun: (expanded: string): void => {
262
299
  if (harnessBannerShown) return;
263
300
  harnessBannerShown = true;
@@ -266,7 +303,7 @@ function makeHarnessGate(options: { check?: boolean }): HarnessGate {
266
303
  };
267
304
  }
268
305
 
269
- export function registerValidate(program: Command): void {
306
+ export function registerValidate(program: Command, ctx: CliContext): void {
270
307
  const validate = program
271
308
  .command('validate')
272
309
  .description('Validate specs and changes (structural gates + stage/completion rules)')
@@ -276,11 +313,9 @@ export function registerValidate(program: Command): void {
276
313
  .option('--specs', 'restrict scope to specs')
277
314
  .option('--type <type>', 'force disambiguation: change | spec')
278
315
  .option('--stage <stage>', 'change stage gate: draft | designed | planned | full')
279
- .option('--strict', 'warnings also make the exit code non-zero')
280
- .option(
281
- '--directory <path>',
282
- 'instance root resolution start (default: nearest llmanspec/ at or above cwd)',
283
- )
316
+ .option('--strict', 'warnings also make the exit code non-zero');
317
+ addSpecDirOption(validate);
318
+ validate
284
319
  .option(
285
320
  '--all-roots',
286
321
  'aggregate: validate every discovered llmanspec root (specs scope, any root red → non-zero exit)',
@@ -307,22 +342,22 @@ export function registerValidate(program: Command): void {
307
342
  allRoots?: boolean;
308
343
  },
309
344
  ) => {
310
- if (!assertCompactJsonPairing(options)) return;
345
+ assertCompactJsonPairing(options);
311
346
  const outMode = resolveOutMode(options.output, options.json, options.compactJson);
312
347
  // r32: INFO issues are presentation noise — dropped unless opted in.
313
348
  // Filtering never touches `valid`, summaries, or exit codes.
314
349
  const keepInfo = options.includeInfo === true;
315
350
  const stripInfo = <T extends { issues: { level: string }[] }>(it: T): T =>
316
351
  keepInfo ? it : { ...it, issues: it.issues.filter((x) => x.level !== 'INFO') };
317
- warnDirtySpecsOnDefaultBranch();
352
+ warnDirtySpecsOnDefaultBranch(ctx);
318
353
  if (options.type !== undefined && options.type !== 'change' && options.type !== 'spec') {
319
- throw new CliError(`invalid --type: ${options.type}`);
354
+ throw new CliError(`invalid --type: ${options.type}`, 2);
320
355
  }
321
356
  if (
322
357
  options.stage !== undefined &&
323
358
  !(STAGE_ORDER as readonly string[]).includes(options.stage)
324
359
  ) {
325
- throw new CliError(`invalid --stage: ${options.stage}`);
360
+ throw new CliError(`invalid --stage: ${options.stage}`, 2);
326
361
  }
327
362
  const maxDepth = cliMaxScanDepth(program);
328
363
 
@@ -331,36 +366,66 @@ export function registerValidate(program: Command): void {
331
366
  if (item !== undefined) {
332
367
  throw new CliError('--all-roots validates every root; drop the <item> argument');
333
368
  }
334
- const start = options.directory ?? gitToplevelOrCwd();
335
- const roots = discoverRoots(start, newIo(), { maxDepth });
369
+ const start = resolve(options.directory ?? gitToplevelOrCwd(ctx));
370
+ const roots = discoverRoots(start, ctx.io, { maxDepth });
336
371
  if (roots.length === 0) {
337
- throw new CliError(`no llmanspec roots discovered under: ${start}`);
372
+ // r91 aggregate anchor: discovery covers the start itself and
373
+ // everything below it — the r109 walk-up family message form, with
374
+ // the direction the aggregate operator actually searches.
375
+ throw new CliError(`no llmanspec root at or under: ${start}`);
338
376
  }
339
- const originalCwd = process.cwd();
340
377
  const reports: RootReport[] = [];
378
+ const namespaceValues: RootNamespaceValues[] = [];
341
379
  let anyFail = false;
342
- try {
343
- for (const root of roots) {
344
- process.chdir(root.rootDir);
345
- const items = specV1Items({
346
- harness: makeHarnessGate(options),
347
- });
348
- const visible = keepInfo ? items : items.map(stripInfo);
349
- if (visible.some((i) => !i.valid)) anyFail = true;
350
- reports.push({
351
- root: relative(start, root.rootDir) || '.',
352
- items: visible,
353
- summary: summarizeItems(visible),
354
- });
355
- }
356
- } finally {
357
- process.chdir(originalCwd);
380
+ for (const root of roots) {
381
+ // r91/r115: the discovered rootDir follows the start's form, and a
382
+ // relative one would make makeIo(rootDir) anchor twice (queries
383
+ // landing in <dir>/<dir>/llmanspec) so every root failed to resolve.
384
+ // Absolutize once, then label relative to the (absolute) start.
385
+ const rootDir = resolve(root.rootDir);
386
+ const rootCtx: CliContext = {
387
+ ...ctx,
388
+ root: rootDir,
389
+ io: makeIo(rootDir),
390
+ };
391
+ const entries = loadRootSpecEntries(rootDir, rootCtx.io);
392
+ const items = specV1Items(
393
+ {
394
+ harness: makeHarnessGate(rootCtx, options),
395
+ },
396
+ entries,
397
+ );
398
+ const visible = keepInfo ? items : items.map(stripInfo);
399
+ if (visible.some((i) => !i.valid)) anyFail = true;
400
+ const label = relative(start, rootDir) || '.';
401
+ reports.push({
402
+ root: label,
403
+ items: visible,
404
+ summary: summarizeItems(visible),
405
+ });
406
+ // r91: the aggregate covers change-id granularity too — one set of
407
+ // ids per root for the cross-root observation (spec/capability ids,
408
+ // @req handles, change ids incl. archived dated entries).
409
+ namespaceValues.push({
410
+ root: label,
411
+ specIds: entries.map((entry) => specIdOf(entry)),
412
+ reqIds: entries
413
+ .flatMap((entry) => entry.doc.rules.map((rule) => rule.reqId))
414
+ .filter((id) => id !== ''),
415
+ changeIds: collectChangeIdValues(rootCtx.io, `${rootDir}/llmanspec/changes`, {
416
+ maxScanDepth: maxDepth,
417
+ }),
418
+ });
358
419
  }
420
+ // r91/r114: undefined for a lone root — the field MUST NOT be emitted
421
+ // at all there (no empty array, byte-identical single-root output).
422
+ const collisions = computeCrossRootCollisions(namespaceValues);
359
423
  if (outMode === 'human') {
360
424
  for (const report of reports) {
361
425
  console.log(`root ${report.root}`);
362
426
  renderValidateText(report.items);
363
427
  }
428
+ if (collisions !== undefined) renderCrossRootCollisions(collisions);
364
429
  } else {
365
430
  const totals = reports.reduce(
366
431
  (acc, r) => ({
@@ -370,34 +435,36 @@ export function registerValidate(program: Command): void {
370
435
  }),
371
436
  { items: 0, passed: 0, failed: 0 },
372
437
  );
373
- console.log(
374
- renderMachine({ roots: reports, summary: { totals }, version: '1.0' }, outMode),
375
- );
438
+ // Observation is data-only in machine form (r114: no hint line);
439
+ // collisions never feed the exit code.
440
+ const payload =
441
+ collisions === undefined
442
+ ? { roots: reports, summary: { totals }, version: '1.0' }
443
+ : {
444
+ roots: reports,
445
+ crossRootCollisions: collisions,
446
+ summary: { totals, crossRootCollisions: collisions.length },
447
+ version: '1.0',
448
+ };
449
+ console.log(renderMachine(payload, outMode));
376
450
  }
377
451
  if (anyFail) console.error('Error: validation failed');
378
452
  exitWith(anyFail ? 1 : 0);
379
453
  return;
380
454
  }
381
455
 
382
- // ---- instance root resolution: --directory start, else nearest
383
- // ancestor llmanspec/ ("cd into the subpackage and run", r94). A no-op
384
- // when cwd already sits at a root (byte-identical legacy path). ----
385
- if (options.directory !== undefined) {
386
- const root = resolveInstanceRoot(options.directory, newIo());
387
- if (root === null) {
388
- throw new CliError(`no llmanspec root at or above: ${options.directory}`);
389
- }
390
- process.chdir(root);
391
- } else {
392
- const root = resolveInstanceRoot(process.cwd(), newIo());
393
- if (root !== null && root !== process.cwd()) process.chdir(root);
394
- }
456
+ // ---- instance root resolution (T21, cli r108/r109/r115): the shared
457
+ // re-root operator, same as every other command — io, git and root are
458
+ // all anchored at the resolved instance, so downstream discovery reads
459
+ // THAT root (a root swap alone would still discover from the launch
460
+ // cwd). Byte-identical when cwd already sits at the instance root. ----
461
+ const eff: CliContext = reRootContext(ctx, options.directory);
395
462
 
396
- const harness = makeHarnessGate(options);
463
+ const harness = makeHarnessGate(eff, options);
397
464
 
398
465
  // ---- single item (auto-disambiguate: spec first, then change) ----
399
466
  if (item !== undefined) {
400
- const entries = loadSpecEntries();
467
+ const entries = loadRootSpecEntries(undefined, eff.io);
401
468
  const specEntry =
402
469
  options.type === 'change' ? undefined : entries.find((e) => specIdOf(e) === item);
403
470
  if (specEntry !== undefined) {
@@ -432,9 +499,8 @@ export function registerValidate(program: Command): void {
432
499
  return;
433
500
  }
434
501
  // change single (r61: predecessor r112 prefix resolution on the change id)
435
- const io = newIo();
436
- const root = process.cwd();
437
- const resolved = resolveChangeIdOrExit(program, item, {
502
+ const { io, root } = eff;
503
+ const resolved = resolveChangeIdOrExit(eff, program, item, {
438
504
  suppressHint: options.json === true,
439
505
  });
440
506
  const changeId = resolved.id;
@@ -443,13 +509,15 @@ export function registerValidate(program: Command): void {
443
509
  root,
444
510
  changeId,
445
511
  {
446
- strict_defer: loadCliConfig()?.archive?.strict_defer ?? null,
447
- change_id_pattern: loadCliConfig()?.change_id?.pattern ?? null,
512
+ strict_defer: loadCliConfig(eff.root)?.archive?.strict_defer ?? null,
513
+ change_id_pattern: loadCliConfig(eff.root)?.change_id?.pattern ?? null,
448
514
  },
449
515
  {
450
516
  stage: options.stage as never,
451
517
  strict: options.strict === true,
452
- git: makeCliGit(process.cwd()),
518
+ git: eff.git,
519
+ // r119: specs-landing judged under this instance's prefix.
520
+ specsPrefix: specsPrefixFor(eff),
453
521
  },
454
522
  );
455
523
  const infos = res.issues.filter((i) => i.level === 'INFO');
@@ -497,17 +565,20 @@ export function registerValidate(program: Command): void {
497
565
  let items: VItem[] = [];
498
566
  if (effectiveSpecs) {
499
567
  items = items.concat(
500
- specV1Items({
501
- harness,
502
- }),
568
+ specV1Items(
569
+ {
570
+ harness,
571
+ },
572
+ loadRootSpecEntries(undefined, eff.io),
573
+ ),
503
574
  );
504
575
  }
505
576
  if (effectiveChanges) {
506
- const names = collectChanges(newIo(), process.cwd(), new Date(), {
577
+ const names = collectChanges(eff.io, eff.root, new Date(), {
507
578
  maxScanDepth: maxDepth,
508
579
  }).map((c) => c.name);
509
580
  items = items.concat(
510
- changeV1Items(names, { stage: options.stage, strict: options.strict }),
581
+ changeV1Items(eff, names, { stage: options.stage, strict: options.strict }),
511
582
  );
512
583
  }
513
584
  items.sort(compareItems);
package/src/io.ts CHANGED
@@ -29,6 +29,12 @@ export function parentOf(p: string): string {
29
29
  }
30
30
 
31
31
  export interface CliIo {
32
+ /**
33
+ * The directory this io is anchored at (relative paths resolve against it).
34
+ * r115: root discovery defaults to this anchor, never to the ambient
35
+ * `process.cwd()` — a re-rooted context must read its own instance.
36
+ */
37
+ root: string;
32
38
  exists(path: string): boolean;
33
39
  readText(path: string): string;
34
40
  writeText(path: string, content: string): void;
@@ -48,6 +54,7 @@ export interface CliIo {
48
54
  export function makeIo(root: string): CliIo {
49
55
  const full = (p: string): string => (isAbsolute(p) ? p : join(root, p));
50
56
  return {
57
+ root,
51
58
  exists: (p) => existsSync(full(p)),
52
59
  readText: (p) => readFileSync(full(p), 'utf8'),
53
60
  writeText: (p, content) => {
package/src/main.ts CHANGED
@@ -1,59 +1,20 @@
1
1
  #!/usr/bin/env bun
2
- import { Command } from 'commander';
2
+ // Execution entry only (cli r107): assemble the command tree via the factory,
3
+ // parse argv and render the unified error exits. Safe to import — nothing runs
4
+ // unless this module is the main module (guard at the bottom).
5
+ import { realpathSync } from 'node:fs';
3
6
 
4
- import { CliError, versionDisplay } from './cli-shared.ts';
5
- import { registerArchive } from './commands/archive.ts';
6
- import { registerChange } from './commands/change.ts';
7
- import { registerConfig } from './commands/config.ts';
8
- import { registerContext } from './commands/context.ts';
9
- import { registerGraph } from './commands/graph.ts';
10
- import { registerIndex } from './commands/index.ts';
11
- import { registerInit } from './commands/init.ts';
12
- import { registerList } from './commands/list.ts';
13
- import { registerProject } from './commands/project.ts';
14
- import { registerReview } from './commands/review.ts';
15
- import { registerShow } from './commands/show.ts';
16
- import { registerSpec } from './commands/spec.ts';
17
- import { registerValidate } from './commands/validate.ts';
18
-
19
- // Assembly order is load-bearing: commander children copy _exitCallback at
20
- // creation time, so exitOverride/configureOutput must run before any
21
- // `registerXxx` call, and the register calls below must keep the original
22
- // top-level command order (help text renders in registration order).
23
- const program = new Command();
24
-
25
- // Must run before subcommand registration (children copy _exitCallback at
26
- // creation time); exitOverride turns commander's process.exit into a throw.
27
- program.exitOverride();
28
- program.configureOutput({ outputError: () => {} });
29
-
30
- program.name('llman-sdd').description('Spec-driven development workflow').version(versionDisplay());
31
- program.option(
32
- '--max-scan-depth <n>',
33
- 'max depth when scanning llmanspec/changes/ for proposal.md (min 1, default 8)',
34
- '8',
35
- );
36
-
37
- registerInit(program);
38
- registerValidate(program);
39
- registerChange(program);
40
- registerList(program);
41
- registerShow(program);
42
- registerGraph(program);
43
- registerSpec(program);
44
- registerProject(program);
45
- registerArchive(program);
46
- registerReview(program);
47
- registerConfig(program);
48
- registerIndex(program);
49
- registerContext(program);
7
+ import { CliError, makeCliContext } from './cli-shared.ts';
8
+ import { createProgram } from './program.ts';
50
9
 
51
10
  function commandChain(argv: string[]): string {
52
- let node: Command = program;
11
+ // Re-parse argv against a fresh tree for the unknown-command/option usage line.
12
+ const program = createProgram(makeCliContext());
13
+ let node = program;
53
14
  let chain = '';
54
15
  let rest = argv.slice(2);
55
16
  while (rest.length > 0) {
56
- let child: Command | undefined;
17
+ let child;
57
18
  for (const cmd of node.commands) {
58
19
  if (cmd.name() === rest[0]) {
59
20
  child = cmd;
@@ -69,6 +30,9 @@ function commandChain(argv: string[]): string {
69
30
  }
70
31
 
71
32
  async function main(): Promise<void> {
33
+ // r108: run context resolved ONCE at assembly time — command bodies take
34
+ // io/git/root/cwd from here instead of reading process state ad hoc.
35
+ const program = createProgram(makeCliContext());
72
36
  try {
73
37
  await program.parseAsync(process.argv);
74
38
  } catch (error) {
@@ -87,6 +51,28 @@ async function main(): Promise<void> {
87
51
  const commanderMsg = String(comErr?.message ?? '');
88
52
  const stripCommanderPrefix = (text: string): string => text.replace(/^error:\s*/u, '');
89
53
 
54
+ // cli r75: every remaining commander parse failure is a usage error —
55
+ // missingArgument / excessArguments / invalidArgument / invalidOption …
56
+ // — rendered through the shared single-prefix exit with rc 2. Handler
57
+ // level enum validation throws CliError(…, 2) itself (intentional
58
+ // divergence from the predecessor's rc 1).
59
+ if (typeof comErr?.code === 'string' && comErr.code.startsWith('commander.')) {
60
+ // r75: an unknown token at root level surfaces as excessArguments (the
61
+ // root action owns the bare call) — render the unknown-command shape.
62
+ const rootExcess =
63
+ comErr.code === 'commander.excessArguments' &&
64
+ process.argv.length > 2 &&
65
+ !program.commands.some((c) => c.name() === process.argv[2]);
66
+ if (rootExcess) {
67
+ console.error(`Error: unknown command '${process.argv[2] as string}'`);
68
+ process.exitCode = 2;
69
+ return;
70
+ }
71
+ console.error(`Error: ${stripCommanderPrefix(commanderMsg)}`);
72
+ process.exitCode = 2;
73
+ return;
74
+ }
75
+
90
76
  if (comErr?.code === 'commander.unknownOption') {
91
77
  const raw = stripCommanderPrefix(commanderMsg);
92
78
  const arg = raw.replace(/^unknown option ['"]/u, '').replace(/['"]?\s*$/u, '') ?? '';
@@ -122,4 +108,23 @@ async function main(): Promise<void> {
122
108
  }
123
109
  }
124
110
 
125
- await main();
111
+ /**
112
+ * r107 execution guard with the Node 24.0/24.1 fallback: `import.meta.main`
113
+ * is undefined there (introduced in v24.2.0), so a bare check would silently
114
+ * skip every invocation. The fallback compares the realpath-normalized
115
+ * `process.argv[1]` against this module's path — argv may be missing and the
116
+ * realpath may fail, both fold to "not the entry".
117
+ */
118
+ const isEntry =
119
+ import.meta.main ??
120
+ (() => {
121
+ try {
122
+ const invoked = process.argv[1];
123
+ if (invoked === undefined) return false;
124
+ return realpathSync(invoked) === realpathSync(import.meta.filename);
125
+ } catch {
126
+ return false;
127
+ }
128
+ })();
129
+
130
+ if (isEntry) await main();
package/src/program.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * T17 program factory (cli r107): builds the full command tree WITHOUT
3
+ * parsing argv or running any action. Importing this module (or calling
4
+ * `createProgram`) must never execute a command — `main.ts` is the only
5
+ * assembly+run entry.
6
+ *
7
+ * Assembly order is load-bearing: commander children copy _exitCallback at
8
+ * creation time, so exitOverride/configureOutput must run before any
9
+ * `registerXxx` call, and the register calls below must keep the original
10
+ * top-level command order (help text renders in registration order).
11
+ */
12
+ import { Command } from 'commander';
13
+
14
+ import { CliError, versionDisplay, type CliContext } from './cli-shared.ts';
15
+ import { registerArchive } from './commands/archive.ts';
16
+ import { registerChange } from './commands/change.ts';
17
+ import { registerConfig } from './commands/config.ts';
18
+ import { registerContext } from './commands/context.ts';
19
+ import { registerGraph } from './commands/graph.ts';
20
+ import { registerIndex } from './commands/index.ts';
21
+ import { registerInit } from './commands/init.ts';
22
+ import { registerList } from './commands/list.ts';
23
+ import { registerProject } from './commands/project.ts';
24
+ import { registerReview } from './commands/review.ts';
25
+ import { registerSelf } from './commands/self.ts';
26
+ import { registerShow } from './commands/show.ts';
27
+ import { registerSpec } from './commands/spec.ts';
28
+ import { registerValidate } from './commands/validate.ts';
29
+
30
+ export function createProgram(ctx: CliContext): Command {
31
+ const program = new Command();
32
+
33
+ // Must run before subcommand registration (children copy _exitCallback at
34
+ // creation time); exitOverride turns commander's process.exit into a throw.
35
+ program.exitOverride();
36
+ program.configureOutput({ outputError: () => {} });
37
+
38
+ program
39
+ .name('llman-sdd')
40
+ .description('Spec-driven development workflow')
41
+ .version(versionDisplay());
42
+ program.option(
43
+ '--max-scan-depth <n>',
44
+ 'max depth when scanning llmanspec/changes/ for proposal.md (min 1, default 8)',
45
+ '8',
46
+ );
47
+ // cli r75: a bare root invocation (also with root-only options) equals
48
+ // --help — help to stdout, exit 0 via the commander.help path.
49
+ program.action(() => {
50
+ program.help();
51
+ });
52
+
53
+ registerInit(program, ctx);
54
+ registerValidate(program, ctx);
55
+ registerChange(program, ctx);
56
+ registerList(program, ctx);
57
+ registerShow(program, ctx);
58
+ registerGraph(program, ctx);
59
+ registerSpec(program, ctx);
60
+ registerProject(program, ctx);
61
+ registerArchive(program, ctx);
62
+ registerReview(program, ctx);
63
+ registerConfig(program, ctx);
64
+ registerIndex(program, ctx);
65
+ registerContext(program, ctx);
66
+ registerSelf(program, ctx);
67
+
68
+ // cli r75: pure parent groups (no default action of their own) reject bare
69
+ // calls as usage errors — commander's missing-action help on stderr, rc 2
70
+ // via missingParameter/…; `config` keeps its default action (overview, rc 0).
71
+ for (const name of ['change', 'spec', 'project', 'archive', 'index', 'self']) {
72
+ const group = program.commands.find((c) => c.name() === name);
73
+ if (group === undefined) continue;
74
+ group.action(() => {
75
+ // commander's configureOutput silenced outputError; render the usage
76
+ // line ourselves and exit through the shared CliError path (rc 2).
77
+ group.outputHelp({ error: true });
78
+ throw new CliError('', 2);
79
+ });
80
+ }
81
+
82
+ return program;
83
+ }