docrev 0.9.13 → 0.9.14

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