docrev 0.11.1 → 0.11.3

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