@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.
@@ -4,7 +4,7 @@ import { join } from 'node:path';
4
4
  import {
5
5
  buildReview,
6
6
  collectChanges,
7
- renderMachine,
7
+ discoverSpecs,
8
8
  renderReviewHtml,
9
9
  specIdOf,
10
10
  TEMPLATES_ROOT,
@@ -13,22 +13,24 @@ import type { Command } from 'commander';
13
13
 
14
14
  import {
15
15
  addReportOutputOptions,
16
+ addSpecDirOption,
16
17
  CliError,
17
18
  cliMaxScanDepth,
19
+ emitReport,
18
20
  exitWith,
19
- loadSpecEntries,
20
- newIo,
21
- resolveOutMode,
21
+ resolveCommandRoot,
22
22
  templateIo,
23
+ type CliContext,
23
24
  } from '../cli-shared.ts';
24
25
 
25
- export function registerReview(program: Command): void {
26
+ export function registerReview(program: Command, ctx: CliContext): void {
26
27
  const review = program
27
28
  .command('review')
28
29
  .description('Aggregate review: unbound signals plus a validate sweep');
29
30
 
30
31
  review.option('--capability <capability>', 'restrict the sweep to one capability/spec id');
31
32
  addReportOutputOptions(review);
33
+ addSpecDirOption(review);
32
34
  review
33
35
  .option('--export-html <path>', 'write a self-contained HTML report')
34
36
  .action(
@@ -38,40 +40,41 @@ export function registerReview(program: Command): void {
38
40
  compactJson?: boolean;
39
41
  output?: string;
40
42
  exportHtml?: string;
43
+ directory?: string;
41
44
  }) => {
42
- const io = newIo();
43
- const entries = loadSpecEntries();
45
+ const io = ctx.io;
46
+ const root = resolveCommandRoot(ctx, options.directory);
47
+ const entries = discoverSpecs(join(root, 'llmanspec', 'specs'), ctx.io);
44
48
  if (options.capability !== undefined) {
45
49
  const known = new Set(entries.map((e) => specIdOf(e)));
46
50
  if (!known.has(options.capability)) {
47
51
  throw new CliError(`capability \`${options.capability}\` not found`);
48
52
  }
49
53
  }
50
- const activeChanges = collectChanges(io, process.cwd(), new Date(), {
51
- maxScanDepth: cliMaxScanDepth(program),
52
- });
53
- // B17: 墙钟由 CLI 注入,core 不直读 new Date()
54
- const now = new Date();
55
- const result = buildReview(
54
+ const activeChanges = collectChanges(
55
+ io,
56
+ resolveCommandRoot(ctx, options.directory),
57
+ new Date(),
56
58
  {
57
- entries,
58
- boundChangeCount: activeChanges.filter((c) => c.hasBinding).length,
59
- activeChanges,
60
- capability: options.capability,
59
+ maxScanDepth: cliMaxScanDepth(program),
61
60
  },
62
- io,
63
61
  );
62
+ // B17: 墙钟由 CLI 注入,core 不直读 new Date()
63
+ const now = new Date();
64
+ const result = buildReview({
65
+ entries,
66
+ boundChangeCount: activeChanges.filter((c) => c.hasBinding).length,
67
+ activeChanges,
68
+ capability: options.capability,
69
+ });
64
70
  if (options.exportHtml !== undefined) {
65
71
  const template = templateIo.readText(join(TEMPLATES_ROOT, 'shared', 'review.html'));
66
72
  writeFileSync(options.exportHtml, renderReviewHtml(template, result, now));
67
73
  console.log(`wrote ${options.exportHtml}`);
68
74
  }
69
- const outMode = resolveOutMode(options.output, options.json, options.compactJson);
70
- if (outMode !== 'human') {
71
- console.log(renderMachine({ signals: result.signals, summary: result.summary }, outMode));
72
- } else {
73
- console.log(result.lines.join('\n'));
74
- }
75
+ emitReport({ signals: result.signals, summary: result.summary }, options, () =>
76
+ result.lines.join('\n'),
77
+ );
75
78
  if (result.exitCode !== 0) exitWith(result.exitCode);
76
79
  },
77
80
  );
@@ -0,0 +1,156 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
+ /**
5
+ * `self` command group (completion capability r110-r112): shell-completion
6
+ * generation from the live commander tree and marker-idempotent rc install
7
+ * with a confirmation gate. Terminal interaction stays in this CLI adapter
8
+ * (core owns only pure text transforms), per the AGENTS interaction rule.
9
+ */
10
+ import { createInterface } from 'node:readline';
11
+
12
+ import {
13
+ COMPLETION_BIN,
14
+ COMPLETION_SHELLS,
15
+ completionBlock,
16
+ isCompletionShell,
17
+ renderCompletionScript,
18
+ resolveBashRc,
19
+ upsertCompletionBlock,
20
+ type CompletionCommandSpec,
21
+ type CompletionShell,
22
+ } from '@llman-sdd/core';
23
+ import { type Command } from 'commander';
24
+
25
+ import { CliError, type CliContext } from '../cli-shared.ts';
26
+
27
+ /** Extract the completion IR from the live commander tree — no second manifest. */
28
+ export function extractCompletionSpec(program: Command): CompletionCommandSpec {
29
+ const walk = (cmd: Command): CompletionCommandSpec => ({
30
+ name: cmd.name(),
31
+ flags: cmd.options.map((o) => o.long).filter((f): f is string => typeof f === 'string'),
32
+ subcommands: cmd.commands
33
+ .filter((c) => (c as unknown as { hidden?: boolean }).hidden !== true)
34
+ .map(walk),
35
+ });
36
+ return walk(program);
37
+ }
38
+
39
+ function completionSnippet(shell: CompletionShell): string {
40
+ switch (shell) {
41
+ case 'bash':
42
+ case 'zsh':
43
+ return `source <(${COMPLETION_BIN} self completion --shell ${shell})`;
44
+ case 'fish':
45
+ return `${COMPLETION_BIN} self completion --shell fish | source`;
46
+ case 'powershell':
47
+ return `${COMPLETION_BIN} self completion --shell powershell | Out-String | Invoke-Expression`;
48
+ case 'elvish':
49
+ return `eval (${COMPLETION_BIN} self completion --shell elvish)`;
50
+ }
51
+ }
52
+
53
+ /** rc/profile target for one shell (r111). Bash keeps the 3-step fallback chain. */
54
+ export function resolveRcPath(shell: CompletionShell, home: string): string {
55
+ switch (shell) {
56
+ case 'bash':
57
+ return resolveBashRc(home, (p) => existsSync(p));
58
+ case 'zsh':
59
+ return join(home, '.zshrc');
60
+ case 'fish':
61
+ return join(home, '.config', 'fish', 'config.fish');
62
+ case 'powershell':
63
+ return resolvePowerShellProfile(home);
64
+ case 'elvish':
65
+ return join(home, '.elvish', 'rc.elv');
66
+ }
67
+ }
68
+
69
+ function resolvePowerShellProfile(home: string): string {
70
+ const envProfile = process.env.PROFILE?.trim();
71
+ if (envProfile !== undefined && envProfile !== '') {
72
+ const absolute = isAbsolute(envProfile) ? resolve(envProfile) : resolve(envProfile);
73
+ const homeAbs = resolve(home);
74
+ if (absolute === homeAbs || absolute.startsWith(homeAbs + sep)) return absolute;
75
+ throw new CliError(`powershell profile resolves outside home: ${absolute}`, 2);
76
+ }
77
+ return join(home, '.config', 'powershell', 'Microsoft.PowerShell_profile.ps1');
78
+ }
79
+
80
+ /** Confirmation gate (r112): TTY prompt, `-y` bypass, non-interactive → refuse. */
81
+ export async function confirmInstall(
82
+ rcPath: string,
83
+ yes: boolean,
84
+ deps: { isInteractive?: () => boolean; prompt?: (text: string) => Promise<string> } = {},
85
+ ): Promise<boolean> {
86
+ if (yes) return true;
87
+ const isInteractive = deps.isInteractive ?? (() => process.stdin.isTTY === true);
88
+ const prompt =
89
+ deps.prompt ??
90
+ ((text: string) =>
91
+ new Promise<string>((resolvePrompt) => {
92
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
93
+ rl.question(text, (answer) => {
94
+ rl.close();
95
+ resolvePrompt(answer);
96
+ });
97
+ }));
98
+ if (!isInteractive()) return false;
99
+ const answer = await prompt(`Install ${COMPLETION_BIN} completion block into ${rcPath}? [y/N] `);
100
+ return /^y(?:es)?$/iu.test(answer.trim());
101
+ }
102
+
103
+ export interface InstallDeps {
104
+ /** Injectable home (tests); defaults to os.homedir() — Bun's homedir()
105
+ * ignores in-process process.env.HOME writes, so tests MUST inject. */
106
+ home?: string;
107
+ isInteractive?: () => boolean;
108
+ prompt?: (text: string) => Promise<string>;
109
+ }
110
+
111
+ export async function runInstall(
112
+ shell: CompletionShell,
113
+ yes: boolean,
114
+ deps: InstallDeps = {},
115
+ ): Promise<void> {
116
+ const home = deps.home ?? homedir();
117
+ const rcPath = resolveRcPath(shell, home);
118
+ const confirmed = await confirmInstall(rcPath, yes, {
119
+ isInteractive: deps.isInteractive,
120
+ prompt: deps.prompt,
121
+ });
122
+ if (!confirmed) {
123
+ throw new CliError(`non-interactive session without --yes — refusing to write ${rcPath}`, 2);
124
+ }
125
+ const existing = existsSync(rcPath) ? readFileSync(rcPath, 'utf8') : '';
126
+ const snippet = completionSnippet(shell);
127
+ const { content } = upsertCompletionBlock(existing, snippet);
128
+ mkdirSync(dirname(rcPath), { recursive: true });
129
+ writeFileSync(rcPath, content);
130
+ console.log(completionBlock(snippet));
131
+ }
132
+
133
+ export function registerSelf(program: Command, _ctx: CliContext): void {
134
+ const self = program.command('self').description('Self-inspection surface (shell completion)');
135
+
136
+ self
137
+ .command('completion')
138
+ .description('Generate or install shell completions (generation prints to stdout)')
139
+ .requiredOption('--shell <shell>', `target shell (${COMPLETION_SHELLS.join('|')})`)
140
+ .option('--install', 'install the marker-wrapped snippet block into the shell rc/profile')
141
+ .option('-y, --yes', 'skip the confirmation prompt (only meaningful with --install)')
142
+ .action(async (options: { shell: string; install?: boolean; yes?: boolean }) => {
143
+ const shell = options.shell.toLowerCase();
144
+ if (!isCompletionShell(shell)) {
145
+ throw new CliError(
146
+ `unknown shell "${options.shell}" — legal values: ${COMPLETION_SHELLS.join(', ')}`,
147
+ 2,
148
+ );
149
+ }
150
+ if (options.install === true) {
151
+ await runInstall(shell, options.yes === true);
152
+ return;
153
+ }
154
+ process.stdout.write(renderCompletionScript(extractCompletionSpec(program), shell));
155
+ });
156
+ }
@@ -8,18 +8,23 @@ import {
8
8
  renderMachine,
9
9
  showChangeJson,
10
10
  specIdOf,
11
+ discoverSpecs,
11
12
  } from '@llman-sdd/core';
12
13
  import type { Command } from 'commander';
13
14
 
14
15
  import {
15
16
  addReportOutputOptions,
17
+ addSpecDirOption,
16
18
  CliError,
17
19
  cliMaxScanDepth,
18
- loadSpecEntries,
19
- newIo,
20
+ loadRootSpecEntries,
21
+ reRootContext,
22
+ specsPrefixFor,
23
+ resolveCommandRoot,
20
24
  resolveChangeIdOrExit,
25
+ resolveRootSpecsDirTolerant,
26
+ type CliContext,
21
27
  } from '../cli-shared.ts';
22
- import { makeCliGit } from '../io.ts';
23
28
 
24
29
  function hasSection(proposal: string, heading: string): boolean {
25
30
  return (
@@ -29,7 +34,7 @@ function hasSection(proposal: string, heading: string): boolean {
29
34
  }
30
35
 
31
36
  function renderSpecJson(
32
- entries: ReturnType<typeof loadSpecEntries>,
37
+ entries: ReturnType<typeof loadRootSpecEntries>,
33
38
  item: string,
34
39
  opts: { metaOnly: boolean; noScenarios: boolean },
35
40
  ): Record<string, unknown> {
@@ -97,13 +102,14 @@ function renderSpecJson(
97
102
  };
98
103
  }
99
104
 
100
- export function registerShow(program: Command): void {
105
+ export function registerShow(program: Command, ctx: CliContext): void {
101
106
  const show = program
102
107
  .command('show')
103
108
  .description('Show a change or spec')
104
109
  .argument('<item>')
105
110
  .option('--type <type>', 'force disambiguation: change | spec')
106
111
  .option('-r, --requirement <n>', 'spec only: show a specific requirement by 1-based index');
112
+ addSpecDirOption(show);
107
113
  addReportOutputOptions(show, {
108
114
  outputHint: 'json | compact-json | toon | human | {json,meta-only|no-scenarios|reqs-only}',
109
115
  });
@@ -116,6 +122,7 @@ export function registerShow(program: Command): void {
116
122
  requirement?: string;
117
123
  json?: boolean;
118
124
  compactJson?: boolean;
125
+ directory?: string;
119
126
  },
120
127
  ) => {
121
128
  // D4 shared surface: the registered --json/--compact-json aliases feed
@@ -175,16 +182,32 @@ export function registerShow(program: Command): void {
175
182
  // `.feature` 后缀的 fileName)命中;r25 spec id 精确匹配优先于 change 前缀,
176
183
  // 不做模糊解析。
177
184
  // Discover once per run — the spec lookup, summary and JSON render below
178
- // all share these entries.
179
- const entries = loadSpecEntries();
180
- const specEntry = entries.find((e) => specIdOf(e) === item);
181
- const isSpec =
182
- options.type === 'spec' ||
183
- existsSync(join('llmanspec', 'specs', `${item}.feature`)) ||
184
- specEntry !== undefined;
185
+ // all share these entries. Lazy: a bare changes-only workspace has no
186
+ // resolvable instance root for the specs half, and the change path below
187
+ // must not require one (r109 root discovery gates specs, not changes).
188
+ type SpecEntries = ReturnType<typeof loadRootSpecEntries>;
189
+ let entriesCache: SpecEntries | null = null;
190
+ const specEntries = (): SpecEntries =>
191
+ (entriesCache ??= loadRootSpecEntries(undefined, ctx.io));
192
+ // spec discovery is attempted but a root-less workspace must not fail
193
+ // here — the change path below is root-independent until the spec half.
194
+ let specEntry: SpecEntries[number] | undefined;
195
+ // r115: the instance root resolved from `--directory` decides where the
196
+ // flat-spec probe, the spec source read and the change face below look —
197
+ // never the launch directory. Absent an instance the change face stays
198
+ // root-independent (changes-only workspace, r109).
199
+ let specRoot = ctx.root;
200
+ try {
201
+ specRoot = resolveCommandRoot(ctx, options.directory);
202
+ entriesCache ??= discoverSpecs(join(specRoot, 'llmanspec', 'specs'), ctx.io);
203
+ specEntry = entriesCache?.find((e) => specIdOf(e) === item);
204
+ } catch {
205
+ specEntry = undefined;
206
+ }
207
+ const flatSpecPath = join(specRoot, 'llmanspec', 'specs', `${item}.feature`);
208
+ const isSpec = options.type === 'spec' || existsSync(flatSpecPath) || specEntry !== undefined;
185
209
 
186
210
  if (isSpec) {
187
- const flatSpecPath = join('llmanspec', 'specs', `${item}.feature`);
188
211
  // discoverSpecs 的 fileName 已是含 specs 目录前缀的相对路径
189
212
  // (如 `llmanspec/specs/<cap>/<cap>.feature`),直接使用。
190
213
  const specPath =
@@ -195,7 +218,7 @@ export function registerShow(program: Command): void {
195
218
  if (asJson) {
196
219
  console.log(
197
220
  renderMachine(
198
- renderSpecJson(entries, item, {
221
+ renderSpecJson(specEntries(), item, {
199
222
  metaOnly,
200
223
  noScenarios: noScenarios || reqsOnly,
201
224
  }),
@@ -207,7 +230,7 @@ export function registerShow(program: Command): void {
207
230
  // text mode: predecessor ignores all output modifiers (meta-only/no-scenarios/-r)
208
231
  // and renders the full source + morphology.
209
232
  const raw = readFileSync(specPath, 'utf8').trimEnd();
210
- const summary = collectSpecs(entries).find((x) => x.id === item);
233
+ const summary = collectSpecs(specEntries()).find((x) => x.id === item);
211
234
  const morphology = summary
212
235
  ? `\n\n## Morphology\nrequirements=${summary.requirementCount} bound=${summary.morphology.requirementBoundCount} unbound=${summary.morphology.requirementUnboundCount} acceptanceCount=${summary.morphology.acceptanceCount}`
213
236
  : '';
@@ -217,10 +240,36 @@ export function registerShow(program: Command): void {
217
240
 
218
241
  // ---- change ----
219
242
  // r61: predecessor r112 prefix chain — exact > unique prefix > multiple > not found.
220
- const resolved = resolveChangeIdOrExit(program, item, { suppressHint: asJson });
243
+ // r115: id resolution, the proposal read and the phase collection all use
244
+ // the resolved instance root; git stays repo-level (r118: branch is a
245
+ // git-level notion, not an instance-root one).
246
+ let rctx = ctx;
247
+ try {
248
+ rctx = reRootContext(ctx, options.directory);
249
+ } catch (error) {
250
+ // changes-only workspace (no config.yaml / specs/): the change path is
251
+ // root-independent, but an explicitly named root must resolve (r109).
252
+ if (options.directory !== undefined) throw error;
253
+ }
254
+ const resolved = resolveChangeIdOrExit(rctx, program, item, { suppressHint: asJson });
221
255
  const changeId = resolved.id;
222
256
  const viaPrefix = resolved.viaPrefix;
223
- const proposal = readFileSync(join('llmanspec', 'changes', changeId, 'proposal.md'), 'utf8');
257
+ const proposal = readFileSync(
258
+ join(rctx.root, 'llmanspec', 'changes', changeId, 'proposal.md'),
259
+ 'utf8',
260
+ );
261
+ // r115: ONE dependency set for the change path, built from the resolved
262
+ // instance root — io/git/root are the re-rooted ones and the spec gate
263
+ // reads THAT instance's registry (derived from this very io). Both
264
+ // output faces share it, so they can never disagree on a gate.
265
+ const deps = {
266
+ io: rctx.io,
267
+ git: rctx.git,
268
+ root: rctx.root,
269
+ specsDir: resolveRootSpecsDirTolerant(rctx),
270
+ // r119: the specs-landed gate judges under this instance's prefix.
271
+ specsPrefix: specsPrefixFor(rctx),
272
+ };
224
273
  if (asJson) {
225
274
  // predecessor parse_change gates: Why first, then What Changes (json only).
226
275
  if (!hasSection(proposal, 'Why')) {
@@ -229,21 +278,12 @@ export function registerShow(program: Command): void {
229
278
  if (!hasSection(proposal, 'What Changes')) {
230
279
  throw new CliError('Change must have a What Changes section');
231
280
  }
232
- const result = showChangeJson(
233
- {
234
- io: newIo(),
235
- git: makeCliGit(process.cwd()),
236
- root: process.cwd(),
237
- specsDir: 'llmanspec/specs',
238
- },
239
- changeId,
240
- { matchedViaPrefix: viaPrefix },
241
- );
281
+ const result = showChangeJson(deps, changeId, { matchedViaPrefix: viaPrefix });
242
282
  console.log(renderMachine(result, showMode));
243
283
  return;
244
284
  }
245
285
  // text: Stage / path / content / Gates trailer (no section gates).
246
- const changes = collectChanges(newIo(), process.cwd(), new Date(), {
286
+ const changes = collectChanges(rctx.io, rctx.root, new Date(), {
247
287
  maxScanDepth: cliMaxScanDepth(program),
248
288
  });
249
289
  const change = changes.find((c) => c.name === changeId);
@@ -251,15 +291,11 @@ export function registerShow(program: Command): void {
251
291
  console.log(`path: ${changeId}`);
252
292
  process.stdout.write(proposal);
253
293
  if (!proposal.endsWith('\n')) console.log();
254
- const gates = showChangeJson(
255
- {
256
- io: newIo(),
257
- git: makeCliGit(process.cwd()),
258
- root: process.cwd(),
259
- specsDir: 'llmanspec/specs',
260
- },
261
- changeId,
262
- ).gateChecks as { name: string; pass: boolean; hint: string }[];
294
+ const gates = showChangeJson(deps, changeId).gateChecks as {
295
+ name: string;
296
+ pass: boolean;
297
+ hint: string;
298
+ }[];
263
299
  const passCount = gates.filter((g) => g.pass).length;
264
300
  console.log(`Gates: ${passCount}/${gates.length} pass`);
265
301
  for (const g of gates.filter((g) => !g.pass)) console.log(`✗ ${g.name}: ${g.hint}`);