@llman-sdd/cli 0.11.0 → 0.12.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.
Files changed (45) hide show
  1. package/package.json +13 -5
  2. package/src/cli-shared.ts +85 -43
  3. package/src/commands/archive.ts +0 -9
  4. package/src/commands/change.ts +71 -33
  5. package/src/commands/init.ts +9 -11
  6. package/src/commands/list.ts +0 -2
  7. package/src/commands/project.ts +0 -6
  8. package/src/commands/review.ts +0 -1
  9. package/src/commands/self.ts +3 -1
  10. package/src/commands/show.ts +8 -46
  11. package/src/commands/spec.ts +4 -6
  12. package/src/commands/studio.ts +1315 -0
  13. package/src/commands/studioMcp.ts +862 -0
  14. package/src/commands/studioShared.ts +87 -0
  15. package/src/commands/theorem-write.ts +608 -0
  16. package/src/commands/theorem.ts +479 -0
  17. package/src/commands/validate.ts +108 -47
  18. package/src/io.ts +0 -1
  19. package/src/main.ts +3 -18
  20. package/src/program.ts +16 -12
  21. package/src/progress.ts +1 -3
  22. package/src/studio-server/changeScope.ts +295 -0
  23. package/src/studio-server/hub.ts +98 -0
  24. package/src/studio-server/negotiate.ts +60 -0
  25. package/src/studio-server/security.ts +71 -0
  26. package/src/studio-server/server.ts +1694 -0
  27. package/src/studio-server/static.ts +184 -0
  28. package/src/studio-server/syncDisk.ts +116 -0
  29. package/src/theorems/base.ts +53 -0
  30. package/src/theorems/diagnose.ts +90 -0
  31. package/src/theorems/draft.ts +252 -0
  32. package/src/theorems/os-lock.ts +364 -0
  33. package/src/theorems/paths.ts +11 -0
  34. package/src/theorems/prompts.ts +79 -0
  35. package/src/theorems/quiet.ts +21 -0
  36. package/src/theorems/runner.ts +48 -0
  37. package/src/theorems/transaction.ts +272 -0
  38. package/src/theorems/workspace.ts +103 -0
  39. package/studio-dist/index.html +14 -0
  40. package/studio-dist/static/css/index.00cf48cf.css +1 -0
  41. package/studio-dist/static/js/610.51883f69.js +218 -0
  42. package/studio-dist/static/js/610.51883f69.js.LICENSE.txt +26 -0
  43. package/studio-dist/static/js/index.c5f7c530.js +13 -0
  44. package/studio-dist/static/js/lib-react.a4b07007.js +2 -0
  45. package/studio-dist/static/js/lib-react.a4b07007.js.LICENSE.txt +49 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llman-sdd/cli",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Spec-driven development workflow CLI (the `llman-sdd` command)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -12,7 +12,8 @@
12
12
  "llman-sdd": "./src/main.ts"
13
13
  },
14
14
  "files": [
15
- "src"
15
+ "src",
16
+ "studio-dist"
16
17
  ],
17
18
  "type": "module",
18
19
  "exports": {
@@ -24,11 +25,18 @@
24
25
  "format:check": "bun run --cwd ../.. format:check",
25
26
  "format:write": "bun run --cwd ../.. format:write",
26
27
  "typecheck": "bun run --cwd ../.. typecheck",
27
- "build": "bun run ./scripts/build-binary.ts"
28
+ "build": "bun run ./scripts/build-binary.ts",
29
+ "sync:studio-dist": "bun run ./scripts/sync-studio-dist.ts",
30
+ "prepack": "bun run ./scripts/sync-studio-dist.ts"
28
31
  },
29
32
  "dependencies": {
30
- "@llman-sdd/core": "0.11.0",
31
- "commander": "^15.1.0"
33
+ "@hono/node-server": "^1.19.6",
34
+ "@inquirer/prompts": "^8.8.1",
35
+ "@llman-sdd/core": "0.12.0",
36
+ "@modelcontextprotocol/server": "^2.4.0",
37
+ "commander": "^15.1.0",
38
+ "hono": "^4.10.6",
39
+ "zod": "^4.6.7"
32
40
  },
33
41
  "engines": {
34
42
  "bun": ">=1.4.0",
package/src/cli-shared.ts CHANGED
@@ -8,8 +8,11 @@ import { existsSync, readFileSync } from 'node:fs';
8
8
  import { isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
 
10
10
  import {
11
+ ChangeIdResolveError,
12
+ collectChanges,
11
13
  discoverSpecs,
12
14
  embeddedTemplates,
15
+ formatCliHint,
13
16
  loadConfig,
14
17
  loadConfigDetail,
15
18
  makeEmbeddedTemplateIo,
@@ -18,7 +21,9 @@ import {
18
21
  resolveInstanceRoot,
19
22
  renderMachine,
20
23
  semverLt,
24
+ shouldEmitCliHint,
21
25
  specsPrefixOfInstance,
26
+ type CliHint,
22
27
  type TemplateIo,
23
28
  } from '@llman-sdd/core';
24
29
  import type { Command } from 'commander';
@@ -26,8 +31,6 @@ import type { Command } from 'commander';
26
31
  import pkg from '../package.json' with { type: 'json' };
27
32
  import { makeCliGit, makeIo } from './io.ts';
28
33
 
29
- // Re-exported so leaf consumers (e.g. regression gates under tests/) can type
30
- // against the commander surface without resolving 'commander' themselves.
31
34
  export type { Command } from 'commander';
32
35
 
33
36
  /**
@@ -48,13 +51,6 @@ export function makeCliContext(cwd: string = process.cwd()): CliContext {
48
51
  return { io: makeIo(cwd), git: makeCliGit(cwd), root: cwd, cwd };
49
52
  }
50
53
 
51
- // Version SSOT is this package's package.json (inlined at compile time — a
52
- // single-file binary has no on-disk package.json to read); binary builds
53
- // additionally override it through the LLMAN_SDD_DEV_BUILD_VERSION define injected by
54
- // scripts/build-binary.ts (git tag > package version).
55
-
56
- // Injected at binary build time by scripts/build-binary.ts; falls back to the
57
- // package version when running from source.
58
54
  const baseVersion = process.env.LLMAN_SDD_DEV_BUILD_VERSION ?? pkg.version;
59
55
 
60
56
  /**
@@ -66,7 +62,7 @@ const baseVersion = process.env.LLMAN_SDD_DEV_BUILD_VERSION ?? pkg.version;
66
62
  let dirtySuffix: string | null | undefined;
67
63
 
68
64
  function computeDirtySuffix(): string {
69
- // Dual-runtime surface: `node:child_process.spawnSync` (not `Bun.spawnSync`).
65
+ // Dual-runtime surface: `node:child_process.spawnSync` (not `Bun.spawnSync`). ~keep
70
66
  // It reports a missing git binary through `error` and a non-zero exit through
71
67
  // `status` instead of throwing, so the degradation is explicit — a wide catch
72
68
  // around this block would also swallow ReferenceError from the parsing below.
@@ -90,7 +86,7 @@ export function versionDisplay(): string {
90
86
  /** Package version without the dirty suffix (drift comparison baseline). */
91
87
  export const version: string = baseVersion;
92
88
 
93
- // Compiled single-file binaries have no on-disk templates and Bun <= 1.4.x has
89
+ // Compiled single-file binaries have no on-disk templates and Bun <= 1.4.x has ~keep
94
90
  // no embedding mechanism, so scripts/build-binary.ts injects the template
95
91
  // table through the literal define `process.env.LLMAN_SDD_DEV_BUILD_EMBEDDED_TEMPLATES`
96
92
  // (define only rewrites literal member access — the read must stay here, not
@@ -123,6 +119,53 @@ export class CliError extends Error {
123
119
  }
124
120
  }
125
121
 
122
+ function levenshtein(a: string, b: string): number {
123
+ const m = a.length;
124
+ const n = b.length;
125
+ const dp: number[][] = Array.from({ length: m + 1 }, () =>
126
+ Array.from({ length: n + 1 }, () => 0),
127
+ );
128
+ for (let i = 0; i <= m; i++) dp[i]![0] = i;
129
+ for (let j = 0; j <= n; j++) dp[0]![j] = j;
130
+ for (let i = 1; i <= m; i++) {
131
+ for (let j = 1; j <= n; j++) {
132
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
133
+ dp[i]![j] = Math.min(dp[i - 1]![j]! + 1, dp[i]![j - 1]! + 1, dp[i - 1]![j - 1]! + cost);
134
+ }
135
+ }
136
+ return dp[m]![n]!;
137
+ }
138
+
139
+ /**
140
+ * Deterministic not-found candidates: prefix (lexicographic), then substring
141
+ * (non-prefix, lexicographic), then edit distance <= 2 (distance then lex).
142
+ * Case-sensitive. At most `limit` entries. Same input always same output.
143
+ */
144
+ export function pickNotFoundCandidates(query: string, ids: readonly string[], limit = 5): string[] {
145
+ const unique = [...new Set(ids)];
146
+ const byLex = (a: string, b: string): number => a.localeCompare(b);
147
+ const prefix = unique.filter((id) => id.startsWith(query)).toSorted(byLex);
148
+ const used = new Set(prefix);
149
+ const substr = unique.filter((id) => !used.has(id) && id.includes(query)).toSorted(byLex);
150
+ for (const id of substr) used.add(id);
151
+ const fuzzy = unique
152
+ .filter((id) => !used.has(id) && levenshtein(query, id) <= 2)
153
+ .toSorted((a, b) => {
154
+ const da = levenshtein(query, a);
155
+ const db = levenshtein(query, b);
156
+ return da !== db ? da - db : byLex(a, b);
157
+ });
158
+ for (const id of fuzzy) used.add(id);
159
+ const rest = unique.filter((id) => !used.has(id)).toSorted(byLex);
160
+ return [...prefix, ...substr, ...fuzzy, ...rest].slice(0, limit);
161
+ }
162
+
163
+ export function formatNotFound(kind: string, query: string, ids: readonly string[]): string {
164
+ const picks = pickNotFoundCandidates(query, ids);
165
+ if (picks.length === 0) return `${kind} not found: ${query}`;
166
+ return `${kind} not found: ${query}. Available: ${picks.join(', ')}`;
167
+ }
168
+
126
169
  /** Single exit-code write point for non-error result paths (e.g. sweep verdicts). */
127
170
  export function exitWith(code: number): void {
128
171
  process.exitCode = code;
@@ -138,21 +181,11 @@ export function resolveRootSpecsDir(
138
181
  directory?: string,
139
182
  io: ReturnType<typeof makeIo> = newIo(),
140
183
  ): string {
141
- // r115: the default start is the io's own anchor, NOT the ambient cwd — a
142
- // re-rooted io (reRootContext) must discover its own instance, otherwise
143
- // every re-rooted read silently falls back to the launch directory.
144
184
  const start = directory ?? io.root;
145
185
  const root = resolveInstanceRoot(start, io);
146
186
  if (root === null) {
147
187
  throw new CliError(`no llmanspec root at or above: ${start}`);
148
188
  }
149
- // r115: the legacy relative identity is only valid when the resolved
150
- // instance IS this io's own anchor (the single-root default) — there the
151
- // returned path means `llmanspec/specs` relative to that very anchor, never
152
- // to the ambient cwd. Every other instance is addressed absolutely, so a
153
- // caller consuming the result with its own io cannot re-join a
154
- // launch-relative path into a non-existent directory (which would silently
155
- // empty the registry and turn a red gate green).
156
189
  const absolute = isAbsolute(root) ? root : resolve(io.root, root);
157
190
  return sameDir(absolute, io.root) ? 'llmanspec/specs' : join(absolute, 'llmanspec', 'specs');
158
191
  }
@@ -190,7 +223,7 @@ function warnLegacyCheckTransitions(stripped: boolean): void {
190
223
  if (!stripped || legacyCheckTransitionsWarningShown) return;
191
224
  legacyCheckTransitionsWarningShown = true;
192
225
  console.error(
193
- '[WARNING] llmanspec/config.yaml `specs.check_transitions` was removed — transition-table validation is now tag-scoped per scenario (@transitions force / @no-transitions escape). Delete the key. See migrations/v0.8-v0.9/README.md.',
226
+ '[WARNING] llmanspec/config.yaml `specs.check_transitions` was removed — graph validation is whitelist tag-scoped per scenario (@flow / @state / @nodes / @decision_table). Delete the key. See migrations/v0.8-v0.9/README.md.',
194
227
  );
195
228
  }
196
229
 
@@ -253,13 +286,22 @@ export function resolveChangeIdOrExit(
253
286
  input: string,
254
287
  opts: { suppressHint?: boolean } = {},
255
288
  ): { id: string; viaPrefix: boolean } {
256
- const resolved = resolveChangeId(ctx.io, ctx.root, input, {
257
- maxScanDepth: cliMaxScanDepth(program),
258
- });
259
- if (resolved.viaPrefix && opts.suppressHint !== true) {
260
- console.error(`'${input}' -> '${resolved.id}' (prefix match)`);
289
+ const maxScanDepth = cliMaxScanDepth(program);
290
+ try {
291
+ const resolved = resolveChangeId(ctx.io, ctx.root, input, { maxScanDepth });
292
+ if (resolved.viaPrefix && opts.suppressHint !== true) {
293
+ console.error(`'${input}' -> '${resolved.id}' (prefix match)`);
294
+ }
295
+ return resolved;
296
+ } catch (error) {
297
+ if (error instanceof ChangeIdResolveError && error.message.startsWith('change not found:')) {
298
+ const ids = collectChanges(ctx.io, ctx.root, new Date(0), { maxScanDepth }).map(
299
+ (c) => c.name,
300
+ );
301
+ throw new CliError(formatNotFound('change', input, ids), 1);
302
+ }
303
+ throw error;
261
304
  }
262
- return resolved;
263
305
  }
264
306
 
265
307
  export type OutMode = 'toon' | 'json' | 'compact-json' | 'human';
@@ -317,9 +359,6 @@ export function assertCompactJsonPairing(options: {
317
359
  json?: boolean;
318
360
  output?: string;
319
361
  }): void {
320
- // r76: `--compact-json` is a pairing modifier of `--json`. Standalone use is
321
- // rejected; combining with an explicit `--output toon|human` is ambiguous
322
- // (two modes requested) and equally a usage error.
323
362
  if (options.compactJson === true && options.json !== true) {
324
363
  if (options.output === undefined || options.output === 'toon' || options.output === 'human') {
325
364
  throw new CliError('--compact-json requires --json', 2);
@@ -328,15 +367,24 @@ export function assertCompactJsonPairing(options: {
328
367
  }
329
368
 
330
369
  export const SKILL_DESCRIPTIONS: Record<string, string> = {
331
- 'llman-sdd-continue': 'Fill in missing change artifacts',
332
- 'llman-sdd-ff': 'Fast-forward propose: planning shell → Branch binding → Specs landing',
333
- 'llman-sdd-validate': 'Standalone validation skill',
334
- 'llman-sdd-arch-review': 'Scan shallow modules for deepening candidates',
335
- 'llman-sdd-wayfinder': 'Plan large foggy work as a decision map',
336
- 'llman-sdd-research': 'Delegate external research to a background agent',
370
+ 'llman-sdd-specs': 'Author, evolve, and validate llmanspec/specs/*.feature behavior specs',
371
+ 'llman-sdd-studio':
372
+ 'Visual spec negotiation, onboarding, and code-drift reconciliation in Studio',
373
+ 'llman-sdd-change': 'Optional cross-session change scaffolding, branch binding, and archiving',
374
+ 'llman-sdd-review': 'Independent read-only multi-perspective review with preflight enforcement',
375
+ 'llman-sdd-autopilot': 'Manual-only controlled implementation, gate, and independent review loop',
337
376
  };
338
377
  export const skillDesc = (name: string): string => SKILL_DESCRIPTIONS[name] ?? '';
339
378
 
379
+ /**
380
+ * Emit a single-line JIT hint (`next:` / `fix:`) to stderr in non-JSON modes.
381
+ * Keeps stdout 100% pure for JSON / compact-json / TOON consumers (cli r203).
382
+ */
383
+ export function emitCliHint(hint: CliHint | null | undefined, mode: OutMode = 'human'): void {
384
+ if (!hint || !shouldEmitCliHint(mode)) return;
385
+ console.error(formatCliHint(hint));
386
+ }
387
+
340
388
  /**
341
389
  * Tolerant specs-dir half of the root fork (show gates trailer): bare
342
390
  * changes-only workspaces have no resolvable instance root; there the legacy
@@ -381,12 +429,6 @@ export function reRootContext(ctx: CliContext, directory?: string): CliContext {
381
429
  * Throws the shared domain error when no instance exists at or above start.
382
430
  */
383
431
  export function resolveCommandRoot(ctx: CliContext, directory?: string): string {
384
- // r109/r115: the start is absolutized at this CLI boundary — a relative
385
- // `--directory` (`packages`, `..`, `.`) is relative to the process cwd, and
386
- // the core walk-up cannot climb above a single-segment relative name (its
387
- // parent is the empty string, which terminates the walk). The returned root
388
- // is therefore always absolute, so every downstream path/io join stays
389
- // single-anchored. The error keeps the user's own spelling of the start.
390
432
  const given = directory ?? ctx.root;
391
433
  const root = resolveInstanceRoot(resolve(given), ctx.io);
392
434
  if (root === null) throw new CliError(`no llmanspec root at or above: ${given}`);
@@ -67,8 +67,6 @@ export function registerArchive(program: Command, ctx: CliContext): void {
67
67
  ignoreFile: string[];
68
68
  directory?: string;
69
69
  }) => {
70
- // r118: the cold-backup reads and writes stay inside the resolved
71
- // instance root (`llmanspec/changes/archive`), never the launch cwd.
72
70
  const rctx = reRootContext(ctx, options.directory);
73
71
  const root = rctx.root;
74
72
  warnIfNotMainCheckout(ctx.git);
@@ -78,13 +76,11 @@ export function registerArchive(program: Command, ctx: CliContext): void {
78
76
  for (const line of await runList(io, sz, root)) console.log(line);
79
77
  return;
80
78
  }
81
- // 7z 压缩可能耗时 — 进度提示防止看上去卡住(B1);dry-run/list 不走压缩
82
79
  if (!options.dryRun) progressNote('freeze.pack', root);
83
80
  const result = await runFreeze(io, sz, root, {
84
81
  before: options.before,
85
82
  keepRecent: Number(options.keepRecent),
86
83
  dryRun: options.dryRun,
87
- // r116 exemption: user-supplied paths keep their cwd-literal meaning.
88
84
  ignoreFiles: options.ignoreFile.map((p) => resolve(p)),
89
85
  });
90
86
  for (const line of result.lines) console.log(line);
@@ -114,13 +110,8 @@ export function registerArchive(program: Command, ctx: CliContext): void {
114
110
  warnIfNotMainCheckout(ctx.git);
115
111
  const sz = await makeEmbeddedSevenZip();
116
112
  const io = rctx.io;
117
- // r116 exemption: `--dest` is a user-supplied path and keeps its
118
- // cwd-literal meaning. Core resolves it against the (possibly re-rooted)
119
- // instance io, so hand it over already made absolute — single-root
120
- // invocations keep the literal spelling untouched.
121
113
  const dest =
122
114
  options.dest === undefined || rctx.root === ctx.root ? options.dest : resolve(options.dest);
123
- // 7z 解包可能耗时 — 进度提示防止看上去卡住(B1)
124
115
  progressNote('thaw.unpack', root);
125
116
  const result = await runThaw(io, sz, root, options.change, { dest });
126
117
  for (const line of result.lines) console.log(line);
@@ -3,6 +3,7 @@ import { isAbsolute, join, relative, resolve } from 'node:path';
3
3
 
4
4
  import {
5
5
  CLOSE_OUT_TASK_HINT,
6
+ THEOREMS_DIR_REL,
6
7
  closeOutTaskLines,
7
8
  archiveChange,
8
9
  archiveTaskGate,
@@ -11,6 +12,8 @@ import {
11
12
  defaultBranch,
12
13
  deriveChangeId,
13
14
  harvestAcrossWorktrees,
15
+ hintForChangeNew,
16
+ hintForChangeStart,
14
17
  isCleanTree,
15
18
  newChange,
16
19
  renderChangeIdTemplate,
@@ -18,6 +21,7 @@ import {
18
21
  startChange,
19
22
  validateAllSpecs,
20
23
  decideCloseOutHarness,
24
+ decideCloseOutDangling,
21
25
  extractFrontmatter,
22
26
  readNeedsSpecsChange,
23
27
  type GitLike,
@@ -35,14 +39,15 @@ import {
35
39
  resolveChangeIdOrExit,
36
40
  type CliContext,
37
41
  addReportOutputOptions,
42
+ emitCliHint,
38
43
  emitReport,
39
44
  resolveOutMode,
40
45
  } from '../cli-shared.ts';
41
46
  import { makeCliHarnessRunner } from '../harness.ts';
47
+ import { isPromptAborted, makeInquirerPromptPort } from '../theorems/prompts.ts';
48
+ import { changedTheoremFiles } from './theorem.ts';
42
49
 
43
50
  function runValidateSweep(ctx: CliContext): boolean {
44
- // r118: the sweep validates the resolved instance root's registry, not the
45
- // launch directory's (`ctx` here is already the re-rooted context).
46
51
  const report = validateAllSpecs(loadRootSpecEntries(ctx.root, ctx.io));
47
52
  return report.verdicts.some((v) => !v.ok);
48
53
  }
@@ -81,17 +86,17 @@ function warnBaseBranchDeviation(
81
86
 
82
87
  /** r81: run or refuse the spec verification command before any merge or rename. */
83
88
  function enforceCloseOutHarness(ctx: CliContext, id: string, noCheck: boolean): void {
84
- // r118: the proposal is read and the harness runs at the resolved instance
85
- // root (root-relative io), never at the launch directory.
86
89
  const proposalPath = `llmanspec/changes/${id}/proposal.md`;
87
90
  const proposal = ctx.io.exists(proposalPath) ? ctx.io.readText(proposalPath) : '';
88
91
  const needsSpecsChange = readNeedsSpecsChange(extractFrontmatter(proposal));
89
- const runCommand = loadCliConfig(ctx.root)?.specs?.check_command ?? null;
92
+ const specs = loadCliConfig(ctx.root)?.specs;
93
+ const runCommand = specs?.check_command ?? null;
94
+ const nested = process.env.LLMAN_SDD_HARNESS_ACTIVE === '1';
90
95
  const decision = decideCloseOutHarness({
91
96
  noCheck,
92
97
  needsSpecsChange,
93
98
  runCommand,
94
- nested: process.env.LLMAN_SDD_HARNESS_ACTIVE === '1',
99
+ nested,
95
100
  });
96
101
  if (decision.kind === 'abort') {
97
102
  throw new CliError(`close-out aborted: ${decision.message}`);
@@ -99,12 +104,27 @@ function enforceCloseOutHarness(ctx: CliContext, id: string, noCheck: boolean):
99
104
  if (decision.kind === 'skip') {
100
105
  if (decision.announce) console.error('spec check skipped: --no-check');
101
106
  if (decision.warning !== undefined) console.error(`[WARNING] ${decision.warning}`);
102
- return;
107
+ } else {
108
+ const result = makeCliHarnessRunner().run(decision.command, ctx.root);
109
+ if (result.spawnError !== undefined || result.exitCode !== 0) {
110
+ const why = result.spawnError ?? `exit ${result.exitCode}`;
111
+ throw new CliError(`close-out aborted: spec check failed (${why})`);
112
+ }
113
+ }
114
+ const dangling = decideCloseOutDangling({
115
+ noCheck,
116
+ needsSpecsChange,
117
+ danglingCommand: specs?.check_dangling_bdd_command ?? null,
118
+ nested,
119
+ });
120
+ if (dangling.kind === 'abort') {
121
+ throw new CliError(`close-out aborted: ${dangling.message}`);
103
122
  }
104
- const result = makeCliHarnessRunner().run(decision.command, ctx.root);
105
- if (result.spawnError !== undefined || result.exitCode !== 0) {
106
- const why = result.spawnError ?? `exit ${result.exitCode}`;
107
- throw new CliError(`close-out aborted: spec check failed (${why})`);
123
+ if (dangling.kind === 'skip') return;
124
+ const danglingResult = makeCliHarnessRunner().run(dangling.command, ctx.root);
125
+ if (danglingResult.spawnError !== undefined || danglingResult.exitCode !== 0) {
126
+ const why = danglingResult.spawnError ?? `exit ${danglingResult.exitCode}`;
127
+ throw new CliError(`close-out aborted: dangling bdd check failed (${why})`);
108
128
  }
109
129
  }
110
130
 
@@ -127,12 +147,6 @@ function harvestIo(top: string): {
127
147
  isDirectory: (p: string) => boolean;
128
148
  } {
129
149
  const at = (p: string): string => (isAbsolute(p) ? p : join(top, p));
130
- // r109/r35: a linked worktree without the instance directory is "absent",
131
- // not an error — an unguarded lstat/readdir would leak a bare `ENOENT:
132
- // ... lstat '<worktree>/llmanspec'` and abort the whole harvest. Only
133
- // absence stays silent: this adapter also serves the primary tree, and the
134
- // core layer's warning channel (`cannot list <dir>`, r35) exists precisely
135
- // for real read errors (EACCES, ELOOP), so those MUST propagate.
136
150
  const isAbsent = (error: unknown): boolean => {
137
151
  const code = (error as NodeJS.ErrnoException | null)?.code;
138
152
  return code === 'ENOENT' || code === 'ENOTDIR';
@@ -181,8 +195,6 @@ function deriveNewId(ctx: CliContext, description: string, verb: string | undefi
181
195
  const template = cliConfig?.change_id?.template;
182
196
  if (template) {
183
197
  const { verb: v, subject } = splitVerb(slug, verb);
184
- // unify-numeric-id-allocation: the template variable consumes the same
185
- // worktree-union collector as `change next-id` — one survey, one max+1.
186
198
  return renderChangeIdTemplate(template, {
187
199
  llman_sdd_unique_id: harvestForRoot(ctx).nextNumber,
188
200
  verb: v,
@@ -197,6 +209,41 @@ function deriveNewId(ctx: CliContext, description: string, verb: string | undefi
197
209
  return slug;
198
210
  }
199
211
 
212
+ export async function enforceArchiveTheoremGate(
213
+ changed: readonly string[],
214
+ options: {
215
+ interactive?: boolean;
216
+ confirm?: (message: string) => Promise<boolean>;
217
+ /** Warning printer (tests inject a no-op); defaults to console.error. */
218
+ warn?: (line: string) => void;
219
+ } = {},
220
+ ): Promise<void> {
221
+ if (changed.length === 0) return;
222
+ const list = changed.join(', ');
223
+ const interactive =
224
+ options.interactive ?? (process.stdin.isTTY === true && process.stdout.isTTY === true);
225
+ if (!interactive) {
226
+ throw new CliError(
227
+ `changes under \`${THEOREMS_DIR_REL}/\` detected relative to merge-base: ${list}. Agent workflows must not modify Human Theorems. Ask a human to review and commit theorem updates separately, or resolve the conflict before archiving.`,
228
+ );
229
+ }
230
+ const warn = options.warn ?? console.error;
231
+ warn(
232
+ `[WARNING] this archive carries \`${THEOREMS_DIR_REL}/\` changes relative to the merge base: ${list}`,
233
+ );
234
+ warn('Human Theorems are human-owned. Confirm only if you personally reviewed these changes.');
235
+ let confirmed: boolean;
236
+ try {
237
+ const confirm =
238
+ options.confirm ??
239
+ (async (message: string) => (await makeInquirerPromptPort()).confirm(message));
240
+ confirmed = await confirm('Archive anyway with these theorem changes?');
241
+ } catch (error) {
242
+ if (isPromptAborted(error)) confirmed = false;
243
+ else throw error;
244
+ }
245
+ if (!confirmed) throw new CliError('archive cancelled: theorem changes were not confirmed');
246
+ }
200
247
  export function registerChange(program: Command, ctx: CliContext): void {
201
248
  const change = program
202
249
  .command('change')
@@ -225,8 +272,6 @@ export function registerChange(program: Command, ctx: CliContext): void {
225
272
  if ((id === undefined) === (options.from === undefined)) {
226
273
  throw new CliError('<CHANGE> and --from are mutually exclusive; pass one or the other');
227
274
  }
228
- // r118: the draft is created inside the nearest instance root, never in
229
- // a cwd-literal `llmanspec/` (and an instance-less path is a domain error).
230
275
  const rctx = reRootContext(ctx, options.directory);
231
276
  if (options.dryRun) {
232
277
  console.log(id ?? deriveNewId(rctx, options.from as string, options.verb));
@@ -237,10 +282,12 @@ export function registerChange(program: Command, ctx: CliContext): void {
237
282
  console.log(`derived change id: ${derived}`);
238
283
  const result = newChange(rctx.io, { id: derived, force: options.force });
239
284
  console.log(`./${result.path}`);
285
+ emitCliHint(hintForChangeNew(derived), 'human');
240
286
  return;
241
287
  }
242
288
  const result = newChange(rctx.io, { id, force: options.force });
243
289
  console.log(`./${result.path}`);
290
+ emitCliHint(hintForChangeNew(id as string), 'human');
244
291
  },
245
292
  );
246
293
 
@@ -291,6 +338,7 @@ export function registerChange(program: Command, ctx: CliContext): void {
291
338
  `started change \`${resolved.id}\` → branch \`${result.branch}\` base \`${result.baseSha}\` base-branch \`${result.baseBranch}\``,
292
339
  );
293
340
  if (result.worktreePath !== undefined) console.log(`worktree ${result.worktreePath}`);
341
+ emitCliHint(hintForChangeStart(resolved.id), 'human');
294
342
  },
295
343
  );
296
344
 
@@ -301,14 +349,8 @@ export function registerChange(program: Command, ctx: CliContext): void {
301
349
  addSpecDirOption(nextId);
302
350
  nextId.action(
303
351
  (options: { json?: boolean; output?: string; compactJson?: boolean; directory?: string }) => {
304
- // r35/r118: the scan covers the resolved instance tree plus every linked
305
- // git worktree's own copy of it (degrades to the current tree when
306
- // worktree list fails).
307
352
  const rctx = reRootContext(ctx, options.directory);
308
353
  const harvest = harvestForRoot(rctx);
309
- // r35: the human face is exactly the two legacy lines (bare default and
310
- // explicit `--output human`); machine modes render the harvest IR through
311
- // the shared pipeline.
312
354
  const human = (): string => {
313
355
  const lines: string[] = [];
314
356
  if (harvest.maxNumber === null) lines.push('no numbered change dirs found in tree');
@@ -338,7 +380,7 @@ export function registerChange(program: Command, ctx: CliContext): void {
338
380
  .option('--dry-run', 'print the rename plan only');
339
381
  addSpecDirOption(archiveCmd);
340
382
  archiveCmd.action(
341
- (
383
+ async (
342
384
  id: string,
343
385
  options: {
344
386
  into?: string;
@@ -380,6 +422,7 @@ export function registerChange(program: Command, ctx: CliContext): void {
380
422
  if (failed) {
381
423
  throw new CliError('archive aborted: validation sweep failed (use --no-check to skip)');
382
424
  }
425
+ await enforceArchiveTheoremGate(changedTheoremFiles(rctx, undefined));
383
426
  }
384
427
  if (!isCleanTree(ctx.git)) {
385
428
  throw new CliError('`change archive` requires a clean working tree');
@@ -437,10 +480,6 @@ export function registerChange(program: Command, ctx: CliContext): void {
437
480
  const git = ctx.git;
438
481
  const diff = changeDiff(git, rctx.io, id);
439
482
  if (options.exportPatch !== undefined) {
440
- // writeText creates parent dirs — exporting into a fresh path like
441
- // out/change.patch must not ENOENT. Export wins over any output mode.
442
- // r116 exemption: the export path is a user-supplied argument and keeps
443
- // its cwd-literal meaning.
444
483
  ctx.io.writeText(options.exportPatch, diff);
445
484
  console.log(`wrote ${options.exportPatch}`);
446
485
  return;
@@ -449,7 +488,6 @@ export function registerChange(program: Command, ctx: CliContext): void {
449
488
  emitReport(changeDiffInfo(git, rctx.io, id), options);
450
489
  return;
451
490
  }
452
- // T37: an empty diff says so instead of printing nothing.
453
491
  if (diff.trim() === '') console.log('no differences against the base (empty diff)');
454
492
  else console.log(diff);
455
493
  },
@@ -74,9 +74,7 @@ export function registerInit(program: Command, _ctx: CliContext): void {
74
74
  markdown: readFileSync(join(skillsDir, name, 'SKILL.md'), 'utf8'),
75
75
  });
76
76
  }
77
- } catch {
78
- // missing directory is an empty install
79
- }
77
+ } catch {}
80
78
  const result = checkSkillVersions(skills, version);
81
79
  if (!result.ok) throw new CliError(result.message, 1);
82
80
  console.log(result.message);
@@ -86,8 +84,6 @@ export function registerInit(program: Command, _ctx: CliContext): void {
86
84
  const warn = (message: string): void => {
87
85
  console.error(message);
88
86
  };
89
- // r106 new-instance notice: creating a fresh instance below an existing
90
- // one is legal (r93 逐根构造) but usually a cwd mistake — surface both.
91
87
  if (!isValidRoot(join(root, 'llmanspec'), io)) {
92
88
  const ancestor = resolveInstanceRoot(root, io);
93
89
  if (ancestor !== null) {
@@ -97,21 +93,17 @@ export function registerInit(program: Command, _ctx: CliContext): void {
97
93
  }
98
94
  }
99
95
  const repoRootInstance = isRepoRootInstance(root);
100
- // 模板生成/子根扫块可能耗时 — 进度提示防止看上去卡住(B1)
101
96
  progressNote('init.generate', root);
102
97
  const result = runInit(io, templateIo, {
103
98
  update: options.update ?? false,
104
99
  locale: options.locale ?? options.lang,
105
100
  version,
106
101
  skills: options.skills === true || repoRootInstance,
102
+ uncomment: repoRootInstance,
107
103
  onWarning: warn,
108
104
  });
109
105
  let swept = '';
110
106
  if (options.update ?? false) {
111
- // r93 --update sweep, per-workspace from any instance root: refresh
112
- // managed blocks of every root discovered from the repo toplevel
113
- // (outside a repo: from the target). Blocks only; skills stay a
114
- // repo-root surface.
115
107
  const toplevel = makeCliGit(root).runOpt(['rev-parse', '--show-toplevel']);
116
108
  const sweepStart = toplevel !== null ? resolve(toplevel) : root;
117
109
  const subRoots = discoverRoots(sweepStart, makeIo(sweepStart)).filter(
@@ -126,7 +118,13 @@ export function registerInit(program: Command, _ctx: CliContext): void {
126
118
  if (refreshed.length > 0) swept = `, blocks refreshed: ${refreshed.join(', ')}`;
127
119
  }
128
120
  const removed = result.removed.length > 0 ? `, removed: ${result.removed.join(', ')}` : '';
129
- console.log(`initialized llmanspec (${result.skills.length} skills${removed}${swept})`);
121
+ const uncommentNote =
122
+ result.uncomment?.changed === true
123
+ ? `, ${result.uncomment.path} patched (+${String(result.uncomment.addedPreserve.length)} preserve, +${String(result.uncomment.addedExclude.length)} exclude)`
124
+ : '';
125
+ console.log(
126
+ `initialized llmanspec (${result.skills.length} skills${removed}${swept}${uncommentNote})`,
127
+ );
130
128
  },
131
129
  );
132
130
  }
@@ -43,8 +43,6 @@ export function registerList(program: Command, ctx: CliContext): void {
43
43
  if (options.sort !== undefined && options.sort !== 'recent' && options.sort !== 'name') {
44
44
  throw new CliError(`invalid --sort: ${options.sort}`, 2);
45
45
  }
46
- // T18/T30: shared pipeline; compact is the single-point minified
47
- // JSON.stringify (r76) — no per-command newline stripping.
48
46
  const mode = resolveOutMode(options.output, options.json, options.compactJson);
49
47
  const emit = (text: string): void => {
50
48
  console.log(text);
@@ -49,10 +49,6 @@ export function registerProject(program: Command, ctx: CliContext): void {
49
49
  .description('Remap globally duplicated req ids (report with --dry-run)')
50
50
  .option('--dry-run', 'report the remap plan without writing')
51
51
  .action((options: { dryRun?: boolean; directory?: string }) => {
52
- // dedupe registry covers requirement handles (`@req` on 规则: headers) only;
53
- // duplicates follow the occurrence model (同文件内共用或跨文件均算)
54
- // r115: the instance root (--directory, else the nearest at or above cwd)
55
- // scopes the registry AND the write plan — never the launch dir alone.
56
52
  const entries = loadRootSpecEntries(options.directory, ctx.io);
57
53
  const { duplicates } = buildReqRegistry(entries);
58
54
  if (duplicates.length === 0) {
@@ -60,7 +56,6 @@ export function registerProject(program: Command, ctx: CliContext): void {
60
56
  return;
61
57
  }
62
58
  const io = ctx.io;
63
- // r43: --dry-run is zero-side-effect — plan only, never write.
64
59
  const plan = planDedupe(
65
60
  entries,
66
61
  io,
@@ -70,7 +65,6 @@ export function registerProject(program: Command, ctx: CliContext): void {
70
65
  apply: !options.dryRun,
71
66
  },
72
67
  );
73
- // predecessor output: `{cap}: {from} → {to}` per remap (prefix in dry-run) + count line.
74
68
  for (const item of plan) {
75
69
  const cap = item.remapFile.replace(/^.*specs\//u, '').replace(/\.feature$/u, '');
76
70
  const prefix = options.dryRun ? '[dry-run] ' : '';
@@ -59,7 +59,6 @@ export function registerReview(program: Command, ctx: CliContext): void {
59
59
  maxScanDepth: cliMaxScanDepth(program),
60
60
  },
61
61
  );
62
- // B17: 墙钟由 CLI 注入,core 不直读 new Date()
63
62
  const now = new Date();
64
63
  const result = buildReview({
65
64
  entries,
@@ -106,6 +106,8 @@ export interface InstallDeps {
106
106
  home?: string;
107
107
  isInteractive?: () => boolean;
108
108
  prompt?: (text: string) => Promise<string>;
109
+ /** Diagnostic printer (tests inject a no-op); defaults to console.log. */
110
+ out?: (text: string) => void;
109
111
  }
110
112
 
111
113
  export async function runInstall(
@@ -127,7 +129,7 @@ export async function runInstall(
127
129
  const { content } = upsertCompletionBlock(existing, snippet);
128
130
  mkdirSync(dirname(rcPath), { recursive: true });
129
131
  writeFileSync(rcPath, content);
130
- console.log(completionBlock(snippet));
132
+ (deps.out ?? console.log)(completionBlock(snippet));
131
133
  }
132
134
 
133
135
  export function registerSelf(program: Command, _ctx: CliContext): void {