@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,47 +1,53 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
2
3
 
3
- import { renderConfigOverview, renderMachine, skillsJson } from '@llman-sdd/core';
4
+ import { renderConfigOverview, skillsJson } from '@llman-sdd/core';
4
5
  import type { Command } from 'commander';
5
6
 
6
7
  import {
7
8
  addReportOutputOptions,
8
- resolveOutMode,
9
+ addSpecDirOption,
10
+ emitReport,
11
+ resolveCommandRoot,
9
12
  skillDesc,
10
13
  warnLegacyBddOnce,
14
+ type CliContext,
11
15
  } from '../cli-shared.ts';
12
16
 
13
- export function registerConfig(program: Command): void {
14
- const configCmd = program
15
- .command('config')
16
- .description('Project configuration commands (view/edit config.yaml)');
17
+ export function registerConfig(program: Command, ctx: CliContext): void {
18
+ const configCmd = program.command('config');
17
19
 
18
- configCmd.description('Print a read-only llmanspec/config.yaml overview').action(() => {
19
- const source = readFileSync('llmanspec/config.yaml', 'utf8');
20
+ configCmd.description('Print a read-only llmanspec/config.yaml overview');
21
+ addSpecDirOption(configCmd);
22
+ configCmd.action((options: { directory?: string }) => {
23
+ const root = resolveCommandRoot(ctx, options.directory);
24
+ const source = readFileSync(join(root, 'llmanspec', 'config.yaml'), 'utf8');
20
25
  warnLegacyBddOnce(source);
21
26
  console.log(renderConfigOverview(source).join('\n'));
22
27
  });
23
28
 
24
29
  const skills = configCmd.command('skills').description('Manage extra_skills (non-interactive)');
25
30
  addReportOutputOptions(skills);
26
- skills.action((options: { json?: boolean; output?: string; compactJson?: boolean }) => {
27
- const path = 'llmanspec/config.yaml';
28
- const source = readFileSync(path, 'utf8');
29
- warnLegacyBddOnce(source);
30
- const info = skillsJson(source);
31
- const mode = resolveOutMode(options.output, options.json, options.compactJson);
32
- if (mode !== 'human') {
33
- console.log(renderMachine(info, mode));
34
- return;
35
- }
36
- const enabled = info.enabled;
37
- const available = info.available;
38
- console.log('Enabled optional skills:');
39
- if (enabled.length === 0) console.log(' (none)');
40
- else for (const s of enabled) console.log(` [x] ${s}`);
41
- console.log();
42
- console.log('Available but not enabled:');
43
- for (const s of available) {
44
- if (!enabled.includes(s)) console.log(` [ ] ${s} — ${skillDesc(s)}`);
45
- }
46
- });
31
+ addSpecDirOption(skills);
32
+ skills.action(
33
+ (options: { json?: boolean; output?: string; compactJson?: boolean; directory?: string }) => {
34
+ const root = resolveCommandRoot(ctx, options.directory);
35
+ const path = join(root, 'llmanspec', 'config.yaml');
36
+ const source = readFileSync(path, 'utf8');
37
+ warnLegacyBddOnce(source);
38
+ const info = skillsJson(source);
39
+ emitReport(info, options, () => {
40
+ const { enabled, available } = info;
41
+ const lines: string[] = ['Enabled optional skills:'];
42
+ if (enabled.length === 0) lines.push(' (none)');
43
+ else for (const s of enabled) lines.push(` [x] ${s}`);
44
+ lines.push('');
45
+ lines.push('Available but not enabled:');
46
+ for (const s of available) {
47
+ if (!enabled.includes(s)) lines.push(` [ ] ${s} — ${skillDesc(s)}`);
48
+ }
49
+ return lines.join('\n');
50
+ });
51
+ },
52
+ );
47
53
  }
@@ -1,6 +1,8 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
2
3
 
3
4
  import {
5
+ discoverSpecs,
4
6
  loadTreeWithAutoRebuild,
5
7
  resolveChatConfig,
6
8
  runContextRetrieval,
@@ -8,55 +10,79 @@ import {
8
10
  } from '@llman-sdd/core';
9
11
  import type { Command } from 'commander';
10
12
 
11
- import { CliError, loadSpecEntries, newIo, resolveBackend } from '../cli-shared.ts';
13
+ import {
14
+ CliError,
15
+ addSpecDirOption,
16
+ reRootContext,
17
+ resolveBackend,
18
+ type CliContext,
19
+ } from '../cli-shared.ts';
12
20
  import { progressNote } from '../progress.ts';
13
21
 
14
22
  // (err path below converted to CliError; resolveBackend may also throw CliError)
15
23
 
16
- export function registerContext(program: Command): void {
17
- program
24
+ export function registerContext(program: Command, ctx: CliContext): void {
25
+ const context = program
18
26
  .command('context')
19
27
  .description('Get specs relevant to a task (agent-oriented, pageindex agentic retrieval)')
20
28
  .option('--task <task>', 'natural language task description')
21
29
  .option('--paths <paths>', 'comma-separated file paths')
22
30
  .option('--top <n>', 'max entries per tier', '5')
23
31
  .option('--backend <name>', 'retrieval backend (pageindex only)')
24
- .action(async (options: { task?: string; paths?: string; top?: string; backend?: string }) => {
25
- resolveBackend(options.backend);
26
- if (!options.task && !options.paths) {
27
- throw new CliError('at least one of --task or --paths is required');
28
- }
29
- const config = resolveChatConfig(process.env as Record<string, string | undefined>);
30
- // r62: lazy refresh runs BEFORE the chat-model gate (predecessor r97 — the index
31
- // self-heals even when retrieval subsequently fails with api_error).
32
- const refresh = loadTreeWithAutoRebuild(newIo(), 'llmanspec/specs', loadSpecEntries(), {
33
- chatModel: process.env.LLMAN_SDD_INDEX_CHAT_MODEL ?? '',
34
- });
35
- if (refresh.tree === null || refresh.error !== null) {
36
- const failed = unavailableResult();
37
- failed.status.errorKind = 'index_rebuild_failed';
38
- failed.status.qualityNote =
39
- refresh.error ?? 'index rebuild failed — run `llman-sdd index rebuild`';
40
- console.log(JSON.stringify(failed, null, 2));
41
- return;
42
- }
43
- const tree = refresh.tree;
44
- if (config === null) {
45
- // predecessor parity: unavailable/error JSON on stdout, exit 0.
46
- console.log(JSON.stringify(unavailableResult(), null, 2));
47
- return;
48
- }
49
- // LLM 链路可能是秒级 — 进度提示防止看上去卡住(B1)
50
- progressNote('context.retrieve', process.cwd());
51
- const result = await runContextRetrieval({
52
- config,
53
- task: options.task ?? '',
54
- paths: options.paths,
55
- top: Number(options.top),
56
- tree,
57
- readFile: (p) => readFileSync(p, 'utf8'),
58
- root: process.cwd(),
59
- });
60
- console.log(JSON.stringify(result, null, 2));
61
- });
32
+ .action(
33
+ async (options: {
34
+ task?: string;
35
+ paths?: string;
36
+ top?: string;
37
+ backend?: string;
38
+ directory?: string;
39
+ }) => {
40
+ resolveBackend(options.backend);
41
+ if (!options.task && !options.paths) {
42
+ throw new CliError('at least one of --task or --paths is required');
43
+ }
44
+ const config = resolveChatConfig(process.env as Record<string, string | undefined>);
45
+ // r62: lazy refresh runs BEFORE the chat-model gate (predecessor r97 — the index
46
+ // self-heals even when retrieval subsequently fails with api_error).
47
+ // r115/r116: the resolved instance root decides every read AND write target,
48
+ // so the index store lands in the --directory instance, not the launch dir.
49
+ const rctx = reRootContext(ctx, options.directory);
50
+ const specsDir = join(rctx.root, 'llmanspec', 'specs');
51
+ const refresh = loadTreeWithAutoRebuild(
52
+ rctx.io,
53
+ specsDir,
54
+ discoverSpecs(specsDir, rctx.io),
55
+ {
56
+ chatModel: process.env.LLMAN_SDD_INDEX_CHAT_MODEL ?? '',
57
+ },
58
+ );
59
+ if (refresh.tree === null || refresh.error !== null) {
60
+ const failed = unavailableResult();
61
+ failed.status.errorKind = 'index_rebuild_failed';
62
+ failed.status.qualityNote =
63
+ refresh.error ?? 'index rebuild failed — run `llman-sdd index rebuild`';
64
+ console.log(JSON.stringify(failed, null, 2));
65
+ return;
66
+ }
67
+ const tree = refresh.tree;
68
+ if (config === null) {
69
+ // predecessor parity: unavailable/error JSON on stdout, exit 0.
70
+ console.log(JSON.stringify(unavailableResult(), null, 2));
71
+ return;
72
+ }
73
+ // LLM 链路可能是秒级 — 进度提示防止看上去卡住(B1)
74
+ progressNote('context.retrieve', rctx.root);
75
+ const result = await runContextRetrieval({
76
+ config,
77
+ task: options.task ?? '',
78
+ paths: options.paths,
79
+ top: Number(options.top),
80
+ tree,
81
+ readFile: (p) => readFileSync(p, 'utf8'),
82
+ root: rctx.root,
83
+ });
84
+ console.log(JSON.stringify(result, null, 2));
85
+ },
86
+ );
87
+ addSpecDirOption(context);
62
88
  }
@@ -1,10 +1,16 @@
1
1
  import { graphMermaid } from '@llman-sdd/core';
2
2
  import type { Command } from 'commander';
3
3
 
4
- import { cliMaxScanDepth, CliError, newIo } from '../cli-shared.ts';
4
+ import {
5
+ cliMaxScanDepth,
6
+ CliError,
7
+ type CliContext,
8
+ addSpecDirOption,
9
+ resolveCommandRoot,
10
+ } from '../cli-shared.ts';
5
11
 
6
- export function registerGraph(program: Command): void {
7
- program
12
+ export function registerGraph(program: Command, ctx: CliContext): void {
13
+ const graph = program
8
14
  .command('graph')
9
15
  .description('Generate a change dependency graph (mermaid)')
10
16
  .argument('[change]', 'seed change id (BFS over depends_on)')
@@ -13,23 +19,29 @@ export function registerGraph(program: Command): void {
13
19
  .option(
14
20
  '--depth <n>',
15
21
  'expansion depth: 0 = scope only, 1 = direct deps (default), N = recursive',
16
- )
17
- .action(
18
- (change: string | undefined, options: { format: string; scope?: string; depth?: string }) => {
19
- if (options.format !== 'mermaid') {
20
- throw new CliError(`unsupported --format: ${options.format} (mermaid only)`, 2);
21
- }
22
- const depth = options.depth !== undefined ? Number(options.depth) : undefined;
23
- if (depth !== undefined && (!Number.isInteger(depth) || depth < 0)) {
24
- throw new CliError(`invalid --depth: ${options.depth}`);
25
- }
26
- const graphOpts = {
27
- scope: options.scope,
28
- depth: depth ?? 1,
29
- seed: change,
30
- maxScanDepth: cliMaxScanDepth(program),
31
- };
32
- console.log(graphMermaid(newIo(), process.cwd(), graphOpts).join('\n'));
33
- },
34
22
  );
23
+ addSpecDirOption(graph);
24
+ graph.action(
25
+ (
26
+ change: string | undefined,
27
+ options: { format: string; scope?: string; depth?: string; directory?: string },
28
+ ) => {
29
+ if (options.format !== 'mermaid') {
30
+ throw new CliError(`unsupported --format: ${options.format} (mermaid only)`, 2);
31
+ }
32
+ const depth = options.depth !== undefined ? Number(options.depth) : undefined;
33
+ if (depth !== undefined && (!Number.isInteger(depth) || depth < 0)) {
34
+ throw new CliError(`invalid --depth: ${options.depth}`, 2);
35
+ }
36
+ const graphOpts = {
37
+ scope: options.scope,
38
+ depth: depth ?? 1,
39
+ seed: change,
40
+ maxScanDepth: cliMaxScanDepth(program),
41
+ };
42
+ console.log(
43
+ graphMermaid(ctx.io, resolveCommandRoot(ctx, options.directory), graphOpts).join('\n'),
44
+ );
45
+ },
46
+ );
35
47
  }
@@ -1,43 +1,53 @@
1
- import { checkIndexFreshness, rebuildIndex, renderMachine } from '@llman-sdd/core';
1
+ import { join } from 'node:path';
2
+
3
+ import { checkIndexFreshness, discoverSpecs, rebuildIndex } from '@llman-sdd/core';
2
4
  import type { Command } from 'commander';
3
5
 
4
6
  import {
5
7
  addReportOutputOptions,
8
+ addSpecDirOption,
9
+ emitReport,
6
10
  exitWith,
7
- loadSpecEntries,
8
- newIo,
11
+ reRootContext,
9
12
  resolveBackend,
10
- resolveOutMode,
13
+ type CliContext,
11
14
  } from '../cli-shared.ts';
12
15
 
13
- export function registerIndex(program: Command): void {
16
+ export function registerIndex(program: Command, ctx: CliContext): void {
14
17
  const indexCmd = program
15
18
  .command('index')
16
19
  .description('Index management commands (rebuild, check freshness)');
17
20
 
18
- indexCmd
21
+ const rebuild = indexCmd
19
22
  .command('rebuild')
20
23
  .description('Rebuild the pageindex tree from spec IR (no LLM)')
21
24
  .option('--backend <name>', 'index backend (pageindex only)')
22
- .action((options: { backend?: string }) => {
25
+ .action((options: { backend?: string; directory?: string }) => {
23
26
  resolveBackend(options.backend);
24
- const result = rebuildIndex(newIo(), 'llmanspec/specs', loadSpecEntries(), {
27
+ // r115/r116: resolve the instance root once and anchor io at it — the
28
+ // pageindex store is written through root-relative paths, which must land
29
+ // in the --directory instance rather than the launch directory.
30
+ const rctx = reRootContext(ctx, options.directory);
31
+ const specsDir = join(rctx.root, 'llmanspec', 'specs');
32
+ const result = rebuildIndex(rctx.io, specsDir, discoverSpecs(specsDir, rctx.io), {
25
33
  chatModel: process.env.LLMAN_SDD_INDEX_CHAT_MODEL ?? '',
26
34
  });
27
35
  for (const line of result.lines.slice(0, -1)) console.error(line);
28
36
  if (result.lines.length > 0) console.log(result.lines.at(-1));
29
37
  });
38
+ addSpecDirOption(rebuild);
30
39
 
31
40
  const check = indexCmd.command('check').description('Check index freshness without rebuilding');
32
41
  addReportOutputOptions(check);
33
- check.action((options: { output?: string; json?: boolean; compactJson?: boolean }) => {
34
- const result = checkIndexFreshness(newIo(), 'llmanspec/specs');
35
- const mode = resolveOutMode(options.output, options.json, options.compactJson);
36
- if (mode !== 'human') {
37
- console.log(renderMachine({ fresh: result.fresh, notes: result.lines }, mode));
38
- } else {
39
- for (const line of result.lines) console.log(line);
40
- }
41
- if (!result.fresh) exitWith(1);
42
- });
42
+ addSpecDirOption(check);
43
+ check.action(
44
+ (options: { output?: string; json?: boolean; compactJson?: boolean; directory?: string }) => {
45
+ const rctx = reRootContext(ctx, options.directory);
46
+ const result = checkIndexFreshness(rctx.io, join(rctx.root, 'llmanspec', 'specs'));
47
+ emitReport({ fresh: result.fresh, notes: result.lines }, options, () =>
48
+ result.lines.join('\n'),
49
+ );
50
+ if (!result.fresh) exitWith(1);
51
+ },
52
+ );
43
53
  }
@@ -1,10 +1,16 @@
1
1
  import { mkdirSync } from 'node:fs';
2
- import { resolve } from 'node:path';
2
+ import { join, resolve } from 'node:path';
3
3
 
4
- import { discoverRoots, refreshSubRootBlocks, runInit } from '@llman-sdd/core';
4
+ import {
5
+ discoverRoots,
6
+ isValidRoot,
7
+ refreshSubRootBlocks,
8
+ resolveInstanceRoot,
9
+ runInit,
10
+ } from '@llman-sdd/core';
5
11
  import type { Command } from 'commander';
6
12
 
7
- import { CliError, templateIo, version } from '../cli-shared.ts';
13
+ import { CliError, templateIo, version, type CliContext } from '../cli-shared.ts';
8
14
  import { makeCliGit, makeIo } from '../io.ts';
9
15
  import { progressNote } from '../progress.ts';
10
16
 
@@ -18,7 +24,7 @@ function isRepoRootInstance(root: string): boolean {
18
24
  return toplevel === null || resolve(toplevel) === root;
19
25
  }
20
26
 
21
- export function registerInit(program: Command): void {
27
+ export function registerInit(program: Command, _ctx: CliContext): void {
22
28
  program
23
29
  .command('init')
24
30
  .description('Initialize llmanspec in your project (--update to refresh existing)')
@@ -28,7 +34,10 @@ export function registerInit(program: Command): void {
28
34
  '--skills',
29
35
  'inject .agents/skills at a sub-root instance (repo-root instances always inject)',
30
36
  )
31
- .option('--locale <locale>', 'locale for generated templates (defaults to config or en)')
37
+ .option(
38
+ '--locale <locale>',
39
+ 'locale for generated templates (explicit config.yaml locale wins; fills a missing key; built-in default zh-Hans)',
40
+ )
32
41
  .option('--lang <locale>', 'alias of --locale')
33
42
  .action(
34
43
  (
@@ -43,23 +52,44 @@ export function registerInit(program: Command): void {
43
52
  root = resolve(path);
44
53
  mkdirSync(root, { recursive: true });
45
54
  }
55
+ const io = makeIo(root);
56
+ const warn = (message: string): void => {
57
+ console.error(message);
58
+ };
59
+ // r106 new-instance notice: creating a fresh instance below an existing
60
+ // one is legal (r93 逐根构造) but usually a cwd mistake — surface both.
61
+ if (!isValidRoot(join(root, 'llmanspec'), io)) {
62
+ const ancestor = resolveInstanceRoot(root, io);
63
+ if (ancestor !== null) {
64
+ warn(
65
+ `WARNING: no llman-sdd instance at ${root}; creating a new one (nearest existing instance: ${ancestor})`,
66
+ );
67
+ }
68
+ }
46
69
  const repoRootInstance = isRepoRootInstance(root);
47
70
  // 模板生成/子根扫块可能耗时 — 进度提示防止看上去卡住(B1)
48
71
  progressNote('init.generate', root);
49
- const result = runInit(makeIo(root), templateIo, {
72
+ const result = runInit(io, templateIo, {
50
73
  update: options.update ?? false,
51
74
  locale: options.locale ?? options.lang,
52
75
  version,
53
76
  skills: options.skills === true || repoRootInstance,
77
+ onWarning: warn,
54
78
  });
55
79
  let swept = '';
56
- if ((options.update ?? false) && repoRootInstance) {
57
- // r93 --update sweep: refresh managed blocks of every discovered
58
- // sub-root (blocks only; skills stay a repo-root surface).
59
- const subRoots = discoverRoots(root, makeIo(root)).filter((r) => r.rootDir !== root);
80
+ if (options.update ?? false) {
81
+ // r93 --update sweep, per-workspace from any instance root: refresh
82
+ // managed blocks of every root discovered from the repo toplevel
83
+ // (outside a repo: from the target). Blocks only; skills stay a
84
+ // repo-root surface.
85
+ const toplevel = makeCliGit(root).runOpt(['rev-parse', '--show-toplevel']);
86
+ const sweepStart = toplevel !== null ? resolve(toplevel) : root;
87
+ const subRoots = discoverRoots(sweepStart, makeIo(sweepStart)).filter(
88
+ (r) => r.rootDir !== root,
89
+ );
60
90
  const refreshed: string[] = [];
61
91
  for (const sub of subRoots) {
62
- if (refreshSubRootBlocks(makeIo(sub.rootDir), templateIo, version)) {
92
+ if (refreshSubRootBlocks(makeIo(sub.rootDir), templateIo, version, warn)) {
63
93
  refreshed.push(sub.rootDir);
64
94
  }
65
95
  }
@@ -1,3 +1,5 @@
1
+ import { join } from 'node:path';
2
+
1
3
  import {
2
4
  collectChanges,
3
5
  collectSpecs,
@@ -5,26 +7,29 @@ import {
5
7
  renderChangesList,
6
8
  renderSpecsJson,
7
9
  renderSpecsList,
10
+ discoverSpecs,
8
11
  } from '@llman-sdd/core';
9
12
  import type { Command } from 'commander';
10
13
 
11
14
  import {
15
+ addSpecDirOption,
12
16
  CliError,
13
17
  assertCompactJsonPairing,
14
18
  addReportOutputOptions,
15
19
  cliMaxScanDepth,
16
- loadSpecEntries,
17
- newIo,
20
+ resolveCommandRoot,
18
21
  resolveOutMode,
22
+ type CliContext,
19
23
  } from '../cli-shared.ts';
20
24
 
21
- export function registerList(program: Command): void {
25
+ export function registerList(program: Command, ctx: CliContext): void {
22
26
  const list = program
23
27
  .command('list')
24
28
  .description('List changes or specs')
25
29
  .option('--specs', 'list specs instead of changes')
26
30
  .option('--sort <order>', 'recent (mtime desc, default) | name');
27
31
  addReportOutputOptions(list);
32
+ addSpecDirOption(list);
28
33
  list.action(
29
34
  (options: {
30
35
  specs?: boolean;
@@ -32,37 +37,38 @@ export function registerList(program: Command): void {
32
37
  compactJson?: boolean;
33
38
  output?: string;
34
39
  sort?: string;
40
+ directory?: string;
35
41
  }) => {
36
- if (!assertCompactJsonPairing(options)) return;
42
+ assertCompactJsonPairing(options);
37
43
  if (options.sort !== undefined && options.sort !== 'recent' && options.sort !== 'name') {
38
- throw new CliError(`invalid --sort: ${options.sort}`);
44
+ throw new CliError(`invalid --sort: ${options.sort}`, 2);
39
45
  }
46
+ // T18/T30: shared pipeline; compact is the single-point minified
47
+ // JSON.stringify (r76) — no per-command newline stripping.
48
+ const mode = resolveOutMode(options.output, options.json, options.compactJson);
40
49
  const emit = (text: string): void => {
41
- console.log(options.compactJson ? text.replaceAll('\n', '') : text);
50
+ console.log(text);
42
51
  };
43
52
  if (options.specs) {
44
- const summaries = collectSpecs(loadSpecEntries());
45
- const specsMode = resolveOutMode(options.output, options.json, options.compactJson);
53
+ const root = resolveCommandRoot(ctx, options.directory);
54
+ const summaries = collectSpecs(discoverSpecs(join(root, 'llmanspec', 'specs'), ctx.io));
46
55
  emit(
47
- specsMode !== 'human'
48
- ? renderSpecsJson(summaries, specsMode)
49
- : renderSpecsList(summaries).join('\n'),
56
+ mode === 'human'
57
+ ? renderSpecsList(summaries).join('\n')
58
+ : renderSpecsJson(summaries, mode),
50
59
  );
51
60
  return;
52
61
  }
53
- let changes = collectChanges(newIo(), process.cwd(), new Date(), {
62
+ let changes = collectChanges(ctx.io, resolveCommandRoot(ctx, options.directory), new Date(), {
54
63
  maxScanDepth: cliMaxScanDepth(program),
55
64
  });
56
65
  if (options.sort === 'name') {
57
66
  changes = [...changes].toSorted((a, b) => a.name.localeCompare(b.name));
58
67
  }
59
68
  emit(
60
- (() => {
61
- const changesMode = resolveOutMode(options.output, options.json, options.compactJson);
62
- return changesMode !== 'human'
63
- ? renderChangesJson(changes, changesMode)
64
- : renderChangesList(changes, new Date()).join('\n');
65
- })(),
69
+ mode === 'human'
70
+ ? renderChangesList(changes, new Date()).join('\n')
71
+ : renderChangesJson(changes, mode),
66
72
  );
67
73
  },
68
74
  );