docrev 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +184 -173
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  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/anchor-match.d.ts +4 -2
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +52 -24
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/annotations.d.ts +0 -6
  15. package/dist/lib/annotations.d.ts.map +1 -1
  16. package/dist/lib/annotations.js +26 -8
  17. package/dist/lib/annotations.js.map +1 -1
  18. package/dist/lib/build.d.ts.map +1 -1
  19. package/dist/lib/build.js +13 -10
  20. package/dist/lib/build.js.map +1 -1
  21. package/dist/lib/commands/build.d.ts.map +1 -1
  22. package/dist/lib/commands/build.js +5 -0
  23. package/dist/lib/commands/build.js.map +1 -1
  24. package/dist/lib/commands/doi.d.ts.map +1 -1
  25. package/dist/lib/commands/doi.js +14 -2
  26. package/dist/lib/commands/doi.js.map +1 -1
  27. package/dist/lib/commands/sync.d.ts.map +1 -1
  28. package/dist/lib/commands/sync.js +98 -107
  29. package/dist/lib/commands/sync.js.map +1 -1
  30. package/dist/lib/commands/utilities.js +164 -164
  31. package/dist/lib/commands/word-tools.js +8 -8
  32. package/dist/lib/comment-realign.d.ts +12 -21
  33. package/dist/lib/comment-realign.d.ts.map +1 -1
  34. package/dist/lib/comment-realign.js +40 -348
  35. package/dist/lib/comment-realign.js.map +1 -1
  36. package/dist/lib/dependencies.d.ts +10 -0
  37. package/dist/lib/dependencies.d.ts.map +1 -1
  38. package/dist/lib/dependencies.js +41 -9
  39. package/dist/lib/dependencies.js.map +1 -1
  40. package/dist/lib/doi.d.ts.map +1 -1
  41. package/dist/lib/doi.js +68 -80
  42. package/dist/lib/doi.js.map +1 -1
  43. package/dist/lib/errors.d.ts.map +1 -1
  44. package/dist/lib/errors.js +3 -1
  45. package/dist/lib/errors.js.map +1 -1
  46. package/dist/lib/grammar.js +3 -3
  47. package/dist/lib/import.d.ts +7 -4
  48. package/dist/lib/import.d.ts.map +1 -1
  49. package/dist/lib/import.js +58 -62
  50. package/dist/lib/import.js.map +1 -1
  51. package/dist/lib/macro-filter.lua +201 -201
  52. package/dist/lib/ooxml.d.ts +207 -0
  53. package/dist/lib/ooxml.d.ts.map +1 -0
  54. package/dist/lib/ooxml.js +634 -0
  55. package/dist/lib/ooxml.js.map +1 -0
  56. package/dist/lib/pdf-comments.js +44 -44
  57. package/dist/lib/plugins.js +57 -57
  58. package/dist/lib/pptx-color-filter.lua +37 -37
  59. package/dist/lib/pptx-themes.js +115 -115
  60. package/dist/lib/rate-limiter.d.ts +8 -0
  61. package/dist/lib/rate-limiter.d.ts.map +1 -1
  62. package/dist/lib/rate-limiter.js +41 -4
  63. package/dist/lib/rate-limiter.js.map +1 -1
  64. package/dist/lib/sections.d.ts.map +1 -1
  65. package/dist/lib/sections.js +5 -2
  66. package/dist/lib/sections.js.map +1 -1
  67. package/dist/lib/spelling.js +2 -2
  68. package/dist/lib/templates.js +387 -387
  69. package/dist/lib/themes.js +51 -51
  70. package/dist/lib/types.d.ts +9 -1
  71. package/dist/lib/types.d.ts.map +1 -1
  72. package/dist/lib/word-extraction.d.ts.map +1 -1
  73. package/dist/lib/word-extraction.js +48 -307
  74. package/dist/lib/word-extraction.js.map +1 -1
  75. package/dist/lib/word.d.ts.map +1 -1
  76. package/dist/lib/word.js +80 -175
  77. package/dist/lib/word.js.map +1 -1
  78. package/dist/lib/wordcomments.d.ts.map +1 -1
  79. package/dist/lib/wordcomments.js +53 -92
  80. package/dist/lib/wordcomments.js.map +1 -1
  81. package/docs-src/build.py +113 -113
  82. package/docs-src/extra.css +208 -208
  83. package/docs-src/md-to-html.lua +6 -6
  84. package/docs-src/template.html +116 -116
  85. package/eslint.config.js +27 -27
  86. package/lib/anchor-match.ts +307 -276
  87. package/lib/annotations.ts +664 -644
  88. package/lib/build.ts +1770 -1766
  89. package/lib/citations.ts +160 -160
  90. package/lib/commands/build.ts +860 -855
  91. package/lib/commands/citations.ts +515 -515
  92. package/lib/commands/comments.ts +1050 -1050
  93. package/lib/commands/context.ts +176 -176
  94. package/lib/commands/core.ts +309 -309
  95. package/lib/commands/doi.ts +451 -435
  96. package/lib/commands/file-ops.ts +372 -372
  97. package/lib/commands/history.ts +320 -320
  98. package/lib/commands/index.ts +87 -87
  99. package/lib/commands/init.ts +259 -259
  100. package/lib/commands/merge-resolve.ts +378 -378
  101. package/lib/commands/preview.ts +178 -178
  102. package/lib/commands/project-info.ts +244 -244
  103. package/lib/commands/quality.ts +517 -517
  104. package/lib/commands/response.ts +454 -454
  105. package/lib/commands/section-boundaries.ts +82 -82
  106. package/lib/commands/sections.ts +451 -451
  107. package/lib/commands/sync.ts +689 -709
  108. package/lib/commands/text-ops.ts +449 -449
  109. package/lib/commands/utilities.ts +448 -448
  110. package/lib/commands/verify-anchors.ts +272 -272
  111. package/lib/commands/word-tools.ts +340 -340
  112. package/lib/comment-realign.ts +99 -517
  113. package/lib/config.ts +84 -84
  114. package/lib/crossref.ts +781 -781
  115. package/lib/csl.ts +191 -191
  116. package/lib/dependencies.ts +132 -98
  117. package/lib/diff-engine.ts +465 -465
  118. package/lib/doi-cache.ts +115 -115
  119. package/lib/doi.ts +879 -897
  120. package/lib/equations.ts +506 -506
  121. package/lib/errors.ts +350 -346
  122. package/lib/format.ts +541 -541
  123. package/lib/git.ts +326 -326
  124. package/lib/grammar.ts +303 -303
  125. package/lib/image-registry.ts +180 -180
  126. package/lib/import.ts +906 -911
  127. package/lib/journals.ts +543 -543
  128. package/lib/macro-filter.lua +201 -201
  129. package/lib/macros.ts +273 -273
  130. package/lib/merge.ts +633 -633
  131. package/lib/ooxml.ts +768 -0
  132. package/lib/orcid.ts +144 -144
  133. package/lib/pdf-comments.ts +263 -263
  134. package/lib/pdf-import.ts +524 -524
  135. package/lib/plugins.ts +362 -362
  136. package/lib/postprocess.ts +188 -188
  137. package/lib/pptx-color-filter.lua +37 -37
  138. package/lib/pptx-template.ts +469 -469
  139. package/lib/pptx-themes.ts +483 -483
  140. package/lib/protect-restore.ts +520 -520
  141. package/lib/rate-limiter.ts +127 -94
  142. package/lib/response.ts +197 -197
  143. package/lib/restore-references.ts +240 -240
  144. package/lib/review.ts +327 -327
  145. package/lib/schema.ts +488 -488
  146. package/lib/scientific-words.ts +73 -73
  147. package/lib/sections.ts +428 -425
  148. package/lib/slides.ts +756 -756
  149. package/lib/spelling.ts +334 -334
  150. package/lib/templates.ts +526 -526
  151. package/lib/themes.ts +742 -742
  152. package/lib/trackchanges.ts +247 -247
  153. package/lib/tui.ts +450 -450
  154. package/lib/types.ts +558 -550
  155. package/lib/undo.ts +250 -250
  156. package/lib/utils.ts +69 -69
  157. package/lib/variables.ts +179 -179
  158. package/lib/word-extraction.ts +525 -806
  159. package/lib/word.ts +526 -643
  160. package/lib/wordcomments.ts +789 -840
  161. package/mkdocs.yml +64 -64
  162. package/package.json +137 -137
  163. package/scripts/postbuild.js +47 -47
  164. package/skill/REFERENCE.md +539 -539
  165. package/skill/SKILL.md +295 -295
  166. package/tsconfig.json +26 -26
  167. package/types/index.d.ts +525 -525
@@ -1,378 +1,378 @@
1
- /**
2
- * MERGE, CONFLICTS, and MERGE-RESOLVE commands
3
- *
4
- * Commands for three-way merge of reviewer feedback and conflict resolution.
5
- * Split from sections.ts for maintainability.
6
- */
7
-
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- } from './context.js';
14
- import type { Command } from 'commander';
15
- import * as readline from 'readline';
16
-
17
- interface MergeOptions {
18
- base?: string;
19
- output?: string;
20
- names?: string;
21
- strategy: string;
22
- diffLevel: 'sentence' | 'word';
23
- dryRun?: boolean;
24
- sections?: boolean;
25
- }
26
-
27
- /**
28
- * Register merge, conflicts, and merge-resolve commands with the program
29
- */
30
- export function register(program: Command): void {
31
- // ==========================================================================
32
- // MERGE command - Combine feedback from multiple reviewers (three-way merge)
33
- // ==========================================================================
34
-
35
- program
36
- .command('merge')
37
- .description('Merge feedback from multiple Word documents using three-way merge')
38
- .argument('<docx...>', 'Word documents from reviewers')
39
- .option('-b, --base <file>', 'Base document (original sent to reviewers). Auto-detected if not specified.')
40
- .option('-o, --output <file>', 'Output file (default: writes to section files)')
41
- .option('--names <names>', 'Reviewer names (comma-separated, in order of docx files)')
42
- .option('--strategy <strategy>', 'Conflict resolution: first, latest, or interactive (default)', 'interactive')
43
- .option('--diff-level <level>', 'Diff granularity: sentence or word (default: sentence)', 'sentence')
44
- .option('--dry-run', 'Show conflicts without writing')
45
- .option('--sections', 'Split merged output back to section files')
46
- .action(async (docxFiles: string[], options: MergeOptions) => {
47
- const {
48
- mergeThreeWay,
49
- formatConflict,
50
- resolveConflict,
51
- getBaseDocument,
52
- checkBaseMatch,
53
- saveConflicts,
54
- } = await import('../merge.js');
55
-
56
- // Validate reviewer files exist
57
- for (const docx of docxFiles) {
58
- if (!fs.existsSync(docx)) {
59
- console.error(fmt.status('error', `Reviewer file not found: ${docx}`));
60
- process.exit(1);
61
- }
62
- }
63
-
64
- // Determine base document
65
- let basePath = options.base;
66
- let baseSource = 'specified';
67
-
68
- if (!basePath) {
69
- // Try to use .rev/base.docx
70
- const projectDir = process.cwd();
71
- basePath = getBaseDocument(projectDir) ?? undefined;
72
-
73
- if (basePath) {
74
- baseSource = 'auto (.rev/base.docx)';
75
- } else {
76
- console.log(chalk.yellow('\n No base document found in .rev/base.docx'));
77
- console.log(chalk.dim(' Tip: Run "rev build docx" to automatically save the base document.\n'));
78
- console.error(fmt.status('error', 'Base document required. Use --base <file.docx>'));
79
- process.exit(1);
80
- }
81
- }
82
-
83
- if (!fs.existsSync(basePath)) {
84
- console.error(fmt.status('error', `Base document not found: ${basePath}`));
85
- process.exit(1);
86
- }
87
-
88
- // Check similarity between base and reviewer docs
89
- const { matches, similarity } = await checkBaseMatch(basePath, docxFiles[0]);
90
- if (!matches) {
91
- console.log(chalk.yellow(`\n Warning: Base document may not match reviewer file (${Math.round(similarity * 100)}% similar)`));
92
- console.log(chalk.dim(' If this is wrong, use --base to specify the correct original document.\n'));
93
- }
94
-
95
- // Parse reviewer names
96
- const names = options.names
97
- ? options.names.split(',').map(n => n.trim())
98
- : docxFiles.map((f, i) => {
99
- // Try to extract name from filename (e.g., paper_reviewer_A.docx)
100
- const basename = path.basename(f, '.docx');
101
- const match = basename.match(/_([A-Za-z]+)$/);
102
- return match ? match[1] : `Reviewer ${i + 1}`;
103
- });
104
-
105
- // Pad names if needed
106
- while (names.length < docxFiles.length) {
107
- names.push(`Reviewer ${names.length + 1}`);
108
- }
109
-
110
- const reviewerDocs = docxFiles.map((p, i) => ({
111
- path: p,
112
- name: names[i],
113
- }));
114
-
115
- console.log(fmt.header('Three-Way Merge'));
116
- console.log();
117
- console.log(chalk.dim(` Base: ${path.basename(basePath)} (${baseSource})`));
118
- console.log(chalk.dim(` Reviewers: ${names.join(', ')}`));
119
- console.log(chalk.dim(` Diff level: ${options.diffLevel}`));
120
- console.log();
121
-
122
- const spin = fmt.spinner('Analyzing changes...').start();
123
-
124
- try {
125
- const { merged, conflicts, stats, baseText } = await mergeThreeWay(basePath, reviewerDocs, {
126
- diffLevel: options.diffLevel,
127
- });
128
-
129
- spin.stop();
130
-
131
- // Display stats
132
- console.log(fmt.table(['Metric', 'Count'], [
133
- ['Total changes', stats.totalChanges.toString()],
134
- ['Non-conflicting', stats.nonConflicting.toString()],
135
- ['Conflicts', stats.conflicts.toString()],
136
- ['Comments', stats.comments.toString()],
137
- ]));
138
- console.log();
139
-
140
- let finalMerged = merged;
141
-
142
- // Handle conflicts
143
- if (conflicts.length > 0) {
144
- console.log(chalk.yellow(`Found ${conflicts.length} conflict(s):\n`));
145
-
146
- if (options.strategy === 'first') {
147
- // Auto-resolve: take first reviewer's change
148
- for (const conflict of conflicts) {
149
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[0].reviewer}'s change`));
150
- resolveConflict(conflict, 0);
151
- }
152
- } else if (options.strategy === 'latest') {
153
- // Auto-resolve: take last reviewer's change
154
- for (const conflict of conflicts) {
155
- const lastIdx = conflict.changes.length - 1;
156
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[lastIdx].reviewer}'s change`));
157
- resolveConflict(conflict, lastIdx);
158
- }
159
- } else if (!options.dryRun) {
160
- // Interactive resolution
161
- for (let i = 0; i < conflicts.length; i++) {
162
- const conflict = conflicts[i];
163
- console.log(chalk.bold(`\nConflict ${i + 1}/${conflicts.length} (${conflict.id}):`));
164
- console.log(formatConflict(conflict, baseText));
165
- console.log();
166
-
167
- const rl = readline.createInterface({
168
- input: process.stdin,
169
- output: process.stdout,
170
- });
171
-
172
- const answer = await new Promise<string>((resolve) =>
173
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip): `), resolve)
174
- );
175
- rl.close();
176
-
177
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
178
- const choice = parseInt(answer) - 1;
179
- if (choice >= 0 && choice < conflict.changes.length) {
180
- resolveConflict(conflict, choice);
181
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
182
- }
183
- } else {
184
- console.log(chalk.dim(' Skipped (will need manual resolution)'));
185
- }
186
- }
187
- }
188
-
189
- // Save unresolved conflicts for later
190
- const unresolved = conflicts.filter(c => c.resolved === null);
191
- if (unresolved.length > 0) {
192
- saveConflicts(process.cwd(), conflicts, basePath);
193
- console.log(chalk.yellow(`\n ${unresolved.length} unresolved conflict(s) saved to .rev/conflicts.json`));
194
- console.log(chalk.dim(' Run "rev conflicts" to view, "rev merge-resolve" to resolve'));
195
- }
196
- }
197
-
198
- // Write output
199
- if (!options.dryRun) {
200
- if (options.output) {
201
- // Write to single file
202
- fs.writeFileSync(options.output, finalMerged, 'utf-8');
203
- console.log(fmt.status('success', `Merged output written to ${options.output}`));
204
- } else if (options.sections) {
205
- // Split to section files (TODO: implement section splitting)
206
- console.log(chalk.yellow(' Section splitting not yet implemented'));
207
- console.log(chalk.dim(' Use -o to specify output file'));
208
- } else {
209
- // Default: write to merged.md
210
- const outPath = 'merged.md';
211
- fs.writeFileSync(outPath, finalMerged, 'utf-8');
212
- console.log(fmt.status('success', `Merged output written to ${outPath}`));
213
- }
214
-
215
- console.log();
216
- console.log(chalk.dim('Next steps:'));
217
- console.log(chalk.dim(' 1. rev review merged.md - Accept/reject changes'));
218
- console.log(chalk.dim(' 2. rev comments merged.md - Address comments'));
219
- if (conflicts.some(c => c.resolved === null)) {
220
- console.log(chalk.dim(' 3. rev merge-resolve - Resolve remaining conflicts'));
221
- }
222
- } else {
223
- console.log(fmt.status('info', 'Dry run - no output written'));
224
- }
225
- } catch (err) {
226
- spin.stop();
227
- const error = err as Error;
228
- console.error(fmt.status('error', error.message));
229
- if (process.env.DEBUG) console.error(error.stack);
230
- process.exit(1);
231
- }
232
- });
233
-
234
- // ==========================================================================
235
- // CONFLICTS command - List unresolved conflicts
236
- // ==========================================================================
237
-
238
- program
239
- .command('conflicts')
240
- .description('List unresolved merge conflicts')
241
- .action(async () => {
242
- const { loadConflicts, formatConflict } = await import('../merge.js');
243
- const projectDir = process.cwd();
244
- const data = loadConflicts(projectDir);
245
-
246
- if (!data) {
247
- console.log(fmt.status('info', 'No conflicts file found'));
248
- return;
249
- }
250
-
251
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
252
-
253
- if (unresolved.length === 0) {
254
- console.log(fmt.status('success', 'All conflicts resolved!'));
255
- return;
256
- }
257
-
258
- console.log(fmt.header(`Unresolved Conflicts (${unresolved.length})`));
259
- console.log();
260
- console.log(chalk.dim(` Base: ${data.base}`));
261
- console.log(chalk.dim(` Merged: ${data.merged}`));
262
- console.log();
263
-
264
- for (const conflict of unresolved) {
265
- console.log(chalk.bold(`Conflict ${conflict.id}:`));
266
- // Show abbreviated info
267
- console.log(chalk.dim(` Original: "${conflict.original.slice(0, 50)}${conflict.original.length > 50 ? '...' : ''}"`));
268
- console.log(chalk.dim(` Options: ${conflict.changes.map((c: any) => c.reviewer).join(', ')}`));
269
- console.log();
270
- }
271
-
272
- console.log(chalk.dim('Run "rev merge-resolve" to resolve conflicts interactively'));
273
- });
274
-
275
- // ==========================================================================
276
- // MERGE-RESOLVE command - Interactively resolve merge conflicts
277
- // ==========================================================================
278
-
279
- program
280
- .command('merge-resolve')
281
- .alias('mresolve')
282
- .description('Resolve merge conflicts interactively')
283
- .option('--theirs', 'Accept all changes from last reviewer')
284
- .option('--ours', 'Accept all changes from first reviewer')
285
- .action(async (options: { theirs?: boolean; ours?: boolean }) => {
286
- const { loadConflicts, saveConflicts, clearConflicts, resolveConflict, formatConflict } = await import('../merge.js');
287
- const projectDir = process.cwd();
288
- const data = loadConflicts(projectDir);
289
-
290
- if (!data) {
291
- console.log(fmt.status('info', 'No conflicts to resolve'));
292
- return;
293
- }
294
-
295
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
296
-
297
- if (unresolved.length === 0) {
298
- console.log(fmt.status('success', 'All conflicts already resolved!'));
299
- clearConflicts(projectDir);
300
- return;
301
- }
302
-
303
- console.log(fmt.header(`Resolving ${unresolved.length} Conflict(s)`));
304
- console.log();
305
-
306
- if (options.theirs) {
307
- // Accept all from last reviewer
308
- for (const conflict of unresolved) {
309
- const lastIdx = conflict.changes.length - 1;
310
- resolveConflict(conflict, lastIdx);
311
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[lastIdx].reviewer}'s change`));
312
- }
313
- saveConflicts(projectDir, data.conflicts, data.base);
314
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--theirs)`));
315
- } else if (options.ours) {
316
- // Accept all from first reviewer
317
- for (const conflict of unresolved) {
318
- resolveConflict(conflict, 0);
319
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[0].reviewer}'s change`));
320
- }
321
- saveConflicts(projectDir, data.conflicts, data.base);
322
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--ours)`));
323
- } else {
324
- // Interactive resolution
325
- // Read base text for context display
326
- let baseText = '';
327
- try {
328
- const { extractFromWord } = await import('../import.js');
329
- const { text } = await extractFromWord(data.base);
330
- baseText = text;
331
- } catch {
332
- // Can't read base, show without context
333
- }
334
-
335
- for (let i = 0; i < unresolved.length; i++) {
336
- const conflict = unresolved[i];
337
- console.log(chalk.bold(`\nConflict ${i + 1}/${unresolved.length} (${conflict.id}):`));
338
- console.log(formatConflict(conflict, baseText));
339
- console.log();
340
-
341
- const rl = readline.createInterface({
342
- input: process.stdin,
343
- output: process.stdout,
344
- });
345
-
346
- const answer = await new Promise<string>((resolve) =>
347
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip, q=quit): `), resolve)
348
- );
349
- rl.close();
350
-
351
- if (answer.toLowerCase() === 'q') {
352
- console.log(chalk.dim('\n Saving progress...'));
353
- break;
354
- }
355
-
356
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
357
- const choice = parseInt(answer) - 1;
358
- if (choice >= 0 && choice < conflict.changes.length) {
359
- resolveConflict(conflict, choice);
360
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
361
- }
362
- } else {
363
- console.log(chalk.dim(' Skipped'));
364
- }
365
- }
366
-
367
- saveConflicts(projectDir, data.conflicts, data.base);
368
-
369
- const remaining = data.conflicts.filter((c: any) => c.resolved === null).length;
370
- if (remaining === 0) {
371
- console.log(fmt.status('success', '\nAll conflicts resolved!'));
372
- clearConflicts(projectDir);
373
- } else {
374
- console.log(chalk.yellow(`\n ${remaining} conflict(s) remaining`));
375
- }
376
- }
377
- });
378
- }
1
+ /**
2
+ * MERGE, CONFLICTS, and MERGE-RESOLVE commands
3
+ *
4
+ * Commands for three-way merge of reviewer feedback and conflict resolution.
5
+ * Split from sections.ts for maintainability.
6
+ */
7
+
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ } from './context.js';
14
+ import type { Command } from 'commander';
15
+ import * as readline from 'readline';
16
+
17
+ interface MergeOptions {
18
+ base?: string;
19
+ output?: string;
20
+ names?: string;
21
+ strategy: string;
22
+ diffLevel: 'sentence' | 'word';
23
+ dryRun?: boolean;
24
+ sections?: boolean;
25
+ }
26
+
27
+ /**
28
+ * Register merge, conflicts, and merge-resolve commands with the program
29
+ */
30
+ export function register(program: Command): void {
31
+ // ==========================================================================
32
+ // MERGE command - Combine feedback from multiple reviewers (three-way merge)
33
+ // ==========================================================================
34
+
35
+ program
36
+ .command('merge')
37
+ .description('Merge feedback from multiple Word documents using three-way merge')
38
+ .argument('<docx...>', 'Word documents from reviewers')
39
+ .option('-b, --base <file>', 'Base document (original sent to reviewers). Auto-detected if not specified.')
40
+ .option('-o, --output <file>', 'Output file (default: writes to section files)')
41
+ .option('--names <names>', 'Reviewer names (comma-separated, in order of docx files)')
42
+ .option('--strategy <strategy>', 'Conflict resolution: first, latest, or interactive (default)', 'interactive')
43
+ .option('--diff-level <level>', 'Diff granularity: sentence or word (default: sentence)', 'sentence')
44
+ .option('--dry-run', 'Show conflicts without writing')
45
+ .option('--sections', 'Split merged output back to section files')
46
+ .action(async (docxFiles: string[], options: MergeOptions) => {
47
+ const {
48
+ mergeThreeWay,
49
+ formatConflict,
50
+ resolveConflict,
51
+ getBaseDocument,
52
+ checkBaseMatch,
53
+ saveConflicts,
54
+ } = await import('../merge.js');
55
+
56
+ // Validate reviewer files exist
57
+ for (const docx of docxFiles) {
58
+ if (!fs.existsSync(docx)) {
59
+ console.error(fmt.status('error', `Reviewer file not found: ${docx}`));
60
+ process.exit(1);
61
+ }
62
+ }
63
+
64
+ // Determine base document
65
+ let basePath = options.base;
66
+ let baseSource = 'specified';
67
+
68
+ if (!basePath) {
69
+ // Try to use .rev/base.docx
70
+ const projectDir = process.cwd();
71
+ basePath = getBaseDocument(projectDir) ?? undefined;
72
+
73
+ if (basePath) {
74
+ baseSource = 'auto (.rev/base.docx)';
75
+ } else {
76
+ console.log(chalk.yellow('\n No base document found in .rev/base.docx'));
77
+ console.log(chalk.dim(' Tip: Run "rev build docx" to automatically save the base document.\n'));
78
+ console.error(fmt.status('error', 'Base document required. Use --base <file.docx>'));
79
+ process.exit(1);
80
+ }
81
+ }
82
+
83
+ if (!fs.existsSync(basePath)) {
84
+ console.error(fmt.status('error', `Base document not found: ${basePath}`));
85
+ process.exit(1);
86
+ }
87
+
88
+ // Check similarity between base and reviewer docs
89
+ const { matches, similarity } = await checkBaseMatch(basePath, docxFiles[0]);
90
+ if (!matches) {
91
+ console.log(chalk.yellow(`\n Warning: Base document may not match reviewer file (${Math.round(similarity * 100)}% similar)`));
92
+ console.log(chalk.dim(' If this is wrong, use --base to specify the correct original document.\n'));
93
+ }
94
+
95
+ // Parse reviewer names
96
+ const names = options.names
97
+ ? options.names.split(',').map(n => n.trim())
98
+ : docxFiles.map((f, i) => {
99
+ // Try to extract name from filename (e.g., paper_reviewer_A.docx)
100
+ const basename = path.basename(f, '.docx');
101
+ const match = basename.match(/_([A-Za-z]+)$/);
102
+ return match ? match[1] : `Reviewer ${i + 1}`;
103
+ });
104
+
105
+ // Pad names if needed
106
+ while (names.length < docxFiles.length) {
107
+ names.push(`Reviewer ${names.length + 1}`);
108
+ }
109
+
110
+ const reviewerDocs = docxFiles.map((p, i) => ({
111
+ path: p,
112
+ name: names[i],
113
+ }));
114
+
115
+ console.log(fmt.header('Three-Way Merge'));
116
+ console.log();
117
+ console.log(chalk.dim(` Base: ${path.basename(basePath)} (${baseSource})`));
118
+ console.log(chalk.dim(` Reviewers: ${names.join(', ')}`));
119
+ console.log(chalk.dim(` Diff level: ${options.diffLevel}`));
120
+ console.log();
121
+
122
+ const spin = fmt.spinner('Analyzing changes...').start();
123
+
124
+ try {
125
+ const { merged, conflicts, stats, baseText } = await mergeThreeWay(basePath, reviewerDocs, {
126
+ diffLevel: options.diffLevel,
127
+ });
128
+
129
+ spin.stop();
130
+
131
+ // Display stats
132
+ console.log(fmt.table(['Metric', 'Count'], [
133
+ ['Total changes', stats.totalChanges.toString()],
134
+ ['Non-conflicting', stats.nonConflicting.toString()],
135
+ ['Conflicts', stats.conflicts.toString()],
136
+ ['Comments', stats.comments.toString()],
137
+ ]));
138
+ console.log();
139
+
140
+ let finalMerged = merged;
141
+
142
+ // Handle conflicts
143
+ if (conflicts.length > 0) {
144
+ console.log(chalk.yellow(`Found ${conflicts.length} conflict(s):\n`));
145
+
146
+ if (options.strategy === 'first') {
147
+ // Auto-resolve: take first reviewer's change
148
+ for (const conflict of conflicts) {
149
+ console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[0].reviewer}'s change`));
150
+ resolveConflict(conflict, 0);
151
+ }
152
+ } else if (options.strategy === 'latest') {
153
+ // Auto-resolve: take last reviewer's change
154
+ for (const conflict of conflicts) {
155
+ const lastIdx = conflict.changes.length - 1;
156
+ console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[lastIdx].reviewer}'s change`));
157
+ resolveConflict(conflict, lastIdx);
158
+ }
159
+ } else if (!options.dryRun) {
160
+ // Interactive resolution
161
+ for (let i = 0; i < conflicts.length; i++) {
162
+ const conflict = conflicts[i];
163
+ console.log(chalk.bold(`\nConflict ${i + 1}/${conflicts.length} (${conflict.id}):`));
164
+ console.log(formatConflict(conflict, baseText));
165
+ console.log();
166
+
167
+ const rl = readline.createInterface({
168
+ input: process.stdin,
169
+ output: process.stdout,
170
+ });
171
+
172
+ const answer = await new Promise<string>((resolve) =>
173
+ rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip): `), resolve)
174
+ );
175
+ rl.close();
176
+
177
+ if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
178
+ const choice = parseInt(answer) - 1;
179
+ if (choice >= 0 && choice < conflict.changes.length) {
180
+ resolveConflict(conflict, choice);
181
+ console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
182
+ }
183
+ } else {
184
+ console.log(chalk.dim(' Skipped (will need manual resolution)'));
185
+ }
186
+ }
187
+ }
188
+
189
+ // Save unresolved conflicts for later
190
+ const unresolved = conflicts.filter(c => c.resolved === null);
191
+ if (unresolved.length > 0) {
192
+ saveConflicts(process.cwd(), conflicts, basePath);
193
+ console.log(chalk.yellow(`\n ${unresolved.length} unresolved conflict(s) saved to .rev/conflicts.json`));
194
+ console.log(chalk.dim(' Run "rev conflicts" to view, "rev merge-resolve" to resolve'));
195
+ }
196
+ }
197
+
198
+ // Write output
199
+ if (!options.dryRun) {
200
+ if (options.output) {
201
+ // Write to single file
202
+ fs.writeFileSync(options.output, finalMerged, 'utf-8');
203
+ console.log(fmt.status('success', `Merged output written to ${options.output}`));
204
+ } else if (options.sections) {
205
+ // Split to section files (TODO: implement section splitting)
206
+ console.log(chalk.yellow(' Section splitting not yet implemented'));
207
+ console.log(chalk.dim(' Use -o to specify output file'));
208
+ } else {
209
+ // Default: write to merged.md
210
+ const outPath = 'merged.md';
211
+ fs.writeFileSync(outPath, finalMerged, 'utf-8');
212
+ console.log(fmt.status('success', `Merged output written to ${outPath}`));
213
+ }
214
+
215
+ console.log();
216
+ console.log(chalk.dim('Next steps:'));
217
+ console.log(chalk.dim(' 1. rev review merged.md - Accept/reject changes'));
218
+ console.log(chalk.dim(' 2. rev comments merged.md - Address comments'));
219
+ if (conflicts.some(c => c.resolved === null)) {
220
+ console.log(chalk.dim(' 3. rev merge-resolve - Resolve remaining conflicts'));
221
+ }
222
+ } else {
223
+ console.log(fmt.status('info', 'Dry run - no output written'));
224
+ }
225
+ } catch (err) {
226
+ spin.stop();
227
+ const error = err as Error;
228
+ console.error(fmt.status('error', error.message));
229
+ if (process.env.DEBUG) console.error(error.stack);
230
+ process.exit(1);
231
+ }
232
+ });
233
+
234
+ // ==========================================================================
235
+ // CONFLICTS command - List unresolved conflicts
236
+ // ==========================================================================
237
+
238
+ program
239
+ .command('conflicts')
240
+ .description('List unresolved merge conflicts')
241
+ .action(async () => {
242
+ const { loadConflicts, formatConflict } = await import('../merge.js');
243
+ const projectDir = process.cwd();
244
+ const data = loadConflicts(projectDir);
245
+
246
+ if (!data) {
247
+ console.log(fmt.status('info', 'No conflicts file found'));
248
+ return;
249
+ }
250
+
251
+ const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
252
+
253
+ if (unresolved.length === 0) {
254
+ console.log(fmt.status('success', 'All conflicts resolved!'));
255
+ return;
256
+ }
257
+
258
+ console.log(fmt.header(`Unresolved Conflicts (${unresolved.length})`));
259
+ console.log();
260
+ console.log(chalk.dim(` Base: ${data.base}`));
261
+ console.log(chalk.dim(` Merged: ${data.merged}`));
262
+ console.log();
263
+
264
+ for (const conflict of unresolved) {
265
+ console.log(chalk.bold(`Conflict ${conflict.id}:`));
266
+ // Show abbreviated info
267
+ console.log(chalk.dim(` Original: "${conflict.original.slice(0, 50)}${conflict.original.length > 50 ? '...' : ''}"`));
268
+ console.log(chalk.dim(` Options: ${conflict.changes.map((c: any) => c.reviewer).join(', ')}`));
269
+ console.log();
270
+ }
271
+
272
+ console.log(chalk.dim('Run "rev merge-resolve" to resolve conflicts interactively'));
273
+ });
274
+
275
+ // ==========================================================================
276
+ // MERGE-RESOLVE command - Interactively resolve merge conflicts
277
+ // ==========================================================================
278
+
279
+ program
280
+ .command('merge-resolve')
281
+ .alias('mresolve')
282
+ .description('Resolve merge conflicts interactively')
283
+ .option('--theirs', 'Accept all changes from last reviewer')
284
+ .option('--ours', 'Accept all changes from first reviewer')
285
+ .action(async (options: { theirs?: boolean; ours?: boolean }) => {
286
+ const { loadConflicts, saveConflicts, clearConflicts, resolveConflict, formatConflict } = await import('../merge.js');
287
+ const projectDir = process.cwd();
288
+ const data = loadConflicts(projectDir);
289
+
290
+ if (!data) {
291
+ console.log(fmt.status('info', 'No conflicts to resolve'));
292
+ return;
293
+ }
294
+
295
+ const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
296
+
297
+ if (unresolved.length === 0) {
298
+ console.log(fmt.status('success', 'All conflicts already resolved!'));
299
+ clearConflicts(projectDir);
300
+ return;
301
+ }
302
+
303
+ console.log(fmt.header(`Resolving ${unresolved.length} Conflict(s)`));
304
+ console.log();
305
+
306
+ if (options.theirs) {
307
+ // Accept all from last reviewer
308
+ for (const conflict of unresolved) {
309
+ const lastIdx = conflict.changes.length - 1;
310
+ resolveConflict(conflict, lastIdx);
311
+ console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[lastIdx].reviewer}'s change`));
312
+ }
313
+ saveConflicts(projectDir, data.conflicts, data.base);
314
+ console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--theirs)`));
315
+ } else if (options.ours) {
316
+ // Accept all from first reviewer
317
+ for (const conflict of unresolved) {
318
+ resolveConflict(conflict, 0);
319
+ console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[0].reviewer}'s change`));
320
+ }
321
+ saveConflicts(projectDir, data.conflicts, data.base);
322
+ console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--ours)`));
323
+ } else {
324
+ // Interactive resolution
325
+ // Read base text for context display
326
+ let baseText = '';
327
+ try {
328
+ const { extractFromWord } = await import('../import.js');
329
+ const { text } = await extractFromWord(data.base);
330
+ baseText = text;
331
+ } catch {
332
+ // Can't read base, show without context
333
+ }
334
+
335
+ for (let i = 0; i < unresolved.length; i++) {
336
+ const conflict = unresolved[i];
337
+ console.log(chalk.bold(`\nConflict ${i + 1}/${unresolved.length} (${conflict.id}):`));
338
+ console.log(formatConflict(conflict, baseText));
339
+ console.log();
340
+
341
+ const rl = readline.createInterface({
342
+ input: process.stdin,
343
+ output: process.stdout,
344
+ });
345
+
346
+ const answer = await new Promise<string>((resolve) =>
347
+ rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip, q=quit): `), resolve)
348
+ );
349
+ rl.close();
350
+
351
+ if (answer.toLowerCase() === 'q') {
352
+ console.log(chalk.dim('\n Saving progress...'));
353
+ break;
354
+ }
355
+
356
+ if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
357
+ const choice = parseInt(answer) - 1;
358
+ if (choice >= 0 && choice < conflict.changes.length) {
359
+ resolveConflict(conflict, choice);
360
+ console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
361
+ }
362
+ } else {
363
+ console.log(chalk.dim(' Skipped'));
364
+ }
365
+ }
366
+
367
+ saveConflicts(projectDir, data.conflicts, data.base);
368
+
369
+ const remaining = data.conflicts.filter((c: any) => c.resolved === null).length;
370
+ if (remaining === 0) {
371
+ console.log(fmt.status('success', '\nAll conflicts resolved!'));
372
+ clearConflicts(projectDir);
373
+ } else {
374
+ console.log(chalk.yellow(`\n ${remaining} conflict(s) remaining`));
375
+ }
376
+ }
377
+ });
378
+ }