@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,5 +1,5 @@
1
- import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs';
2
- import { basename, resolve } from 'node:path';
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path';
3
3
 
4
4
  import {
5
5
  CLOSE_OUT_TASK_HINT,
@@ -15,7 +15,6 @@ import {
15
15
  archiveTaskGate,
16
16
  isCleanTree,
17
17
  newChange,
18
- nextUniqueNumber,
19
18
  renderChangeIdTemplate,
20
19
  splitVerb,
21
20
  startChange,
@@ -29,16 +28,24 @@ import { Option, type Command } from 'commander';
29
28
 
30
29
  import {
31
30
  CliError,
31
+ addSpecDirOption,
32
32
  loadCliConfig,
33
- loadSpecEntries,
34
- newIo,
33
+ loadRootSpecEntries,
34
+ reRootContext,
35
+ instanceDirRelFor,
36
+ specsPrefixFor,
35
37
  resolveChangeIdOrExit,
38
+ type CliContext,
39
+ addReportOutputOptions,
40
+ emitReport,
41
+ resolveOutMode,
36
42
  } from '../cli-shared.ts';
37
43
  import { makeCliHarnessRunner } from '../harness.ts';
38
- import { makeCliGit } from '../io.ts';
39
44
 
40
- function runValidateSweep(): boolean {
41
- const report = validateAllSpecs(loadSpecEntries(), newIo());
45
+ function runValidateSweep(ctx: CliContext): boolean {
46
+ // r118: the sweep validates the resolved instance root's registry, not the
47
+ // launch directory's (`ctx` here is already the re-rooted context).
48
+ const report = validateAllSpecs(loadRootSpecEntries(ctx.root, ctx.io));
42
49
  return report.verdicts.some((v) => !v.ok);
43
50
  }
44
51
 
@@ -75,11 +82,13 @@ function warnBaseBranchDeviation(
75
82
  }
76
83
 
77
84
  /** r81: run or refuse the spec verification command before any merge or rename. */
78
- function enforceCloseOutHarness(id: string, noCheck: boolean): void {
85
+ function enforceCloseOutHarness(ctx: CliContext, id: string, noCheck: boolean): void {
86
+ // r118: the proposal is read and the harness runs at the resolved instance
87
+ // root (root-relative io), never at the launch directory.
79
88
  const proposalPath = `llmanspec/changes/${id}/proposal.md`;
80
- const proposal = existsSync(proposalPath) ? readFileSync(proposalPath, 'utf8') : '';
89
+ const proposal = ctx.io.exists(proposalPath) ? ctx.io.readText(proposalPath) : '';
81
90
  const needsSpecsChange = readNeedsSpecsChange(extractFrontmatter(proposal));
82
- const runCommand = loadCliConfig()?.specs?.check_command ?? null;
91
+ const runCommand = loadCliConfig(ctx.root)?.specs?.check_command ?? null;
83
92
  const decision = decideCloseOutHarness({
84
93
  noCheck,
85
94
  needsSpecsChange,
@@ -94,7 +103,7 @@ function enforceCloseOutHarness(id: string, noCheck: boolean): void {
94
103
  if (decision.warning !== undefined) console.error(`[WARNING] ${decision.warning}`);
95
104
  return;
96
105
  }
97
- const result = makeCliHarnessRunner().run(decision.command, process.cwd());
106
+ const result = makeCliHarnessRunner().run(decision.command, ctx.root);
98
107
  if (result.spawnError !== undefined || result.exitCode !== 0) {
99
108
  const why = result.spawnError ?? `exit ${result.exitCode}`;
100
109
  throw new CliError(`close-out aborted: spec check failed (${why})`);
@@ -104,10 +113,63 @@ function enforceCloseOutHarness(id: string, noCheck: boolean): void {
104
113
  /** `--method squash|ff` guard shared by `change archive` / `change finalize`. */
105
114
  function assertMergeMethod(method: string | undefined): void {
106
115
  if (method !== undefined && method !== 'squash' && method !== 'ff') {
107
- throw new CliError(`invalid --method: ${method}`);
116
+ throw new CliError(`invalid --method: ${method}`, 2);
108
117
  }
109
118
  }
110
119
 
120
+ /**
121
+ * r35: the change-id harvest scan must skip symlinks and dot directories.
122
+ * `lstat` (never `stat`) reports the link itself, so a symlink — even one
123
+ * pointing at a directory — is not a directory here and is neither counted nor
124
+ * recursed into. r118: paths are anchored at the git toplevel so the same
125
+ * relative instance directory addresses every linked worktree's own instance.
126
+ */
127
+ function harvestIo(top: string): {
128
+ listDir: (p: string) => string[];
129
+ isDirectory: (p: string) => boolean;
130
+ } {
131
+ const at = (p: string): string => (isAbsolute(p) ? p : join(top, p));
132
+ // r109/r35: a linked worktree without the instance directory is "absent",
133
+ // not an error — an unguarded lstat/readdir would leak a bare `ENOENT:
134
+ // ... lstat '<worktree>/llmanspec'` and abort the whole harvest. Only
135
+ // absence stays silent: this adapter also serves the primary tree, and the
136
+ // core layer's warning channel (`cannot list <dir>`, r35) exists precisely
137
+ // for real read errors (EACCES, ELOOP), so those MUST propagate.
138
+ const isAbsent = (error: unknown): boolean => {
139
+ const code = (error as NodeJS.ErrnoException | null)?.code;
140
+ return code === 'ENOENT' || code === 'ENOTDIR';
141
+ };
142
+ return {
143
+ listDir: (p) => {
144
+ try {
145
+ return readdirSync(at(p));
146
+ } catch (error) {
147
+ if (isAbsent(error)) return [];
148
+ throw error;
149
+ }
150
+ },
151
+ isDirectory: (p) => {
152
+ try {
153
+ return lstatSync(at(p)).isDirectory();
154
+ } catch (error) {
155
+ if (isAbsent(error)) return false;
156
+ throw error;
157
+ }
158
+ },
159
+ };
160
+ }
161
+
162
+ /** r113/r118: number harvest for `ctx`'s instance root across linked worktrees. */
163
+ function harvestForRoot(ctx: CliContext): ReturnType<typeof harvestAcrossWorktrees> {
164
+ const top = ctx.git.runOpt(['rev-parse', '--show-toplevel']) ?? ctx.root;
165
+ const rel = relative(top, resolve(ctx.root));
166
+ return harvestAcrossWorktrees(
167
+ ctx.git,
168
+ harvestIo(top),
169
+ rel === '' ? 'llmanspec' : join(rel, 'llmanspec'),
170
+ );
171
+ }
172
+
111
173
  /**
112
174
  * Unified `change new --from` id derivation (r44/r60). With a configured
113
175
  * `change_id.template` the id is rendered through it (Strict: referencing an
@@ -115,30 +177,16 @@ function assertMergeMethod(method: string | undefined): void {
115
177
  * heuristic slug is otherwise returned unchanged unless an explicit `--verb`
116
178
  * is given, in which case the override is applied as `{verb}-{subject}` (r44).
117
179
  */
118
- /**
119
- * r35: `change next-id` / change-id harvest scan must skip symlinks and dot
120
- * directories. `lstat` (never `stat`) reports the link itself, so a symlink —
121
- * even one pointing at a directory — is not a directory here and is neither
122
- * counted nor recursed into. The next-id harvest is the single consumer that
123
- * requires this no-follow semantics cycle-wide.
124
- */
125
- function isDirectoryNoFollow(path: string): boolean {
126
- return lstatSync(resolve(path)).isDirectory();
127
- }
128
- function deriveNewId(description: string, verb: string | undefined): string {
180
+ function deriveNewId(ctx: CliContext, description: string, verb: string | undefined): string {
129
181
  const slug = deriveChangeId(description);
130
- const cliConfig = loadCliConfig();
182
+ const cliConfig = loadCliConfig(ctx.root);
131
183
  const template = cliConfig?.change_id?.template;
132
184
  if (template) {
133
185
  const { verb: v, subject } = splitVerb(slug, verb);
186
+ // unify-numeric-id-allocation: the template variable consumes the same
187
+ // worktree-union collector as `change next-id` — one survey, one max+1.
134
188
  return renderChangeIdTemplate(template, {
135
- llman_sdd_unique_id: nextUniqueNumber(
136
- {
137
- listDir: (p) => readdirSync(resolve(p)),
138
- isDirectory: isDirectoryNoFollow,
139
- },
140
- 'llmanspec',
141
- ),
189
+ llman_sdd_unique_id: harvestForRoot(ctx).nextNumber,
142
190
  verb: v,
143
191
  subject,
144
192
  date: new Date().toISOString().slice(0, 10),
@@ -151,46 +199,54 @@ function deriveNewId(description: string, verb: string | undefined): string {
151
199
  return slug;
152
200
  }
153
201
 
154
- export function registerChange(program: Command): void {
202
+ export function registerChange(program: Command, ctx: CliContext): void {
155
203
  const change = program
156
204
  .command('change')
157
205
  .description('Change lifecycle: new / start / attach / next-id / diff / finalize');
158
206
 
159
- change
207
+ const newCmd = change
160
208
  .command('new')
161
209
  .description('Create a change draft (exactly one of <id> or --from)')
162
210
  .argument('[id]')
163
211
  .option('--from <description>', 'description the id is derived from')
164
212
  .option('--verb <verb>', 'explicit verb for change_id.template rendering')
165
213
  .option('--force', 'overwrite an existing proposal.md')
166
- .option('--dry-run', 'print the resulting id without creating anything')
167
- .action(
168
- (
169
- id: string | undefined,
170
- options: { from?: string; verb?: string; force?: boolean; dryRun?: boolean },
171
- ) => {
172
- if ((id === undefined) === (options.from === undefined)) {
173
- throw new CliError('<CHANGE> and --from are mutually exclusive; pass one or the other');
174
- }
175
- if (options.dryRun) {
176
- console.log(id ?? deriveNewId(options.from as string, options.verb));
177
- return;
178
- }
179
- if (options.from !== undefined) {
180
- const derived = deriveNewId(options.from, options.verb);
181
- console.log(`derived change id: ${derived}`);
182
- const io = newIo();
183
- const result = newChange(io, { id: derived, force: options.force });
184
- console.log(`./${result.path}`);
185
- return;
186
- }
187
- const io = newIo();
188
- const result = newChange(io, { id, force: options.force });
189
- console.log(`./${result.path}`);
214
+ .option('--dry-run', 'print the resulting id without creating anything');
215
+ addSpecDirOption(newCmd);
216
+ newCmd.action(
217
+ (
218
+ id: string | undefined,
219
+ options: {
220
+ from?: string;
221
+ verb?: string;
222
+ force?: boolean;
223
+ dryRun?: boolean;
224
+ directory?: string;
190
225
  },
191
- );
226
+ ) => {
227
+ if ((id === undefined) === (options.from === undefined)) {
228
+ throw new CliError('<CHANGE> and --from are mutually exclusive; pass one or the other');
229
+ }
230
+ // r118: the draft is created inside the nearest instance root, never in
231
+ // a cwd-literal `llmanspec/` (and an instance-less path is a domain error).
232
+ const rctx = reRootContext(ctx, options.directory);
233
+ if (options.dryRun) {
234
+ console.log(id ?? deriveNewId(rctx, options.from as string, options.verb));
235
+ return;
236
+ }
237
+ if (options.from !== undefined) {
238
+ const derived = deriveNewId(rctx, options.from, options.verb);
239
+ console.log(`derived change id: ${derived}`);
240
+ const result = newChange(rctx.io, { id: derived, force: options.force });
241
+ console.log(`./${result.path}`);
242
+ return;
243
+ }
244
+ const result = newChange(rctx.io, { id, force: options.force });
245
+ console.log(`./${result.path}`);
246
+ },
247
+ );
192
248
 
193
- change
249
+ const startCmd = change
194
250
  .command('start')
195
251
  .description('Bind the change to a new feature branch (clean tree + default branch gates)')
196
252
  .argument('<id>')
@@ -205,26 +261,36 @@ export function registerChange(program: Command): void {
205
261
  .option(
206
262
  '--worktree',
207
263
  'create the branch in a dedicated worktree (sdd.worktree_root / sdd.worktree_naming config) instead of switching this checkout',
208
- )
209
- .action((id: string, options: { branchPrefix?: string; base?: string; worktree?: boolean }) => {
210
- const resolved = resolveChangeIdOrExit(program, id);
211
- const git = makeCliGit(process.cwd());
212
- const config = loadCliConfig();
213
- const result = startChange(git, newIo(), resolved.id, {
264
+ );
265
+ addSpecDirOption(startCmd);
266
+ startCmd.action(
267
+ (
268
+ id: string,
269
+ options: { branchPrefix?: string; base?: string; worktree?: boolean; directory?: string },
270
+ ) => {
271
+ const rctx = reRootContext(ctx, options.directory);
272
+ const resolved = resolveChangeIdOrExit(rctx, program, id);
273
+ const git = ctx.git;
274
+ const config = loadCliConfig(rctx.root);
275
+ const result = startChange(git, rctx.io, resolved.id, {
214
276
  branchPrefix: options.branchPrefix ?? config?.sdd?.branch_prefix ?? 'sdd/',
215
277
  base: options.base,
216
278
  worktree: options.worktree,
217
279
  worktreeRoot: config?.sdd?.worktree_root ?? undefined,
218
280
  worktreeNaming: config?.sdd?.worktree_naming ?? undefined,
281
+ // r119: the worktree redirect keeps the instance offset (sub-root
282
+ // start --worktree binds the SAME instance inside the new worktree).
283
+ instanceDirRel: instanceDirRelFor(rctx),
219
284
  });
220
285
  warnBaseBranchDeviation(git, result);
221
286
  console.log(
222
287
  `started change \`${resolved.id}\` → branch \`${result.branch}\` base \`${result.baseSha}\` base-branch \`${result.baseBranch}\``,
223
288
  );
224
289
  if (result.worktreePath !== undefined) console.log(`worktree ${result.worktreePath}`);
225
- });
290
+ },
291
+ );
226
292
 
227
- change
293
+ const attachCmd = change
228
294
  .command('attach')
229
295
  .description('Bind the change to the current feature branch')
230
296
  .argument('<id>')
@@ -232,11 +298,14 @@ export function registerChange(program: Command): void {
232
298
  .option(
233
299
  '--base <branch>',
234
300
  'explicit fork-point branch to record (must be an existing local branch)',
235
- )
236
- .action((id: string, options: { force?: boolean; base?: string }) => {
237
- const resolved = resolveChangeIdOrExit(program, id);
238
- const git = makeCliGit(process.cwd());
239
- const result = attachChange(git, newIo(), resolved.id, {
301
+ );
302
+ addSpecDirOption(attachCmd);
303
+ attachCmd.action(
304
+ (id: string, options: { force?: boolean; base?: string; directory?: string }) => {
305
+ const rctx = reRootContext(ctx, options.directory);
306
+ const resolved = resolveChangeIdOrExit(rctx, program, id);
307
+ const git = ctx.git;
308
+ const result = attachChange(git, rctx.io, resolved.id, {
240
309
  force: options.force,
241
310
  base: options.base,
242
311
  });
@@ -244,130 +313,164 @@ export function registerChange(program: Command): void {
244
313
  console.log(
245
314
  `attached change \`${resolved.id}\` → branch \`${result.branch}\` base \`${result.baseSha}\` base-branch \`${result.baseBranch}\``,
246
315
  );
247
- });
316
+ },
317
+ );
248
318
 
249
- change
319
+ const nextId = change
250
320
  .command('next-id')
251
- .description('Preview the next free change id number (read-only)')
252
- .option('--json', 'emit {maxNumber, nextNumber, warnings}')
253
- .action((options: { json?: boolean }) => {
254
- // r35: the scan covers this tree plus every linked git worktree's own
255
- // llmanspec/ tree (degrades to the current tree when worktree list fails).
256
- const harvest = harvestAcrossWorktrees(
257
- makeCliGit(process.cwd()),
258
- {
259
- listDir: (p) => readdirSync(resolve(p)),
260
- isDirectory: isDirectoryNoFollow,
261
- },
262
- 'llmanspec',
263
- );
264
- if (options.json) {
265
- console.log(JSON.stringify(harvest, null, 2));
266
- return;
267
- }
268
- if (harvest.maxNumber === null) console.log('no numbered change dirs found in tree');
269
- else console.log(`max number in tree: ${harvest.maxNumber}`);
270
- console.log(`next free number: ${harvest.nextNumber}`);
321
+ .description('Preview the next free change id number (read-only)');
322
+ addReportOutputOptions(nextId, { outputHint: 'json (r35 harvest payload); toon default' });
323
+ addSpecDirOption(nextId);
324
+ nextId.action(
325
+ (options: { json?: boolean; output?: string; compactJson?: boolean; directory?: string }) => {
326
+ // r35/r118: the scan covers the resolved instance tree plus every linked
327
+ // git worktree's own copy of it (degrades to the current tree when
328
+ // worktree list fails).
329
+ const rctx = reRootContext(ctx, options.directory);
330
+ const harvest = harvestForRoot(rctx);
331
+ // r35: the human face is exactly the two legacy lines (bare default and
332
+ // explicit `--output human`); machine modes render the harvest IR through
333
+ // the shared pipeline.
334
+ const human = (): string => {
335
+ const lines: string[] = [];
336
+ if (harvest.maxNumber === null) lines.push('no numbered change dirs found in tree');
337
+ else lines.push(`max number in tree: ${harvest.maxNumber}`);
338
+ lines.push(`next free number: ${harvest.nextNumber}`);
339
+ return lines.join('\n');
340
+ };
341
+ const bare =
342
+ options.output === undefined && options.json !== true && options.compactJson !== true;
343
+ if (bare) console.log(human());
344
+ else emitReport(harvest, options, human);
271
345
  for (const w of harvest.warnings) console.error(`warning: ${w}`);
272
- });
346
+ },
347
+ );
273
348
 
274
- change
349
+ const archiveCmd = change
275
350
  .command('archive')
276
- .description('Independent seal-off: task gates + merge + archive rename + commit')
351
+ .description(
352
+ 'Independent seal-off: task gates + merge + archive rename + commit (cold backup: `llman-sdd archive freeze`)',
353
+ )
277
354
  .argument('<id>')
278
355
  .option('--into <branch>', 'target branch to merge into')
279
356
  .option('--method <method>', 'merge method: squash | ff')
280
357
  .option('--dry-run', 'print the rename plan only')
281
- .addOption(new Option('--force', 'skip task and git gates').hideHelp())
282
- .action(
283
- (
284
- id: string,
285
- options: { into?: string; method?: string; dryRun?: boolean; force?: boolean },
286
- ) => {
287
- assertMergeMethod(options.method);
288
- const resolved = resolveChangeIdOrExit(program, id);
289
- id = resolved.id;
290
- const io = newIo();
291
- if (options.dryRun) {
292
- const date = new Date().toISOString().slice(0, 10);
293
- console.log(
294
- `Would move llmanspec/changes/${id} -> llmanspec/changes/archive/${date}-${id}`,
295
- );
296
- return;
297
- }
298
- // r40 task gate: single core implementation (archiveTaskGate); the
299
- // CLI only renders the blocked output + options list, byte-identical.
300
- if (!options.force) {
301
- const tasksPath = `llmanspec/changes/${id}/tasks.md`;
302
- const gate = archiveTaskGate(
303
- existsSync(tasksPath) ? readFileSync(tasksPath, 'utf8') : null,
304
- );
305
- if (gate.blocked) {
306
- console.error(`Archive blocked: ${gate.pendingLines.length} unchecked task(s).`);
307
- for (const line of gate.pendingLines) {
308
- console.error(` - [ ] ${line.replace(/^-\s+\[ \]\s*/u, '').trim()}`);
309
- }
310
- // D9: point at a close-out pseudo-task with the single shared hint.
311
- const closeOut = closeOutTaskLines(gate.pendingLines);
312
- if (closeOut.length > 0) {
313
- console.error(
314
- ` task "${closeOut[0]?.replace(/^-\s+\[ \]\s*/u, '').trim() ?? ''}" looks like a close-out step; ${CLOSE_OUT_TASK_HINT}`,
315
- );
316
- }
358
+ .addOption(new Option('--force', 'skip task and git gates').hideHelp());
359
+ addSpecDirOption(archiveCmd);
360
+ archiveCmd.action(
361
+ (
362
+ id: string,
363
+ options: {
364
+ into?: string;
365
+ method?: string;
366
+ dryRun?: boolean;
367
+ force?: boolean;
368
+ directory?: string;
369
+ },
370
+ ) => {
371
+ assertMergeMethod(options.method);
372
+ const rctx = reRootContext(ctx, options.directory);
373
+ const resolved = resolveChangeIdOrExit(rctx, program, id);
374
+ id = resolved.id;
375
+ const io = rctx.io;
376
+ if (options.dryRun) {
377
+ const date = new Date().toISOString().slice(0, 10);
378
+ console.log(
379
+ `Would move llmanspec/changes/${id} -> llmanspec/changes/archive/${date}-${id}`,
380
+ );
381
+ return;
382
+ }
383
+ // r40 task gate: single core implementation (archiveTaskGate); the
384
+ // CLI only renders the blocked output + options list, byte-identical.
385
+ if (!options.force) {
386
+ const tasksPath = `llmanspec/changes/${id}/tasks.md`;
387
+ const gate = archiveTaskGate(io.exists(tasksPath) ? io.readText(tasksPath) : null);
388
+ if (gate.blocked) {
389
+ console.error(`Archive blocked: ${gate.pendingLines.length} unchecked task(s).`);
390
+ for (const line of gate.pendingLines) {
391
+ console.error(` - [ ] ${line.replace(/^-\s+\[ \]\s*/u, '').trim()}`);
392
+ }
393
+ // D9: point at a close-out pseudo-task with the single shared hint.
394
+ const closeOut = closeOutTaskLines(gate.pendingLines);
395
+ if (closeOut.length > 0) {
317
396
  console.error(
318
- 'Options:\n 1. Complete the remaining tasks\n 2. Use --force to archive anyway (not recommended)',
397
+ ` task "${closeOut[0]?.replace(/^-\s+\[ \]\s*/u, '').trim() ?? ''}" looks like a close-out step; ${CLOSE_OUT_TASK_HINT}`,
319
398
  );
320
- throw new Error('archive blocked by unchecked tasks');
321
- }
322
- if (!isCleanTree(makeCliGit(process.cwd()))) {
323
- throw new CliError('`change archive` requires a clean working tree');
324
399
  }
400
+ console.error(
401
+ 'Options:\n 1. Complete the remaining tasks\n 2. Use --force to archive anyway (not recommended)',
402
+ );
403
+ throw new Error('archive blocked by unchecked tasks');
325
404
  }
326
- enforceCloseOutHarness(id, false);
327
- const result = archiveChange(makeCliGit(process.cwd()), io, id, {
328
- into: options.into,
329
- method: options.method as 'squash' | 'ff' | undefined,
330
- force: options.force,
331
- skipCleanTree: true,
332
- today: new Date().toISOString().slice(0, 10),
333
- });
334
- // node:path.basename — platform-aware (win32 backslashes would defeat
335
- // a hand-rolled lastIndexOf('/')).
336
- const archiveName = basename(result.archiveDir ?? '');
337
- console.log(`Change '${id}' archived as '${archiveName}'.`);
338
- if (result.executedIn !== null) {
339
- console.log(`executed in target worktree ${result.executedIn}`);
405
+ if (!isCleanTree(ctx.git)) {
406
+ throw new CliError('`change archive` requires a clean working tree');
340
407
  }
341
- },
342
- );
408
+ }
409
+ enforceCloseOutHarness(rctx, id, false);
410
+ const result = archiveChange(ctx.git, io, id, {
411
+ into: options.into,
412
+ method: options.method as 'squash' | 'ff' | undefined,
413
+ force: options.force,
414
+ skipCleanTree: true,
415
+ today: new Date().toISOString().slice(0, 10),
416
+ // r119: judge specs-landing under the change's own instance root.
417
+ specsPrefix: specsPrefixFor(rctx),
418
+ });
419
+ // node:path.basename — platform-aware (win32 backslashes would defeat
420
+ // a hand-rolled lastIndexOf('/')).
421
+ const archiveName = basename(result.archiveDir ?? '');
422
+ console.log(`Change '${id}' archived as '${archiveName}'.`);
423
+ if (result.executedIn !== null) {
424
+ console.log(`executed in target worktree ${result.executedIn}`);
425
+ }
426
+ },
427
+ );
343
428
 
344
- change
429
+ const diffCmd = change
345
430
  .command('diff')
346
431
  .description('Print the bound branch diff vs base')
347
432
  .argument('<id>')
348
- .option('--json', 'emit {change, branch, base, commitCount}')
349
- .option('--export-patch <path>', 'write the diff to a file instead of stdout')
350
- .action((id: string, options: { json?: boolean; exportPatch?: string }) => {
351
- const resolved = resolveChangeIdOrExit(program, id);
433
+ .option('--export-patch <path>', 'write the diff to a file instead of stdout');
434
+ addReportOutputOptions(diffCmd, {
435
+ outputHint: 'json {change,branch,base,commitCount}; toon default',
436
+ });
437
+ addSpecDirOption(diffCmd);
438
+ diffCmd.action(
439
+ (
440
+ id: string,
441
+ options: {
442
+ json?: boolean;
443
+ output?: string;
444
+ compactJson?: boolean;
445
+ exportPatch?: string;
446
+ directory?: string;
447
+ },
448
+ ) => {
449
+ const rctx = reRootContext(ctx, options.directory);
450
+ const resolved = resolveChangeIdOrExit(rctx, program, id);
352
451
  id = resolved.id;
353
- const git = makeCliGit(process.cwd());
354
- if (options.json) {
355
- const info = changeDiffInfo(git, newIo(), id);
356
- console.log(JSON.stringify(info, null, 2));
357
- return;
358
- }
359
- const diff = changeDiff(git, newIo(), id);
452
+ const git = ctx.git;
453
+ const diff = changeDiff(git, rctx.io, id);
360
454
  if (options.exportPatch !== undefined) {
361
455
  // writeText creates parent dirs — exporting into a fresh path like
362
- // out/change.patch must not ENOENT.
363
- newIo().writeText(options.exportPatch, diff);
456
+ // out/change.patch must not ENOENT. Export wins over any output mode.
457
+ // r116 exemption: the export path is a user-supplied argument and keeps
458
+ // its cwd-literal meaning.
459
+ ctx.io.writeText(options.exportPatch, diff);
364
460
  console.log(`wrote ${options.exportPatch}`);
365
461
  return;
366
462
  }
367
- console.log(diff);
368
- });
463
+ if (resolveOutMode(options.output, options.json, options.compactJson) !== 'human') {
464
+ emitReport(changeDiffInfo(git, rctx.io, id), options);
465
+ return;
466
+ }
467
+ // T37: an empty diff says so instead of printing nothing.
468
+ if (diff.trim() === '') console.log('no differences against the base (empty diff)');
469
+ else console.log(diff);
470
+ },
471
+ );
369
472
 
370
- change
473
+ const finalizeCmd = change
371
474
  .command('finalize')
372
475
  .description('Validate, merge the feature branch, archive docs, close out with one commit')
373
476
  .argument('<id>')
@@ -377,48 +480,56 @@ export function registerChange(program: Command): void {
377
480
  'merge method: squash | ff (default: sdd.merge_method config, then squash)',
378
481
  )
379
482
  .option('--no-check', 'skip the pre-merge validation sweep')
380
- .option('--no-commit', 'skip the close-out commit (manual/CI history)')
381
- .action(
382
- (
383
- id: string,
384
- options: { into?: string; method?: string; check?: boolean; commit?: boolean },
385
- ) => {
386
- assertMergeMethod(options.method);
387
- if (options.check !== false) {
388
- const failed = runValidateSweep();
389
- if (failed) {
390
- throw new CliError(
391
- 'finalize aborted: validation sweep failed (use --no-check to skip)',
392
- );
393
- }
394
- }
395
- const resolved = resolveChangeIdOrExit(program, id);
396
- id = resolved.id;
397
- enforceCloseOutHarness(id, options.check === false);
398
- const config = loadCliConfig();
399
- const method = options.method ?? config?.sdd?.merge_method ?? 'squash';
400
- const result = finalizeChange(makeCliGit(process.cwd()), newIo(), id, {
401
- into: options.into,
402
- method: method as 'squash' | 'ff',
403
- today: new Date().toISOString().slice(0, 10),
404
- noCommit: options.commit === false,
405
- });
406
- for (const w of result.warnings) console.error(`[WARNING] ${w}`);
407
- if (options.commit === false) {
408
- console.log(
409
- `finalized \`${id}\` → ${result.archiveDir} on ${result.target} (close-out commit skipped — run: git add -A && git commit -m "archive(sdd): ${id}")`,
410
- );
411
- if (result.executedIn !== null) {
412
- console.log(`executed in target worktree ${result.executedIn}`);
413
- }
414
- return;
483
+ .option('--no-commit', 'skip the close-out commit (manual/CI history)');
484
+ addSpecDirOption(finalizeCmd);
485
+ finalizeCmd.action(
486
+ (
487
+ id: string,
488
+ options: {
489
+ into?: string;
490
+ method?: string;
491
+ check?: boolean;
492
+ commit?: boolean;
493
+ directory?: string;
494
+ },
495
+ ) => {
496
+ assertMergeMethod(options.method);
497
+ const rctx = reRootContext(ctx, options.directory);
498
+ if (options.check !== false) {
499
+ const failed = runValidateSweep(rctx);
500
+ if (failed) {
501
+ throw new CliError('finalize aborted: validation sweep failed (use --no-check to skip)');
415
502
  }
503
+ }
504
+ const resolved = resolveChangeIdOrExit(rctx, program, id);
505
+ id = resolved.id;
506
+ enforceCloseOutHarness(rctx, id, options.check === false);
507
+ const config = loadCliConfig(rctx.root);
508
+ const method = options.method ?? config?.sdd?.merge_method ?? 'squash';
509
+ const result = finalizeChange(ctx.git, rctx.io, id, {
510
+ into: options.into,
511
+ method: method as 'squash' | 'ff',
512
+ today: new Date().toISOString().slice(0, 10),
513
+ noCommit: options.commit === false,
514
+ // r119: judge specs-landing under the change's own instance root.
515
+ specsPrefix: specsPrefixFor(rctx),
516
+ });
517
+ for (const w of result.warnings) console.error(`[WARNING] ${w}`);
518
+ if (options.commit === false) {
416
519
  console.log(
417
- `finalized \`${id}\` → ${result.archiveDir} (commit "${result.commitSubject}" on ${result.target})`,
520
+ `finalized \`${id}\` → ${result.archiveDir} on ${result.target} (close-out commit skipped — run: git add -A && git commit -m "archive(sdd): ${id}")`,
418
521
  );
419
522
  if (result.executedIn !== null) {
420
523
  console.log(`executed in target worktree ${result.executedIn}`);
421
524
  }
422
- },
423
- );
525
+ return;
526
+ }
527
+ console.log(
528
+ `finalized \`${id}\` → ${result.archiveDir} (commit "${result.commitSubject}" on ${result.target})`,
529
+ );
530
+ if (result.executedIn !== null) {
531
+ console.log(`executed in target worktree ${result.executedIn}`);
532
+ }
533
+ },
534
+ );
424
535
  }