@llman-sdd/cli 0.8.2 → 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,24 +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
- strict?: boolean;
55
64
  harness?: HarnessGate;
56
65
  harnessOnlyIds?: string[];
57
66
  },
58
- entries: ReturnType<typeof loadSpecEntries> = loadSpecEntries(),
67
+ entries: ReturnType<typeof loadRootSpecEntries>,
59
68
  ): VItem[] {
60
- const io = newIo();
61
69
  const duplicatesFor = buildDuplicatesFor(entries);
62
70
 
63
71
  const items: VItem[] = [];
64
72
  for (const entry of entries) {
65
73
  const cap = specIdOf(entry);
66
- const verdict = validateCapability(entry as never, duplicatesFor, io, {
67
- strict: opts.strict === true,
68
- checkTransitions: Boolean(loadCliConfig()?.specs?.check_transitions),
69
- });
74
+ const verdict = validateCapability(entry as never, duplicatesFor);
70
75
  const issues: ChangeIssue[] = verdict.items.map((i) => ({
71
76
  level: i.level,
72
77
  path: i.id,
@@ -107,21 +112,30 @@ function specV1Items(
107
112
  return items;
108
113
  }
109
114
 
110
- function changeV1Items(names: string[], opts: { stage?: string; strict?: boolean }): VItem[] {
111
- const io = newIo();
112
- const git = makeCliGit(process.cwd());
113
- 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);
114
122
  const items: VItem[] = [];
115
123
  for (const name of names) {
116
124
  const res = validateChange(
117
125
  io,
118
- process.cwd(),
126
+ root,
119
127
  name,
120
128
  {
121
129
  strict_defer: config?.archive?.strict_defer ?? null,
122
130
  change_id_pattern: config?.change_id?.pattern ?? null,
123
131
  },
124
- { 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
+ },
125
139
  );
126
140
  items.push({
127
141
  id: name,
@@ -136,7 +150,7 @@ function changeV1Items(names: string[], opts: { stage?: string; strict?: boolean
136
150
  // active change item when the active change is being validated; archive↔
137
151
  // archive / frozen-only collisions surface as synthetic items (no active
138
152
  // counterpart to carry the ERROR).
139
- const duplicates = checkGlobalChangeIdUniqueness(io, `${process.cwd()}/llmanspec/changes`);
153
+ const duplicates = checkGlobalChangeIdUniqueness(io, `${root}/llmanspec/changes`);
140
154
  const byId = new Map(items.map((i) => [i.id, i]));
141
155
  for (const dup of duplicates) {
142
156
  const issue: ChangeIssue = {
@@ -179,9 +193,28 @@ function renderValidateText(items: VItem[]): void {
179
193
  console.log(formatTotals(passed, failed, items.length));
180
194
  }
181
195
 
182
- function gitToplevelOrCwd(): string {
183
- const toplevel = makeCliGit(process.cwd()).runOpt(['rev-parse', '--show-toplevel']);
184
- 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;
185
218
  }
186
219
 
187
220
  interface RootReport {
@@ -229,8 +262,8 @@ const CHANGE_NEXT_STEPS = [
229
262
  ];
230
263
 
231
264
  /** r63: default-branch dirty live specs — workspace-level guard, once per run. */
232
- function warnDirtySpecsOnDefaultBranch(): void {
233
- const git = makeCliGit(process.cwd());
265
+ function warnDirtySpecsOnDefaultBranch(ctx: CliContext): void {
266
+ const { git } = ctx;
234
267
  const current = currentBranch(git);
235
268
  if (current === null || current !== defaultBranch(git)) return;
236
269
  const out = git.runOpt(['status', '--porcelain', '--', 'llmanspec/specs']) ?? '';
@@ -249,8 +282,8 @@ let harnessBannerShown = false;
249
282
  * logic never touches process.env. Commander binary state:
250
283
  * --check → check=true, absent → undefined.
251
284
  */
252
- function makeHarnessGate(options: { check?: boolean }): HarnessGate {
253
- 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;
254
287
  const configured = runCommand !== null && runCommand !== '';
255
288
  return {
256
289
  nested: process.env.LLMAN_SDD_HARNESS_ACTIVE === '1',
@@ -261,7 +294,7 @@ function makeHarnessGate(options: { check?: boolean }): HarnessGate {
261
294
  check: options.check === true ? 'on' : 'off',
262
295
  runner: configured ? makeCliHarnessRunner() : undefined,
263
296
  runCommand,
264
- cwd: process.cwd(),
297
+ cwd: ctx.root,
265
298
  onBeforeFirstRun: (expanded: string): void => {
266
299
  if (harnessBannerShown) return;
267
300
  harnessBannerShown = true;
@@ -270,7 +303,7 @@ function makeHarnessGate(options: { check?: boolean }): HarnessGate {
270
303
  };
271
304
  }
272
305
 
273
- export function registerValidate(program: Command): void {
306
+ export function registerValidate(program: Command, ctx: CliContext): void {
274
307
  const validate = program
275
308
  .command('validate')
276
309
  .description('Validate specs and changes (structural gates + stage/completion rules)')
@@ -280,11 +313,9 @@ export function registerValidate(program: Command): void {
280
313
  .option('--specs', 'restrict scope to specs')
281
314
  .option('--type <type>', 'force disambiguation: change | spec')
282
315
  .option('--stage <stage>', 'change stage gate: draft | designed | planned | full')
283
- .option('--strict', 'warnings also make the exit code non-zero')
284
- .option(
285
- '--directory <path>',
286
- 'instance root resolution start (default: nearest llmanspec/ at or above cwd)',
287
- )
316
+ .option('--strict', 'warnings also make the exit code non-zero');
317
+ addSpecDirOption(validate);
318
+ validate
288
319
  .option(
289
320
  '--all-roots',
290
321
  'aggregate: validate every discovered llmanspec root (specs scope, any root red → non-zero exit)',
@@ -311,22 +342,22 @@ export function registerValidate(program: Command): void {
311
342
  allRoots?: boolean;
312
343
  },
313
344
  ) => {
314
- if (!assertCompactJsonPairing(options)) return;
345
+ assertCompactJsonPairing(options);
315
346
  const outMode = resolveOutMode(options.output, options.json, options.compactJson);
316
347
  // r32: INFO issues are presentation noise — dropped unless opted in.
317
348
  // Filtering never touches `valid`, summaries, or exit codes.
318
349
  const keepInfo = options.includeInfo === true;
319
350
  const stripInfo = <T extends { issues: { level: string }[] }>(it: T): T =>
320
351
  keepInfo ? it : { ...it, issues: it.issues.filter((x) => x.level !== 'INFO') };
321
- warnDirtySpecsOnDefaultBranch();
352
+ warnDirtySpecsOnDefaultBranch(ctx);
322
353
  if (options.type !== undefined && options.type !== 'change' && options.type !== 'spec') {
323
- throw new CliError(`invalid --type: ${options.type}`);
354
+ throw new CliError(`invalid --type: ${options.type}`, 2);
324
355
  }
325
356
  if (
326
357
  options.stage !== undefined &&
327
358
  !(STAGE_ORDER as readonly string[]).includes(options.stage)
328
359
  ) {
329
- throw new CliError(`invalid --stage: ${options.stage}`);
360
+ throw new CliError(`invalid --stage: ${options.stage}`, 2);
330
361
  }
331
362
  const maxDepth = cliMaxScanDepth(program);
332
363
 
@@ -335,37 +366,66 @@ export function registerValidate(program: Command): void {
335
366
  if (item !== undefined) {
336
367
  throw new CliError('--all-roots validates every root; drop the <item> argument');
337
368
  }
338
- const start = options.directory ?? gitToplevelOrCwd();
339
- const roots = discoverRoots(start, newIo(), { maxDepth });
369
+ const start = resolve(options.directory ?? gitToplevelOrCwd(ctx));
370
+ const roots = discoverRoots(start, ctx.io, { maxDepth });
340
371
  if (roots.length === 0) {
341
- 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}`);
342
376
  }
343
- const originalCwd = process.cwd();
344
377
  const reports: RootReport[] = [];
378
+ const namespaceValues: RootNamespaceValues[] = [];
345
379
  let anyFail = false;
346
- try {
347
- for (const root of roots) {
348
- process.chdir(root.rootDir);
349
- const items = specV1Items({
350
- strict: options.strict,
351
- harness: makeHarnessGate(options),
352
- });
353
- const visible = keepInfo ? items : items.map(stripInfo);
354
- if (visible.some((i) => !i.valid)) anyFail = true;
355
- reports.push({
356
- root: relative(start, root.rootDir) || '.',
357
- items: visible,
358
- summary: summarizeItems(visible),
359
- });
360
- }
361
- } finally {
362
- 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
+ });
363
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);
364
423
  if (outMode === 'human') {
365
424
  for (const report of reports) {
366
425
  console.log(`root ${report.root}`);
367
426
  renderValidateText(report.items);
368
427
  }
428
+ if (collisions !== undefined) renderCrossRootCollisions(collisions);
369
429
  } else {
370
430
  const totals = reports.reduce(
371
431
  (acc, r) => ({
@@ -375,40 +435,41 @@ export function registerValidate(program: Command): void {
375
435
  }),
376
436
  { items: 0, passed: 0, failed: 0 },
377
437
  );
378
- console.log(
379
- renderMachine({ roots: reports, summary: { totals }, version: '1.0' }, outMode),
380
- );
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));
381
450
  }
382
451
  if (anyFail) console.error('Error: validation failed');
383
452
  exitWith(anyFail ? 1 : 0);
384
453
  return;
385
454
  }
386
455
 
387
- // ---- instance root resolution: --directory start, else nearest
388
- // ancestor llmanspec/ ("cd into the subpackage and run", r94). A no-op
389
- // when cwd already sits at a root (byte-identical legacy path). ----
390
- if (options.directory !== undefined) {
391
- const root = resolveInstanceRoot(options.directory, newIo());
392
- if (root === null) {
393
- throw new CliError(`no llmanspec root at or above: ${options.directory}`);
394
- }
395
- process.chdir(root);
396
- } else {
397
- const root = resolveInstanceRoot(process.cwd(), newIo());
398
- if (root !== null && root !== process.cwd()) process.chdir(root);
399
- }
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);
400
462
 
401
- const harness = makeHarnessGate(options);
463
+ const harness = makeHarnessGate(eff, options);
402
464
 
403
465
  // ---- single item (auto-disambiguate: spec first, then change) ----
404
466
  if (item !== undefined) {
405
- const entries = loadSpecEntries();
467
+ const entries = loadRootSpecEntries(undefined, eff.io);
406
468
  const specEntry =
407
469
  options.type === 'change' ? undefined : entries.find((e) => specIdOf(e) === item);
408
470
  if (specEntry !== undefined) {
409
471
  const items = specV1Items(
410
472
  {
411
- strict: options.strict,
412
473
  harness,
413
474
  harnessOnlyIds: [item],
414
475
  },
@@ -438,9 +499,8 @@ export function registerValidate(program: Command): void {
438
499
  return;
439
500
  }
440
501
  // change single (r61: predecessor r112 prefix resolution on the change id)
441
- const io = newIo();
442
- const root = process.cwd();
443
- const resolved = resolveChangeIdOrExit(program, item, {
502
+ const { io, root } = eff;
503
+ const resolved = resolveChangeIdOrExit(eff, program, item, {
444
504
  suppressHint: options.json === true,
445
505
  });
446
506
  const changeId = resolved.id;
@@ -449,13 +509,15 @@ export function registerValidate(program: Command): void {
449
509
  root,
450
510
  changeId,
451
511
  {
452
- strict_defer: loadCliConfig()?.archive?.strict_defer ?? null,
453
- 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,
454
514
  },
455
515
  {
456
516
  stage: options.stage as never,
457
517
  strict: options.strict === true,
458
- git: makeCliGit(process.cwd()),
518
+ git: eff.git,
519
+ // r119: specs-landing judged under this instance's prefix.
520
+ specsPrefix: specsPrefixFor(eff),
459
521
  },
460
522
  );
461
523
  const infos = res.issues.filter((i) => i.level === 'INFO');
@@ -503,18 +565,20 @@ export function registerValidate(program: Command): void {
503
565
  let items: VItem[] = [];
504
566
  if (effectiveSpecs) {
505
567
  items = items.concat(
506
- specV1Items({
507
- strict: options.strict,
508
- harness,
509
- }),
568
+ specV1Items(
569
+ {
570
+ harness,
571
+ },
572
+ loadRootSpecEntries(undefined, eff.io),
573
+ ),
510
574
  );
511
575
  }
512
576
  if (effectiveChanges) {
513
- const names = collectChanges(newIo(), process.cwd(), new Date(), {
577
+ const names = collectChanges(eff.io, eff.root, new Date(), {
514
578
  maxScanDepth: maxDepth,
515
579
  }).map((c) => c.name);
516
580
  items = items.concat(
517
- changeV1Items(names, { stage: options.stage, strict: options.strict }),
581
+ changeV1Items(eff, names, { stage: options.stage, strict: options.strict }),
518
582
  );
519
583
  }
520
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();