docrev 0.6.7 → 0.7.6

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.
@@ -0,0 +1,922 @@
1
+ /**
2
+ * Comment commands: comments, resolve, next, prev, first, last, todo, accept, reject, reply
3
+ *
4
+ * Commands for viewing, navigating, and managing reviewer comments and track changes.
5
+ */
6
+
7
+ import {
8
+ chalk,
9
+ fs,
10
+ path,
11
+ fmt,
12
+ jsonMode,
13
+ jsonOutput,
14
+ findFiles,
15
+ getComments,
16
+ setCommentStatus,
17
+ getTrackChanges,
18
+ applyDecision,
19
+ interactiveCommentReview,
20
+ tuiCommentReview,
21
+ getUserName,
22
+ exitWithError,
23
+ getAnnotationSuggestions,
24
+ requireFile,
25
+ } from './context.js';
26
+
27
+ /**
28
+ * Add a reply after a comment
29
+ * @param {string} text - Full document text
30
+ * @param {object} comment - Comment object with position and match
31
+ * @param {string} author - Reply author name
32
+ * @param {string} message - Reply message
33
+ * @returns {string} Updated text
34
+ */
35
+ function addReply(text, comment, author, message) {
36
+ const replyAnnotation = `{>>${author}: ${message}<<}`;
37
+ const insertPos = comment.position + comment.match.length;
38
+ return text.slice(0, insertPos) + ' ' + replyAnnotation + text.slice(insertPos);
39
+ }
40
+
41
+ /**
42
+ * Helper to find section file by name (deterministic priority)
43
+ */
44
+ function findSectionFile(section) {
45
+ const allMd = findFiles('.md');
46
+ const sectionLower = section.toLowerCase();
47
+
48
+ // 1. Exact filename match
49
+ const exactFile = allMd.find(f => f === section || f === `${section}.md`);
50
+ if (exactFile) return [exactFile];
51
+
52
+ // 2. Filename contains (partial match)
53
+ const filenameMatch = allMd.filter(f =>
54
+ f.toLowerCase().replace(/\.md$/, '').includes(sectionLower)
55
+ );
56
+ if (filenameMatch.length === 1) return filenameMatch;
57
+ if (filenameMatch.length > 1) {
58
+ console.log(chalk.yellow(` Multiple files match "${section}": ${filenameMatch.join(', ')}`));
59
+ console.log(chalk.dim(` Using first match: ${filenameMatch[0]}`));
60
+ return [filenameMatch[0]];
61
+ }
62
+
63
+ // 3. Exact header match
64
+ for (const f of allMd) {
65
+ try {
66
+ const text = fs.readFileSync(f, 'utf-8');
67
+ const headerMatch = text.match(/^#\s+(.+)$/m);
68
+ if (headerMatch && headerMatch[1].toLowerCase().trim() === sectionLower) {
69
+ return [f];
70
+ }
71
+ } catch (e) {}
72
+ }
73
+
74
+ // 4. Header contains (partial match)
75
+ const headerMatches = [];
76
+ for (const f of allMd) {
77
+ try {
78
+ const text = fs.readFileSync(f, 'utf-8');
79
+ const headerMatch = text.match(/^#\s+(.+)$/m);
80
+ if (headerMatch && headerMatch[1].toLowerCase().includes(sectionLower)) {
81
+ headerMatches.push(f);
82
+ }
83
+ } catch (e) {}
84
+ }
85
+ if (headerMatches.length === 1) return headerMatches;
86
+ if (headerMatches.length > 1) {
87
+ console.log(chalk.yellow(` Multiple files match "${section}": ${headerMatches.join(', ')}`));
88
+ console.log(chalk.dim(` Using first match: ${headerMatches[0]}`));
89
+ return [headerMatches[0]];
90
+ }
91
+
92
+ // No match - return original (will fail later with file not found)
93
+ return [section];
94
+ }
95
+
96
+ /**
97
+ * Register comment commands with the program
98
+ * @param {import('commander').Command} program
99
+ */
100
+ export function register(program) {
101
+ // ==========================================================================
102
+ // COMMENTS command - List all comments
103
+ // ==========================================================================
104
+
105
+ program
106
+ .command('comments')
107
+ .alias('c')
108
+ .description('List all comments in the document')
109
+ .argument('<file>', 'Markdown file')
110
+ .option('-p, --pending', 'Show only pending (unresolved) comments')
111
+ .option('-r, --resolved', 'Show only resolved comments')
112
+ .option('-a, --author <name>', 'Filter by author name (case-insensitive)')
113
+ .option('-e, --export <csvFile>', 'Export comments to CSV file')
114
+ .option('-i, --interactive', 'Interactive review mode (reply, resolve, skip)')
115
+ .option('-t, --tui', 'Visual TUI mode for comment review')
116
+ .action(async (file, options) => {
117
+ requireFile(file, 'Markdown file');
118
+
119
+ const text = fs.readFileSync(file, 'utf-8');
120
+
121
+ // TUI review mode
122
+ if (options.tui) {
123
+ let author = options.author || getUserName();
124
+ if (!author) {
125
+ exitWithError('No user name set for replies', getAnnotationSuggestions('no_author'));
126
+ }
127
+
128
+ const result = await tuiCommentReview(text, {
129
+ author,
130
+ addReply: (txt, comment, auth, msg) => {
131
+ const replyAnnotation = `{>>${auth}: ${msg}<<}`;
132
+ const insertPos = comment.position + comment.match.length;
133
+ return txt.slice(0, insertPos) + ' ' + replyAnnotation + txt.slice(insertPos);
134
+ },
135
+ setStatus: setCommentStatus,
136
+ });
137
+
138
+ if (result.resolved > 0 || result.replied > 0) {
139
+ fs.writeFileSync(file, result.text, 'utf-8');
140
+ console.log(fmt.status('success', `Changes saved to ${file}`));
141
+ }
142
+ return;
143
+ }
144
+
145
+ // Interactive review mode
146
+ if (options.interactive) {
147
+ let author = options.author || getUserName();
148
+ if (!author) {
149
+ exitWithError('No user name set for replies', getAnnotationSuggestions('no_author'));
150
+ }
151
+
152
+ const result = await interactiveCommentReview(text, {
153
+ author,
154
+ addReply: (txt, comment, auth, msg) => {
155
+ const replyAnnotation = `{>>${auth}: ${msg}<<}`;
156
+ const insertPos = comment.position + comment.match.length;
157
+ return txt.slice(0, insertPos) + ' ' + replyAnnotation + txt.slice(insertPos);
158
+ },
159
+ setCommentStatus,
160
+ });
161
+
162
+ if (result.resolved > 0 || result.replied > 0) {
163
+ fs.writeFileSync(file, result.text, 'utf-8');
164
+ console.log(fmt.status('success', `Changes saved to ${file}`));
165
+ }
166
+ return;
167
+ }
168
+
169
+ let comments = getComments(text, {
170
+ pendingOnly: options.pending,
171
+ resolvedOnly: options.resolved,
172
+ });
173
+
174
+ // Filter by author if specified
175
+ if (options.author) {
176
+ const authorFilter = options.author.toLowerCase();
177
+ comments = comments.filter(c =>
178
+ c.author && c.author.toLowerCase().includes(authorFilter)
179
+ );
180
+ }
181
+
182
+ // CSV export mode
183
+ if (options.export) {
184
+ const csvEscape = (str) => {
185
+ if (!str) return '';
186
+ str = String(str);
187
+ if (str.includes(',') || str.includes('"') || str.includes('\n')) {
188
+ return '"' + str.replace(/"/g, '""') + '"';
189
+ }
190
+ return str;
191
+ };
192
+
193
+ const header = ['number', 'author', 'comment', 'context', 'status', 'file', 'line'];
194
+ const rows = comments.map((c, i) => [
195
+ i + 1,
196
+ csvEscape(c.author || ''),
197
+ csvEscape(c.content),
198
+ csvEscape(c.before ? c.before.trim() : ''),
199
+ c.resolved ? 'resolved' : 'pending',
200
+ path.basename(file),
201
+ c.line,
202
+ ].join(','));
203
+
204
+ const csv = [header.join(','), ...rows].join('\n');
205
+ fs.writeFileSync(options.export, csv, 'utf-8');
206
+ console.log(fmt.status('success', `Exported ${comments.length} comments to ${options.export}`));
207
+ return;
208
+ }
209
+
210
+ if (comments.length === 0) {
211
+ if (options.pending) {
212
+ console.log(fmt.status('success', 'No pending comments'));
213
+ } else if (options.resolved) {
214
+ console.log(fmt.status('info', 'No resolved comments'));
215
+ } else {
216
+ console.log(fmt.status('info', 'No comments found'));
217
+ }
218
+ return;
219
+ }
220
+
221
+ let filter = options.pending ? ' (pending)' : options.resolved ? ' (resolved)' : '';
222
+ if (options.author) filter += ` by "${options.author}"`;
223
+ console.log(fmt.header(`Comments in ${path.basename(file)}${filter}`));
224
+ console.log();
225
+
226
+ for (let i = 0; i < comments.length; i++) {
227
+ const c = comments[i];
228
+ const statusIcon = c.resolved ? chalk.green('✓') : chalk.yellow('○');
229
+ const authorLabel = c.author ? chalk.blue(`[${c.author}]`) : chalk.dim('[Anonymous]');
230
+ const preview = c.content.length > 60 ? c.content.slice(0, 60) + '...' : c.content;
231
+
232
+ console.log(` ${chalk.bold(`#${i + 1}`)} ${statusIcon} ${authorLabel} ${chalk.dim(`L${c.line}`)}`);
233
+ console.log(` ${preview}`);
234
+ if (c.before) {
235
+ console.log(chalk.dim(` "${c.before.trim().slice(-40)}..."`));
236
+ }
237
+ console.log();
238
+ }
239
+
240
+ // Summary
241
+ const allComments = getComments(text);
242
+ const pending = allComments.filter((c) => !c.resolved).length;
243
+ const resolved = allComments.filter((c) => c.resolved).length;
244
+ console.log(chalk.dim(` Total: ${allComments.length} | Pending: ${pending} | Resolved: ${resolved}`));
245
+ });
246
+
247
+ // ==========================================================================
248
+ // RESOLVE command - Mark comments as resolved/pending
249
+ // ==========================================================================
250
+
251
+ program
252
+ .command('resolve')
253
+ .alias('r')
254
+ .description('Mark comments as resolved or pending')
255
+ .argument('<file>', 'Markdown file')
256
+ .option('-n, --number <n>', 'Comment number to toggle', parseInt)
257
+ .option('-a, --all', 'Mark all comments as resolved')
258
+ .option('-u, --unresolve', 'Mark as pending (unresolve)')
259
+ .option('--dry-run', 'Preview without saving')
260
+ .action((file, options) => {
261
+ requireFile(file, 'Markdown file');
262
+
263
+ let text = fs.readFileSync(file, 'utf-8');
264
+ const comments = getComments(text);
265
+
266
+ if (comments.length === 0) {
267
+ console.log(fmt.status('info', 'No comments found'));
268
+ console.log(chalk.dim(getAnnotationSuggestions('no_comments').join('\n ')));
269
+ return;
270
+ }
271
+
272
+ const resolveStatus = !options.unresolve;
273
+
274
+ if (options.all) {
275
+ // Mark all comments
276
+ let count = 0;
277
+ for (const comment of comments) {
278
+ if (comment.resolved !== resolveStatus) {
279
+ text = setCommentStatus(text, comment, resolveStatus);
280
+ count++;
281
+ }
282
+ }
283
+ if (options.dryRun) {
284
+ console.log(fmt.status('info', `Would mark ${count} comment(s) as ${resolveStatus ? 'resolved' : 'pending'}`));
285
+ } else {
286
+ fs.writeFileSync(file, text, 'utf-8');
287
+ console.log(fmt.status('success', `Marked ${count} comment(s) as ${resolveStatus ? 'resolved' : 'pending'}`));
288
+ }
289
+ return;
290
+ }
291
+
292
+ if (options.number !== undefined) {
293
+ const idx = options.number - 1;
294
+ if (idx < 0 || idx >= comments.length) {
295
+ exitWithError(
296
+ `Invalid comment number ${options.number}. File has ${comments.length} comment(s)`,
297
+ getAnnotationSuggestions('invalid_number')
298
+ );
299
+ }
300
+ const comment = comments[idx];
301
+ text = setCommentStatus(text, comment, resolveStatus);
302
+ if (options.dryRun) {
303
+ console.log(fmt.status('info', `Would mark comment #${options.number} as ${resolveStatus ? 'resolved' : 'pending'}`));
304
+ } else {
305
+ fs.writeFileSync(file, text, 'utf-8');
306
+ console.log(fmt.status('success', `Comment #${options.number} marked as ${resolveStatus ? 'resolved' : 'pending'}`));
307
+ }
308
+ return;
309
+ }
310
+
311
+ // No options: show current status
312
+ console.log(fmt.header(`Comment Status in ${path.basename(file)}`));
313
+ console.log();
314
+
315
+ for (let i = 0; i < comments.length; i++) {
316
+ const c = comments[i];
317
+ const statusIcon = c.resolved ? chalk.green('✓') : chalk.yellow('○');
318
+ const preview = c.content.length > 50 ? c.content.slice(0, 50) + '...' : c.content;
319
+ console.log(` ${statusIcon} #${i + 1} ${preview}`);
320
+ }
321
+
322
+ console.log();
323
+ const pending = comments.filter((c) => !c.resolved).length;
324
+ const resolved = comments.filter((c) => c.resolved).length;
325
+ console.log(chalk.dim(` Pending: ${pending} | Resolved: ${resolved}`));
326
+ console.log();
327
+ console.log(chalk.dim(' Usage: rev resolve <file> -n <number> Mark specific comment'));
328
+ console.log(chalk.dim(' rev resolve <file> -a Mark all as resolved'));
329
+ console.log(chalk.dim(' rev resolve <file> -n 1 -u Unresolve comment #1'));
330
+ });
331
+
332
+ // ==========================================================================
333
+ // NEXT command - Show next pending comment
334
+ // ==========================================================================
335
+
336
+ program
337
+ .command('next')
338
+ .alias('n')
339
+ .description('Show next pending comment')
340
+ .argument('[file]', 'Specific file (default: all markdown files)')
341
+ .option('-n, --number <n>', 'Skip to nth pending comment', parseInt)
342
+ .action((file, options) => {
343
+ const files = file ? [file] : findFiles('.md');
344
+
345
+ if (files.length === 0) {
346
+ console.log(fmt.status('info', 'No markdown files found.'));
347
+ return;
348
+ }
349
+
350
+ // Collect all pending comments across files
351
+ const allPending = [];
352
+ for (const f of files) {
353
+ if (!fs.existsSync(f)) continue;
354
+ const text = fs.readFileSync(f, 'utf-8');
355
+ const allComments = getComments(text);
356
+ const pending = getComments(text, { pendingOnly: true });
357
+
358
+ for (const c of pending) {
359
+ const idx = allComments.findIndex(x => x.position === c.position) + 1;
360
+ allPending.push({ ...c, file: f, number: idx });
361
+ }
362
+ }
363
+
364
+ if (allPending.length === 0) {
365
+ console.log(fmt.status('success', 'No pending comments!'));
366
+ return;
367
+ }
368
+
369
+ // Get the nth pending comment (default: 1st)
370
+ const targetIdx = (options.number || 1) - 1;
371
+ if (targetIdx < 0 || targetIdx >= allPending.length) {
372
+ console.error(chalk.red(`Invalid number. Only ${allPending.length} pending comment(s).`));
373
+ process.exit(1);
374
+ }
375
+
376
+ const c = allPending[targetIdx];
377
+ const position = targetIdx + 1;
378
+
379
+ console.log(fmt.header(`Comment ${position}/${allPending.length}`));
380
+ console.log();
381
+ console.log(` ${chalk.cyan(c.file)}:${c.line} ${chalk.dim(`#${c.number}`)}`);
382
+ console.log();
383
+ if (c.author) console.log(` ${chalk.blue(c.author)}`);
384
+ console.log(` ${c.content}`);
385
+ if (c.before) {
386
+ console.log();
387
+ console.log(chalk.dim(` Context: "${c.before.trim().slice(-60)}"`));
388
+ }
389
+ console.log();
390
+ console.log(chalk.dim(` rev reply ${c.file} -n ${c.number} -m "..."`));
391
+ console.log(chalk.dim(` rev resolve ${c.file} -n ${c.number}`));
392
+ if (position < allPending.length) {
393
+ console.log(chalk.dim(` rev next -n ${position + 1}`));
394
+ }
395
+ });
396
+
397
+ // ==========================================================================
398
+ // PREV command - Show previous/last pending comment
399
+ // ==========================================================================
400
+
401
+ program
402
+ .command('prev')
403
+ .alias('p')
404
+ .description('Show previous pending comment')
405
+ .argument('[file]', 'Specific file (default: all markdown files)')
406
+ .option('-n, --number <n>', 'Skip to nth pending comment from end', parseInt)
407
+ .action((file, options) => {
408
+ const files = file ? [file] : findFiles('.md');
409
+
410
+ if (files.length === 0) {
411
+ console.log(fmt.status('info', 'No markdown files found.'));
412
+ return;
413
+ }
414
+
415
+ // Collect all pending comments across files
416
+ const allPending = [];
417
+ for (const f of files) {
418
+ if (!fs.existsSync(f)) continue;
419
+ const text = fs.readFileSync(f, 'utf-8');
420
+ const allComments = getComments(text);
421
+ const pending = getComments(text, { pendingOnly: true });
422
+
423
+ for (const c of pending) {
424
+ const idx = allComments.findIndex(x => x.position === c.position) + 1;
425
+ allPending.push({ ...c, file: f, number: idx });
426
+ }
427
+ }
428
+
429
+ if (allPending.length === 0) {
430
+ console.log(fmt.status('success', 'No pending comments!'));
431
+ return;
432
+ }
433
+
434
+ // Get the nth pending comment from end (default: last)
435
+ const fromEnd = options.number || 1;
436
+ const targetIdx = allPending.length - fromEnd;
437
+ if (targetIdx < 0 || targetIdx >= allPending.length) {
438
+ console.error(chalk.red(`Invalid number. Only ${allPending.length} pending comment(s).`));
439
+ process.exit(1);
440
+ }
441
+
442
+ const c = allPending[targetIdx];
443
+ const position = targetIdx + 1;
444
+
445
+ console.log(fmt.header(`Comment ${position}/${allPending.length}`));
446
+ console.log();
447
+ console.log(` ${chalk.cyan(c.file)}:${c.line} ${chalk.dim(`#${c.number}`)}`);
448
+ console.log();
449
+ if (c.author) console.log(` ${chalk.blue(c.author)}`);
450
+ console.log(` ${c.content}`);
451
+ if (c.before) {
452
+ console.log();
453
+ console.log(chalk.dim(` Context: "${c.before.trim().slice(-60)}"`));
454
+ }
455
+ console.log();
456
+ console.log(chalk.dim(` rev reply ${c.file} -n ${c.number} -m "..."`));
457
+ console.log(chalk.dim(` rev resolve ${c.file} -n ${c.number}`));
458
+ if (position > 1) {
459
+ console.log(chalk.dim(` rev next -n ${position - 1}`));
460
+ }
461
+ if (position < allPending.length) {
462
+ console.log(chalk.dim(` rev next -n ${position + 1}`));
463
+ }
464
+ });
465
+
466
+ // ==========================================================================
467
+ // FIRST command - Show first comment
468
+ // ==========================================================================
469
+
470
+ program
471
+ .command('first')
472
+ .description('Show first comment')
473
+ .argument('[section]', 'Specific file or section name (default: all markdown files)')
474
+ .action((section) => {
475
+ const files = section ? findSectionFile(section) : findFiles('.md');
476
+
477
+ if (files.length === 0) {
478
+ console.log(fmt.status('info', 'No markdown files found.'));
479
+ return;
480
+ }
481
+
482
+ // Find first comment across files
483
+ for (const f of files) {
484
+ if (!fs.existsSync(f)) continue;
485
+ const text = fs.readFileSync(f, 'utf-8');
486
+ const comments = getComments(text);
487
+
488
+ if (comments.length > 0) {
489
+ const c = comments[0];
490
+ const statusIcon = c.resolved ? chalk.green('✓') : chalk.yellow('○');
491
+
492
+ console.log(fmt.header(`Comment 1/${comments.length}`));
493
+ console.log();
494
+ console.log(` ${chalk.cyan(f)}:${c.line} #1 ${statusIcon}`);
495
+ console.log();
496
+ if (c.author) console.log(` ${chalk.blue(c.author)}`);
497
+ console.log(` ${c.content}`);
498
+ if (c.before) {
499
+ console.log();
500
+ console.log(chalk.dim(` Context: "${c.before.trim().slice(-60)}"`));
501
+ }
502
+ console.log();
503
+ console.log(chalk.dim(` rev reply ${f} -n 1 -m "..."`));
504
+ console.log(chalk.dim(` rev resolve ${f} -n 1`));
505
+ return;
506
+ }
507
+ }
508
+
509
+ console.log(fmt.status('info', 'No comments found.'));
510
+ });
511
+
512
+ // ==========================================================================
513
+ // LAST command - Show last comment
514
+ // ==========================================================================
515
+
516
+ program
517
+ .command('last')
518
+ .description('Show last comment')
519
+ .argument('[section]', 'Specific file or section name (default: all markdown files)')
520
+ .action((section) => {
521
+ const files = section ? findSectionFile(section) : findFiles('.md').reverse();
522
+
523
+ if (files.length === 0) {
524
+ console.log(fmt.status('info', 'No markdown files found.'));
525
+ return;
526
+ }
527
+
528
+ // Find last comment across files (reverse order)
529
+ for (const f of files) {
530
+ if (!fs.existsSync(f)) continue;
531
+ const text = fs.readFileSync(f, 'utf-8');
532
+ const comments = getComments(text);
533
+
534
+ if (comments.length > 0) {
535
+ const c = comments[comments.length - 1];
536
+ const idx = comments.length;
537
+ const statusIcon = c.resolved ? chalk.green('✓') : chalk.yellow('○');
538
+
539
+ console.log(fmt.header(`Comment ${idx}/${comments.length}`));
540
+ console.log();
541
+ console.log(` ${chalk.cyan(f)}:${c.line} #${idx} ${statusIcon}`);
542
+ console.log();
543
+ if (c.author) console.log(` ${chalk.blue(c.author)}`);
544
+ console.log(` ${c.content}`);
545
+ if (c.before) {
546
+ console.log();
547
+ console.log(chalk.dim(` Context: "${c.before.trim().slice(-60)}"`));
548
+ }
549
+ console.log();
550
+ console.log(chalk.dim(` rev reply ${f} -n ${idx} -m "..."`));
551
+ console.log(chalk.dim(` rev resolve ${f} -n ${idx}`));
552
+ return;
553
+ }
554
+ }
555
+
556
+ console.log(fmt.status('info', 'No comments found.'));
557
+ });
558
+
559
+ // ==========================================================================
560
+ // TODO command - List pending comments as checklist
561
+ // ==========================================================================
562
+
563
+ program
564
+ .command('todo')
565
+ .alias('t')
566
+ .description('List all pending comments as a checklist')
567
+ .argument('[file]', 'Specific file (default: all markdown files)')
568
+ .option('--by-author', 'Group by author')
569
+ .action((file, options) => {
570
+ const files = file ? [file] : findFiles('.md');
571
+
572
+ if (files.length === 0) {
573
+ console.log(fmt.status('info', 'No markdown files found.'));
574
+ return;
575
+ }
576
+
577
+ // Collect all pending comments
578
+ const todos = [];
579
+ for (const f of files) {
580
+ if (!fs.existsSync(f)) continue;
581
+ const text = fs.readFileSync(f, 'utf-8');
582
+ const allComments = getComments(text);
583
+ const pending = allComments.filter(c => !c.resolved);
584
+
585
+ for (const c of pending) {
586
+ const idx = allComments.findIndex(x => x.position === c.position) + 1;
587
+ todos.push({
588
+ file: f,
589
+ number: idx,
590
+ line: c.line,
591
+ author: c.author || 'Anonymous',
592
+ content: c.content,
593
+ });
594
+ }
595
+ }
596
+
597
+ if (todos.length === 0) {
598
+ console.log(fmt.status('success', 'No pending comments!'));
599
+ return;
600
+ }
601
+
602
+ console.log(fmt.header(`Todo (${todos.length} pending)`));
603
+ console.log();
604
+
605
+ if (options.byAuthor) {
606
+ // Group by author
607
+ const byAuthor = {};
608
+ for (const t of todos) {
609
+ if (!byAuthor[t.author]) byAuthor[t.author] = [];
610
+ byAuthor[t.author].push(t);
611
+ }
612
+
613
+ for (const [author, items] of Object.entries(byAuthor)) {
614
+ console.log(` ${chalk.blue(author)} (${items.length})`);
615
+ for (const t of items) {
616
+ const preview = t.content.length > 50 ? t.content.slice(0, 50) + '...' : t.content;
617
+ console.log(` ${chalk.yellow('○')} ${chalk.dim(`${t.file}:${t.line}`)} ${preview}`);
618
+ }
619
+ console.log();
620
+ }
621
+ } else {
622
+ // List by file
623
+ let currentFile = null;
624
+ for (const t of todos) {
625
+ if (t.file !== currentFile) {
626
+ if (currentFile) console.log();
627
+ console.log(` ${chalk.cyan(t.file)}`);
628
+ currentFile = t.file;
629
+ }
630
+ const preview = t.content.length > 50 ? t.content.slice(0, 50) + '...' : t.content;
631
+ const authorTag = t.author !== 'Anonymous' ? chalk.dim(`[${t.author}] `) : '';
632
+ console.log(` ${chalk.yellow('○')} #${t.number} ${authorTag}${preview}`);
633
+ }
634
+ }
635
+
636
+ console.log();
637
+ });
638
+
639
+ // ==========================================================================
640
+ // ACCEPT command - Accept track changes
641
+ // ==========================================================================
642
+
643
+ program
644
+ .command('accept')
645
+ .alias('a')
646
+ .description('Accept track changes')
647
+ .argument('<file>', 'Markdown file')
648
+ .option('-n, --number <n>', 'Accept specific change by number', parseInt)
649
+ .option('-a, --all', 'Accept all changes')
650
+ .option('--dry-run', 'Preview without saving')
651
+ .action((file, options) => {
652
+ if (!fs.existsSync(file)) {
653
+ console.error(chalk.red(`Error: File not found: ${file}`));
654
+ process.exit(1);
655
+ }
656
+
657
+ let text = fs.readFileSync(file, 'utf-8');
658
+ const changes = getTrackChanges(text);
659
+
660
+ if (changes.length === 0) {
661
+ console.log(fmt.status('info', 'No track changes found.'));
662
+ return;
663
+ }
664
+
665
+ if (options.all) {
666
+ // Accept all changes - process in reverse to preserve positions
667
+ const sorted = [...changes].sort((a, b) => b.position - a.position);
668
+ for (const change of sorted) {
669
+ text = applyDecision(text, change, true);
670
+ }
671
+ if (!options.dryRun) {
672
+ fs.writeFileSync(file, text, 'utf-8');
673
+ console.log(fmt.status('success', `Accepted ${changes.length} change(s)`));
674
+ } else {
675
+ console.log(fmt.status('info', `Would accept ${changes.length} change(s)`));
676
+ }
677
+ return;
678
+ }
679
+
680
+ if (options.number !== undefined) {
681
+ const idx = options.number - 1;
682
+ if (idx < 0 || idx >= changes.length) {
683
+ console.error(chalk.red(`Invalid change number. File has ${changes.length} changes.`));
684
+ process.exit(1);
685
+ }
686
+ const change = changes[idx];
687
+ text = applyDecision(text, change, true);
688
+ if (!options.dryRun) {
689
+ fs.writeFileSync(file, text, 'utf-8');
690
+ console.log(fmt.status('success', `Accepted change #${options.number}`));
691
+ } else {
692
+ console.log(fmt.status('info', `Would accept change #${options.number}`));
693
+ }
694
+ return;
695
+ }
696
+
697
+ // No options: show changes
698
+ console.log(fmt.header(`Track Changes in ${path.basename(file)}`));
699
+ console.log();
700
+
701
+ for (let i = 0; i < changes.length; i++) {
702
+ const c = changes[i];
703
+ let desc;
704
+ if (c.type === 'insert') {
705
+ desc = chalk.green(`+++ "${c.content.slice(0, 40)}${c.content.length > 40 ? '...' : ''}"`);
706
+ } else if (c.type === 'delete') {
707
+ desc = chalk.red(`--- "${c.content.slice(0, 40)}${c.content.length > 40 ? '...' : ''}"`);
708
+ } else if (c.type === 'substitute') {
709
+ desc = chalk.yellow(`~~~ "${c.content.slice(0, 20)}" → "${(c.replacement || '').slice(0, 20)}"`);
710
+ }
711
+ console.log(` #${i + 1} ${chalk.dim(`L${c.line}`)} ${desc}`);
712
+ }
713
+
714
+ console.log();
715
+ console.log(chalk.dim(` rev accept ${file} -n <number> Accept specific change`));
716
+ console.log(chalk.dim(` rev accept ${file} -a Accept all changes`));
717
+ });
718
+
719
+ // ==========================================================================
720
+ // REJECT command - Reject track changes
721
+ // ==========================================================================
722
+
723
+ program
724
+ .command('reject')
725
+ .alias('x')
726
+ .description('Reject track changes')
727
+ .argument('<file>', 'Markdown file')
728
+ .option('-n, --number <n>', 'Reject specific change by number', parseInt)
729
+ .option('-a, --all', 'Reject all changes')
730
+ .option('--dry-run', 'Preview without saving')
731
+ .action((file, options) => {
732
+ if (!fs.existsSync(file)) {
733
+ console.error(chalk.red(`Error: File not found: ${file}`));
734
+ process.exit(1);
735
+ }
736
+
737
+ let text = fs.readFileSync(file, 'utf-8');
738
+ const changes = getTrackChanges(text);
739
+
740
+ if (changes.length === 0) {
741
+ console.log(fmt.status('info', 'No track changes found.'));
742
+ return;
743
+ }
744
+
745
+ if (options.all) {
746
+ // Reject all changes - process in reverse to preserve positions
747
+ const sorted = [...changes].sort((a, b) => b.position - a.position);
748
+ for (const change of sorted) {
749
+ text = applyDecision(text, change, false);
750
+ }
751
+ if (!options.dryRun) {
752
+ fs.writeFileSync(file, text, 'utf-8');
753
+ console.log(fmt.status('success', `Rejected ${changes.length} change(s)`));
754
+ } else {
755
+ console.log(fmt.status('info', `Would reject ${changes.length} change(s)`));
756
+ }
757
+ return;
758
+ }
759
+
760
+ if (options.number !== undefined) {
761
+ const idx = options.number - 1;
762
+ if (idx < 0 || idx >= changes.length) {
763
+ console.error(chalk.red(`Invalid change number. File has ${changes.length} changes.`));
764
+ process.exit(1);
765
+ }
766
+ const change = changes[idx];
767
+ text = applyDecision(text, change, false);
768
+ if (!options.dryRun) {
769
+ fs.writeFileSync(file, text, 'utf-8');
770
+ console.log(fmt.status('success', `Rejected change #${options.number}`));
771
+ } else {
772
+ console.log(fmt.status('info', `Would reject change #${options.number}`));
773
+ }
774
+ return;
775
+ }
776
+
777
+ // No options: show changes (same as accept)
778
+ console.log(fmt.header(`Track Changes in ${path.basename(file)}`));
779
+ console.log();
780
+
781
+ for (let i = 0; i < changes.length; i++) {
782
+ const c = changes[i];
783
+ let desc;
784
+ if (c.type === 'insert') {
785
+ desc = chalk.green(`+++ "${c.content.slice(0, 40)}${c.content.length > 40 ? '...' : ''}"`);
786
+ } else if (c.type === 'delete') {
787
+ desc = chalk.red(`--- "${c.content.slice(0, 40)}${c.content.length > 40 ? '...' : ''}"`);
788
+ } else if (c.type === 'substitute') {
789
+ desc = chalk.yellow(`~~~ "${c.content.slice(0, 20)}" → "${(c.replacement || '').slice(0, 20)}"`);
790
+ }
791
+ console.log(` #${i + 1} ${chalk.dim(`L${c.line}`)} ${desc}`);
792
+ }
793
+
794
+ console.log();
795
+ console.log(chalk.dim(` rev reject ${file} -n <number> Reject specific change`));
796
+ console.log(chalk.dim(` rev reject ${file} -a Reject all changes`));
797
+ });
798
+
799
+ // ==========================================================================
800
+ // REPLY command - Reply to comments
801
+ // ==========================================================================
802
+
803
+ program
804
+ .command('reply')
805
+ .description('Reply to reviewer comments interactively')
806
+ .argument('<file>', 'Markdown file with comments')
807
+ .option('-m, --message <text>', 'Reply message (non-interactive)')
808
+ .option('-n, --number <n>', 'Reply to specific comment number', parseInt)
809
+ .option('-a, --author <name>', 'Override author name')
810
+ .option('--all', 'Reply to all pending comments with the same message (requires -m)')
811
+ .option('--dry-run', 'Preview without saving')
812
+ .action(async (file, options) => {
813
+ if (!fs.existsSync(file)) {
814
+ console.error(chalk.red(`File not found: ${file}`));
815
+ process.exit(1);
816
+ }
817
+
818
+ // Get author name
819
+ let author = options.author || getUserName();
820
+ if (!author) {
821
+ console.error(chalk.yellow('No user name set.'));
822
+ console.error(chalk.dim('Set with: rev config user "Your Name"'));
823
+ console.error(chalk.dim('Or use: rev reply <file> --author "Your Name"'));
824
+ process.exit(1);
825
+ }
826
+
827
+ const text = fs.readFileSync(file, 'utf-8');
828
+ const comments = getComments(text, { pendingOnly: true });
829
+
830
+ if (comments.length === 0) {
831
+ console.log(chalk.green('No pending comments found in this file.'));
832
+ return;
833
+ }
834
+
835
+ // Batch reply mode: reply to all pending comments
836
+ if (options.all) {
837
+ if (!options.message) {
838
+ console.error(chalk.red('Batch reply requires a message (-m "your reply")'));
839
+ console.error(chalk.dim('Example: rev reply file.md --all -m "Addressed"'));
840
+ process.exit(1);
841
+ }
842
+ let result = text;
843
+ let count = 0;
844
+ // Process in reverse order to maintain positions
845
+ const sortedComments = [...comments].sort((a, b) => b.position - a.position);
846
+ for (const comment of sortedComments) {
847
+ result = addReply(result, comment, author, options.message);
848
+ count++;
849
+ }
850
+ if (options.dryRun) {
851
+ console.log(fmt.status('info', `Would add reply to ${count} pending comment(s)`));
852
+ } else {
853
+ fs.writeFileSync(file, result, 'utf-8');
854
+ console.log(chalk.green(`Reply added to ${count} pending comment(s)`));
855
+ }
856
+ return;
857
+ }
858
+
859
+ // Non-interactive mode: reply to specific comment
860
+ if (options.message && options.number !== undefined) {
861
+ const allComments = getComments(text); // Get all comments for numbering
862
+ const idx = options.number - 1;
863
+ if (idx < 0 || idx >= allComments.length) {
864
+ console.error(chalk.red(`Invalid comment number. File has ${allComments.length} comments.`));
865
+ process.exit(1);
866
+ }
867
+ const result = addReply(text, allComments[idx], author, options.message);
868
+ if (options.dryRun) {
869
+ console.log(fmt.status('info', `Would add reply to comment #${options.number}`));
870
+ } else {
871
+ fs.writeFileSync(file, result, 'utf-8');
872
+ console.log(chalk.green(`Reply added to comment #${options.number}`));
873
+ }
874
+ return;
875
+ }
876
+
877
+ // Interactive mode
878
+ console.log(chalk.cyan(`\nComments in ${path.basename(file)} (replying as ${chalk.bold(author)}):\n`));
879
+
880
+ const rl = (await import('readline')).createInterface({
881
+ input: process.stdin,
882
+ output: process.stdout,
883
+ });
884
+
885
+ const askQuestion = (prompt) =>
886
+ new Promise((resolve) => rl.question(prompt, resolve));
887
+
888
+ let result = text;
889
+ let repliesAdded = 0;
890
+
891
+ for (let i = 0; i < comments.length; i++) {
892
+ const c = comments[i];
893
+ const authorLabel = c.author ? chalk.blue(`[${c.author}]`) : chalk.dim('[Anonymous]');
894
+ const preview = c.content.length > 100 ? c.content.slice(0, 100) + '...' : c.content;
895
+
896
+ console.log(`\n${chalk.bold(`#${i + 1}`)} ${authorLabel}`);
897
+ console.log(chalk.dim(` Line ${c.line}: "${c.before?.trim().slice(-30) || ''}..."`));
898
+ console.log(` ${preview}`);
899
+
900
+ const answer = await askQuestion(chalk.cyan('\n Reply (or Enter to skip, q to quit): '));
901
+
902
+ if (answer.toLowerCase() === 'q') {
903
+ break;
904
+ }
905
+
906
+ if (answer.trim()) {
907
+ result = addReply(result, c, author, answer.trim());
908
+ repliesAdded++;
909
+ console.log(chalk.green(' ✓ Reply added'));
910
+ }
911
+ }
912
+
913
+ rl.close();
914
+
915
+ if (repliesAdded > 0) {
916
+ fs.writeFileSync(file, result, 'utf-8');
917
+ console.log(chalk.green(`\nAdded ${repliesAdded} reply(ies) to ${file}`));
918
+ } else {
919
+ console.log(chalk.dim('\nNo replies added.'));
920
+ }
921
+ });
922
+ }