docrev 0.9.4 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/lib/commands/comments.d.ts.map +1 -1
  2. package/dist/lib/commands/comments.js +19 -27
  3. package/dist/lib/commands/comments.js.map +1 -1
  4. package/dist/lib/commands/context.d.ts +1 -0
  5. package/dist/lib/commands/context.d.ts.map +1 -1
  6. package/dist/lib/commands/context.js +1 -2
  7. package/dist/lib/commands/context.js.map +1 -1
  8. package/dist/lib/commands/file-ops.d.ts +11 -0
  9. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  10. package/dist/lib/commands/file-ops.js +301 -0
  11. package/dist/lib/commands/file-ops.js.map +1 -0
  12. package/dist/lib/commands/index.d.ts +9 -1
  13. package/dist/lib/commands/index.d.ts.map +1 -1
  14. package/dist/lib/commands/index.js +17 -1
  15. package/dist/lib/commands/index.js.map +1 -1
  16. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  17. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  18. package/dist/lib/commands/merge-resolve.js +318 -0
  19. package/dist/lib/commands/merge-resolve.js.map +1 -0
  20. package/dist/lib/commands/preview.d.ts +11 -0
  21. package/dist/lib/commands/preview.d.ts.map +1 -0
  22. package/dist/lib/commands/preview.js +138 -0
  23. package/dist/lib/commands/preview.js.map +1 -0
  24. package/dist/lib/commands/project-info.d.ts +11 -0
  25. package/dist/lib/commands/project-info.d.ts.map +1 -0
  26. package/dist/lib/commands/project-info.js +187 -0
  27. package/dist/lib/commands/project-info.js.map +1 -0
  28. package/dist/lib/commands/quality.d.ts +11 -0
  29. package/dist/lib/commands/quality.d.ts.map +1 -0
  30. package/dist/lib/commands/quality.js +384 -0
  31. package/dist/lib/commands/quality.js.map +1 -0
  32. package/dist/lib/commands/sections.d.ts +3 -2
  33. package/dist/lib/commands/sections.d.ts.map +1 -1
  34. package/dist/lib/commands/sections.js +4 -723
  35. package/dist/lib/commands/sections.js.map +1 -1
  36. package/dist/lib/commands/sync.d.ts +11 -0
  37. package/dist/lib/commands/sync.d.ts.map +1 -0
  38. package/dist/lib/commands/sync.js +441 -0
  39. package/dist/lib/commands/sync.js.map +1 -0
  40. package/dist/lib/commands/text-ops.d.ts +11 -0
  41. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  42. package/dist/lib/commands/text-ops.js +357 -0
  43. package/dist/lib/commands/text-ops.js.map +1 -0
  44. package/dist/lib/commands/utilities.d.ts +2 -4
  45. package/dist/lib/commands/utilities.d.ts.map +1 -1
  46. package/dist/lib/commands/utilities.js +3 -1605
  47. package/dist/lib/commands/utilities.js.map +1 -1
  48. package/dist/lib/commands/word-tools.d.ts +11 -0
  49. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  50. package/dist/lib/commands/word-tools.js +272 -0
  51. package/dist/lib/commands/word-tools.js.map +1 -0
  52. package/dist/lib/comment-realign.d.ts.map +1 -1
  53. package/dist/lib/comment-realign.js +0 -7
  54. package/dist/lib/comment-realign.js.map +1 -1
  55. package/dist/lib/dependencies.d.ts.map +1 -1
  56. package/dist/lib/dependencies.js +11 -23
  57. package/dist/lib/dependencies.js.map +1 -1
  58. package/dist/lib/diff-engine.d.ts +25 -0
  59. package/dist/lib/diff-engine.d.ts.map +1 -0
  60. package/dist/lib/diff-engine.js +354 -0
  61. package/dist/lib/diff-engine.js.map +1 -0
  62. package/dist/lib/git.d.ts.map +1 -1
  63. package/dist/lib/git.js +18 -28
  64. package/dist/lib/git.js.map +1 -1
  65. package/dist/lib/import.d.ts +37 -117
  66. package/dist/lib/import.d.ts.map +1 -1
  67. package/dist/lib/import.js +10 -1039
  68. package/dist/lib/import.js.map +1 -1
  69. package/dist/lib/merge.d.ts.map +1 -1
  70. package/dist/lib/merge.js +29 -117
  71. package/dist/lib/merge.js.map +1 -1
  72. package/dist/lib/pdf-comments.d.ts.map +1 -1
  73. package/dist/lib/pdf-comments.js +1 -13
  74. package/dist/lib/pdf-comments.js.map +1 -1
  75. package/dist/lib/pptx-themes.d.ts.map +1 -1
  76. package/dist/lib/pptx-themes.js +0 -403
  77. package/dist/lib/pptx-themes.js.map +1 -1
  78. package/dist/lib/protect-restore.d.ts.map +1 -1
  79. package/dist/lib/protect-restore.js +34 -36
  80. package/dist/lib/protect-restore.js.map +1 -1
  81. package/dist/lib/restore-references.d.ts +35 -0
  82. package/dist/lib/restore-references.d.ts.map +1 -0
  83. package/dist/lib/restore-references.js +188 -0
  84. package/dist/lib/restore-references.js.map +1 -0
  85. package/dist/lib/slides.d.ts.map +1 -1
  86. package/dist/lib/slides.js +0 -35
  87. package/dist/lib/slides.js.map +1 -1
  88. package/dist/lib/trackchanges.d.ts.map +1 -1
  89. package/dist/lib/trackchanges.js +1 -11
  90. package/dist/lib/trackchanges.js.map +1 -1
  91. package/dist/lib/tui.d.ts +36 -45
  92. package/dist/lib/tui.d.ts.map +1 -1
  93. package/dist/lib/tui.js +92 -108
  94. package/dist/lib/tui.js.map +1 -1
  95. package/dist/lib/undo.d.ts +3 -4
  96. package/dist/lib/undo.d.ts.map +1 -1
  97. package/dist/lib/undo.js +0 -7
  98. package/dist/lib/undo.js.map +1 -1
  99. package/dist/lib/utils.d.ts +12 -0
  100. package/dist/lib/utils.d.ts.map +1 -1
  101. package/dist/lib/utils.js +26 -0
  102. package/dist/lib/utils.js.map +1 -1
  103. package/dist/lib/word-extraction.d.ts +77 -0
  104. package/dist/lib/word-extraction.d.ts.map +1 -0
  105. package/dist/lib/word-extraction.js +515 -0
  106. package/dist/lib/word-extraction.js.map +1 -0
  107. package/dist/lib/wordcomments.d.ts.map +1 -1
  108. package/dist/lib/wordcomments.js +1 -8
  109. package/dist/lib/wordcomments.js.map +1 -1
  110. package/dist/package.json +137 -0
  111. package/lib/commands/comments.ts +20 -25
  112. package/lib/commands/context.ts +1 -2
  113. package/lib/commands/file-ops.ts +372 -0
  114. package/lib/commands/index.ts +24 -0
  115. package/lib/commands/merge-resolve.ts +378 -0
  116. package/lib/commands/preview.ts +178 -0
  117. package/lib/commands/project-info.ts +244 -0
  118. package/lib/commands/quality.ts +517 -0
  119. package/lib/commands/sections.ts +3 -857
  120. package/lib/commands/sync.ts +536 -0
  121. package/lib/commands/text-ops.ts +449 -0
  122. package/lib/commands/utilities.ts +62 -2066
  123. package/lib/commands/word-tools.ts +340 -0
  124. package/lib/comment-realign.ts +0 -8
  125. package/lib/dependencies.ts +12 -20
  126. package/lib/diff-engine.ts +465 -0
  127. package/lib/git.ts +24 -31
  128. package/lib/import.ts +78 -1348
  129. package/lib/merge.ts +42 -132
  130. package/lib/pdf-comments.ts +2 -14
  131. package/lib/pptx-themes.ts +0 -413
  132. package/lib/protect-restore.ts +48 -44
  133. package/lib/restore-references.ts +240 -0
  134. package/lib/slides.ts +0 -37
  135. package/lib/trackchanges.ts +1 -12
  136. package/lib/{tui.js → tui.ts} +139 -126
  137. package/lib/undo.ts +3 -12
  138. package/lib/utils.ts +28 -0
  139. package/lib/word-extraction.ts +666 -0
  140. package/lib/wordcomments.ts +1 -9
  141. package/package.json +1 -1
@@ -1,25 +1,19 @@
1
1
  /**
2
- * Section commands: import, extract, split, sync, merge
2
+ * Section commands: import, extract, split
3
3
  *
4
- * Commands for importing Word documents, splitting/syncing section files.
4
+ * Commands for importing Word documents and splitting section files.
5
+ * Sync and merge commands are in sync.ts and merge-resolve.ts respectively.
5
6
  */
6
7
 
7
8
  import {
8
9
  chalk,
9
10
  fs,
10
11
  path,
11
- fmt,
12
- findFiles,
13
12
  countAnnotations,
14
13
  loadConfig,
15
- extractSectionsFromText,
16
14
  splitAnnotatedPaper,
17
- buildRegistry,
18
- convertHardcodedRefs,
19
- inlineDiffPreview,
20
15
  } from './context.js';
21
16
  import type { Command } from 'commander';
22
- import * as readline from 'readline';
23
17
 
24
18
  interface DetectedSection {
25
19
  header: string;
@@ -56,25 +50,6 @@ interface SplitOptions {
56
50
  dryRun?: boolean;
57
51
  }
58
52
 
59
- interface SyncOptions {
60
- config: string;
61
- dir: string;
62
- crossref?: boolean;
63
- diff?: boolean;
64
- force?: boolean;
65
- dryRun?: boolean;
66
- }
67
-
68
- interface MergeOptions {
69
- base?: string;
70
- output?: string;
71
- names?: string;
72
- strategy: string;
73
- diffLevel: 'sentence' | 'word';
74
- dryRun?: boolean;
75
- sections?: boolean;
76
- }
77
-
78
53
  /**
79
54
  * Detect sections from Word document text
80
55
  * Looks for common academic paper section headers
@@ -473,833 +448,4 @@ export function register(program: Command): void {
473
448
  console.log(chalk.cyan('\nNext: rev review <section.md> for each section'));
474
449
  }
475
450
  });
476
-
477
- // ==========================================================================
478
- // SYNC command - Import with section awareness
479
- // ==========================================================================
480
-
481
- program
482
- .command('sync')
483
- .alias('sections')
484
- .description('Sync feedback from Word/PDF back to section files')
485
- .argument('[file]', 'Word (.docx) or PDF file from reviewer (default: most recent)')
486
- .argument('[sections...]', 'Specific sections to sync (default: all)')
487
- .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
488
- .option('-d, --dir <directory>', 'Directory with section files', '.')
489
- .option('--no-crossref', 'Skip converting hardcoded figure/table refs')
490
- .option('--no-diff', 'Skip showing diff preview')
491
- .option('--force', 'Overwrite files without conflict warning')
492
- .option('--dry-run', 'Preview without writing files')
493
- .action(async (docx: string | undefined, sections: string[], options: SyncOptions) => {
494
- // Auto-detect most recent docx or pdf if not provided
495
- if (!docx) {
496
- const docxFiles = findFiles('.docx');
497
- const pdfFiles = findFiles('.pdf');
498
- const allFiles = [...docxFiles, ...pdfFiles];
499
-
500
- if (allFiles.length === 0) {
501
- console.error(fmt.status('error', 'No .docx or .pdf files found in current directory.'));
502
- process.exit(1);
503
- }
504
- const sorted = allFiles
505
- .map(f => ({ name: f, mtime: fs.statSync(f).mtime }))
506
- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
507
- docx = sorted[0].name;
508
- console.log(fmt.status('info', `Using most recent: ${docx}`));
509
- console.log();
510
- }
511
-
512
- if (!fs.existsSync(docx)) {
513
- console.error(fmt.status('error', `File not found: ${docx}`));
514
- process.exit(1);
515
- }
516
-
517
- // Handle PDF files
518
- if (docx.toLowerCase().endsWith('.pdf')) {
519
- const { extractPdfComments, formatPdfComments, getPdfCommentStats } = await import('../pdf-import.js');
520
-
521
- const spin = fmt.spinner(`Extracting comments from ${path.basename(docx)}...`).start();
522
-
523
- try {
524
- const comments = await extractPdfComments(docx);
525
- spin.stop();
526
-
527
- if (comments.length === 0) {
528
- console.log(fmt.status('info', 'No comments found in PDF.'));
529
- return;
530
- }
531
-
532
- const stats = getPdfCommentStats(comments);
533
- console.log(fmt.header(`PDF Comments from ${path.basename(docx)}`));
534
- console.log();
535
- console.log(formatPdfComments(comments));
536
- console.log();
537
-
538
- const authorList = Object.entries(stats.byAuthor)
539
- .map(([author, count]) => `${author} (${count})`)
540
- .join(', ');
541
- console.log(chalk.dim(`Total: ${stats.total} comments from ${authorList}`));
542
- console.log();
543
-
544
- const configPath = path.resolve(options.dir, options.config);
545
- if (fs.existsSync(configPath) && !options.dryRun) {
546
- const config = loadConfig(configPath);
547
- const mainSection = config.sections?.[0];
548
-
549
- if (mainSection && typeof mainSection === 'string') {
550
- const mainPath = path.join(options.dir, mainSection);
551
- if (fs.existsSync(mainPath)) {
552
- console.log(chalk.dim(`Use 'rev pdf-comments ${docx} --append ${mainSection}' to add comments to markdown.`));
553
- }
554
- }
555
- }
556
- } catch (err) {
557
- spin.stop();
558
- const error = err as Error;
559
- console.error(fmt.status('error', `Failed to extract PDF comments: ${error.message}`));
560
- if (process.env.DEBUG) console.error(error.stack);
561
- process.exit(1);
562
- }
563
- return;
564
- }
565
-
566
- const configPath = path.resolve(options.dir, options.config);
567
- if (!fs.existsSync(configPath)) {
568
- console.error(fmt.status('error', `Config not found: ${configPath}`));
569
- console.error(chalk.dim(' Run "rev init" first to generate sections.yaml'));
570
- process.exit(1);
571
- }
572
-
573
- // Check pandoc availability upfront and warn
574
- const { hasPandoc, getInstallInstructions } = await import('../dependencies.js');
575
- if (!hasPandoc()) {
576
- console.log(fmt.status('warning', `Pandoc not installed. Track changes will be extracted from XML (formatting may differ).`));
577
- console.log(chalk.dim(` Install for best results: ${getInstallInstructions('pandoc')}`));
578
- console.log();
579
- }
580
-
581
- const spin = fmt.spinner(`Importing ${path.basename(docx)}...`).start();
582
-
583
- try {
584
- const config = loadConfig(configPath);
585
- const { importFromWord, extractWordComments, extractCommentAnchors, insertCommentsIntoMarkdown, extractFromWord } = await import('../import.js');
586
-
587
- let registry = null;
588
- let totalRefConversions = 0;
589
- if (options.crossref !== false) {
590
- registry = buildRegistry(options.dir);
591
- }
592
-
593
- const comments = await extractWordComments(docx);
594
- const { anchors, fullDocText: xmlDocText } = await extractCommentAnchors(docx);
595
-
596
- // Extract Word text (uses pandoc if available, falls back to XML extraction)
597
- const wordExtraction = await extractFromWord(docx, { mediaDir: options.dir });
598
- let wordText = wordExtraction.text;
599
- const wordTables = wordExtraction.tables || [];
600
-
601
- // Log extraction messages (warnings about pandoc, track change stats, etc.)
602
- for (const msg of wordExtraction.messages || []) {
603
- if (msg.type === 'warning') {
604
- spin.stop();
605
- console.log(fmt.status('warning', msg.message));
606
- spin.start();
607
- }
608
- }
609
-
610
- // Restore crossref on FULL text BEFORE splitting into sections
611
- // This ensures duplicate labels from track changes are handled correctly
612
- // (the same figure may appear multiple times in old/new versions)
613
- const { restoreCrossrefFromWord, restoreImagesFromRegistry } = await import('../import.js');
614
- const crossrefResult = restoreCrossrefFromWord(wordText, options.dir);
615
- wordText = crossrefResult.text;
616
- if (crossrefResult.restored > 0) {
617
- console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
618
- }
619
-
620
- // Also restore images from registry using shared restoredLabels
621
- const imageRestoreResult = restoreImagesFromRegistry(wordText, options.dir, crossrefResult.restoredLabels);
622
- wordText = imageRestoreResult.text;
623
- if (imageRestoreResult.restored > 0) {
624
- console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
625
- }
626
-
627
- let wordSections = extractSectionsFromText(wordText, config.sections);
628
-
629
- if (wordSections.length === 0) {
630
- spin.stop();
631
- console.error(fmt.status('warning', 'No sections detected in Word document.'));
632
- console.error(chalk.dim(' Check that headings match sections.yaml'));
633
- process.exit(1);
634
- }
635
-
636
- if (sections && sections.length > 0) {
637
- const onlyList = sections.map(s => s.trim().toLowerCase());
638
- wordSections = wordSections.filter(section => {
639
- const fileName = section.file.replace(/\.md$/i, '').toLowerCase();
640
- const header = section.header.toLowerCase();
641
- return onlyList.some(name => fileName === name || fileName.includes(name) || header.includes(name));
642
- });
643
- if (wordSections.length === 0) {
644
- spin.stop();
645
- console.error(fmt.status('error', `No sections matched: ${sections.join(', ')}`));
646
- console.error(chalk.dim(` Available: ${extractSectionsFromText(wordText, config.sections).map(s => s.file.replace(/\.md$/i, '')).join(', ')}`));
647
- process.exit(1);
648
- }
649
- }
650
-
651
- spin.stop();
652
- console.log(fmt.header(`Import from ${path.basename(docx)}`));
653
- console.log();
654
-
655
- // Conflict detection
656
- if (!options.force && !options.dryRun) {
657
- const conflicts: Array<{ file: string; annotations: number }> = [];
658
- for (const section of wordSections) {
659
- const sectionPath = path.join(options.dir, section.file);
660
- if (fs.existsSync(sectionPath)) {
661
- const existing = fs.readFileSync(sectionPath, 'utf-8');
662
- const existingCounts = countAnnotations(existing);
663
- if (existingCounts.total > 0) {
664
- conflicts.push({
665
- file: section.file,
666
- annotations: existingCounts.total,
667
- });
668
- }
669
- }
670
- }
671
-
672
- if (conflicts.length > 0) {
673
- console.log(fmt.status('warning', 'Files with existing annotations will be overwritten:'));
674
- for (const c of conflicts) {
675
- console.log(chalk.yellow(` - ${c.file} (${c.annotations} annotations)`));
676
- }
677
- console.log();
678
-
679
- const rl = readline.createInterface({
680
- input: process.stdin,
681
- output: process.stdout,
682
- });
683
-
684
- const answer = await new Promise<string>((resolve) =>
685
- rl.question(chalk.cyan('Continue and overwrite? [y/N] '), resolve)
686
- );
687
- rl.close();
688
-
689
- if (answer.toLowerCase() !== 'y') {
690
- console.log(chalk.dim('Aborted. Use --force to skip this check.'));
691
- process.exit(0);
692
- }
693
- console.log();
694
- }
695
- }
696
-
697
- const sectionResults: Array<{
698
- file: string;
699
- header: string;
700
- status: string;
701
- stats?: ImportStats;
702
- refs?: number;
703
- }> = [];
704
- let totalChanges = 0;
705
-
706
- // Calculate section boundaries in the XML document text for comment filtering
707
- // Comment positions (docPosition) are relative to xmlDocText, NOT wordText
708
- // So we must find section headers in xmlDocText to get matching boundaries
709
- const sectionBoundaries: Array<{ file: string; start: number; end: number }> = [];
710
- const xmlLower = xmlDocText.toLowerCase();
711
-
712
- // Standard section header keywords to search for in XML
713
- // Map from file name pattern to search terms
714
- const sectionKeywords: Record<string, string[]> = {
715
- 'abstract': ['abstract', 'summary'],
716
- 'introduction': ['introduction', 'background'],
717
- 'methods': ['methods', 'materials and methods', 'methodology'],
718
- 'results': ['results'],
719
- 'discussion': ['discussion'],
720
- 'conclusion': ['conclusion', 'conclusions'],
721
- };
722
-
723
- // Helper: find section header (skip labels like "Methods:" in structured abstracts)
724
- // Real section headers are NOT followed by ":" immediately
725
- function findSectionHeader(text: string, keyword: string, startFrom: number = 0): number {
726
- const lower = text.toLowerCase();
727
- let idx = startFrom;
728
- while ((idx = lower.indexOf(keyword, idx)) !== -1) {
729
- // Check what follows the keyword
730
- const afterKeyword = text.slice(idx + keyword.length, idx + keyword.length + 5);
731
- // Skip if followed by ":" (this is a label, not a section header)
732
- // Real headers are followed by text content, a newline, or a subheading
733
- if (!afterKeyword.startsWith(':') && !afterKeyword.startsWith(' :')) {
734
- return idx;
735
- }
736
- idx++;
737
- }
738
- return -1;
739
- }
740
-
741
- for (const section of wordSections) {
742
- const fileBase = section.file.replace(/\.md$/i, '').toLowerCase();
743
-
744
- // Get keywords for this section
745
- const keywords = sectionKeywords[fileBase] || [fileBase];
746
-
747
- // Find the first valid keyword that exists in XML (not a label)
748
- let headerIdx = -1;
749
- for (const kw of keywords) {
750
- const idx = findSectionHeader(xmlDocText, kw, 0);
751
- if (idx >= 0 && (headerIdx < 0 || idx < headerIdx)) {
752
- headerIdx = idx;
753
- }
754
- }
755
-
756
- if (headerIdx >= 0) {
757
- // Find the next section's start to determine end boundary
758
- let nextHeaderIdx = xmlDocText.length;
759
- const sectionIdx = wordSections.indexOf(section);
760
- if (sectionIdx < wordSections.length - 1) {
761
- const nextFileBase = wordSections[sectionIdx + 1].file.replace(/\.md$/i, '').toLowerCase();
762
- const nextKeywords = sectionKeywords[nextFileBase] || [nextFileBase];
763
- for (const nkw of nextKeywords) {
764
- const foundNext = findSectionHeader(xmlDocText, nkw, headerIdx + 10);
765
- if (foundNext >= 0 && foundNext < nextHeaderIdx) {
766
- nextHeaderIdx = foundNext;
767
- }
768
- }
769
- }
770
-
771
- sectionBoundaries.push({
772
- file: section.file,
773
- start: headerIdx,
774
- end: nextHeaderIdx
775
- });
776
-
777
- }
778
- }
779
-
780
- // Document length is the XML text length (same coordinate system as docPosition)
781
- const docLength = xmlDocText.length;
782
-
783
- for (const section of wordSections) {
784
- const sectionPath = path.join(options.dir, section.file);
785
-
786
- if (!fs.existsSync(sectionPath)) {
787
- sectionResults.push({
788
- file: section.file,
789
- header: section.header,
790
- status: 'skipped',
791
- stats: undefined,
792
- });
793
- continue;
794
- }
795
-
796
- const result = await importFromWord(docx, sectionPath, {
797
- sectionContent: section.content,
798
- author: 'Reviewer',
799
- wordTables: wordTables,
800
- });
801
-
802
- let { annotated, stats } = result;
803
-
804
- let refConversions: Array<{ from: string; to: string }> = [];
805
- if (registry && options.crossref !== false) {
806
- const crossrefResult = convertHardcodedRefs(annotated, registry);
807
- annotated = crossrefResult.converted;
808
- refConversions = crossrefResult.conversions;
809
- totalRefConversions += refConversions.length;
810
- }
811
-
812
- let commentsInserted = 0;
813
- if (comments.length > 0 && anchors.size > 0) {
814
- // Filter comments to only those that belong to this section
815
- // Use exact position matching: docPosition is in xmlDocText coordinates,
816
- // and sectionBoundaries are also in xmlDocText coordinates (same source!)
817
- const boundary = sectionBoundaries.find(b => b.file === section.file);
818
- const isFirstSection = wordSections.indexOf(section) === 0;
819
- const firstBoundaryStart = sectionBoundaries.length > 0 ? Math.min(...sectionBoundaries.map(b => b.start)) : 0;
820
-
821
- const sectionComments = comments.filter((c: any) => {
822
- const anchorData = anchors.get(c.id);
823
- if (!anchorData) return false;
824
-
825
- // Use exact position - no scaling needed since both are in xmlDocText coordinates
826
- if (anchorData.docPosition !== undefined && boundary) {
827
- // Include comments within section boundaries
828
- if (anchorData.docPosition >= boundary.start && anchorData.docPosition < boundary.end) {
829
- return true;
830
- }
831
- // Also include "outside" comments (before first section) in the first section file
832
- if (isFirstSection && anchorData.docPosition < firstBoundaryStart) {
833
- return true;
834
- }
835
- }
836
-
837
- return false;
838
- });
839
-
840
- if (process.env.DEBUG) {
841
- console.log(`[DEBUG] ${section.file}: ${sectionComments.length} comments to place (boundary: ${boundary?.start}-${boundary?.end})`);
842
- }
843
-
844
- if (sectionComments.length > 0) {
845
- // Use a more robust pattern that handles < in comment text
846
- const commentPattern = /\{>>.*?<<\}/gs;
847
- const beforeCount = (annotated.match(commentPattern) || []).length;
848
- annotated = insertCommentsIntoMarkdown(annotated, sectionComments, anchors, {
849
- quiet: !process.env.DEBUG,
850
- sectionBoundary: boundary // Pass section boundary for position-based insertion
851
- });
852
- const afterCount = (annotated.match(commentPattern) || []).length;
853
- commentsInserted = afterCount - beforeCount;
854
-
855
- if (process.env.DEBUG) {
856
- console.log(`[DEBUG] ${section.file}: inserted ${commentsInserted} of ${sectionComments.length} comments`);
857
- }
858
-
859
- if (commentsInserted > 0) {
860
- stats.comments = (stats.comments || 0) + commentsInserted;
861
- }
862
- }
863
- }
864
-
865
- totalChanges += stats.total;
866
-
867
- sectionResults.push({
868
- file: section.file,
869
- header: section.header,
870
- status: 'ok',
871
- stats,
872
- refs: refConversions.length,
873
- });
874
-
875
- if (!options.dryRun) {
876
- fs.writeFileSync(sectionPath, annotated, 'utf-8');
877
- }
878
- }
879
-
880
- const tableRows = sectionResults.map((r) => {
881
- if (r.status === 'skipped') {
882
- return [
883
- chalk.dim(r.file),
884
- chalk.dim(r.header.slice(0, 25)),
885
- chalk.yellow('skipped'),
886
- '',
887
- '',
888
- '',
889
- '',
890
- ];
891
- }
892
- const s = r.stats!;
893
- return [
894
- chalk.bold(r.file),
895
- r.header.length > 25 ? r.header.slice(0, 22) + '...' : r.header,
896
- s.insertions > 0 ? chalk.green(`+${s.insertions}`) : chalk.dim('-'),
897
- s.deletions > 0 ? chalk.red(`-${s.deletions}`) : chalk.dim('-'),
898
- s.substitutions > 0 ? chalk.yellow(`~${s.substitutions}`) : chalk.dim('-'),
899
- s.comments > 0 ? chalk.blue(`#${s.comments}`) : chalk.dim('-'),
900
- r.refs! > 0 ? chalk.magenta(`@${r.refs}`) : chalk.dim('-'),
901
- ];
902
- });
903
-
904
- console.log(fmt.table(
905
- ['File', 'Section', 'Ins', 'Del', 'Sub', 'Cmt', 'Ref'],
906
- tableRows,
907
- { align: ['left', 'left', 'right', 'right', 'right', 'right', 'right'] }
908
- ));
909
- console.log();
910
-
911
- if (options.diff !== false && totalChanges > 0) {
912
- console.log(fmt.header('Changes Preview'));
913
- console.log();
914
- for (const result of sectionResults) {
915
- if (result.status === 'ok' && result.stats && result.stats.total > 0) {
916
- const sectionPath = path.join(options.dir, result.file);
917
- if (fs.existsSync(sectionPath)) {
918
- const content = fs.readFileSync(sectionPath, 'utf-8');
919
- const preview = inlineDiffPreview(content, { maxLines: 3 });
920
- if (preview) {
921
- console.log(chalk.bold(result.file) + ':');
922
- console.log(preview);
923
- console.log();
924
- }
925
- }
926
- }
927
- }
928
- }
929
-
930
- if (options.dryRun) {
931
- console.log(fmt.box(chalk.yellow('Dry run - no files written'), { padding: 0 }));
932
- } else if (totalChanges > 0 || totalRefConversions > 0 || comments.length > 0) {
933
- const summaryLines: string[] = [];
934
- summaryLines.push(`${chalk.bold(wordSections.length)} sections processed`);
935
- if (totalChanges > 0) summaryLines.push(`${chalk.bold(totalChanges)} annotations imported`);
936
- if (comments.length > 0) summaryLines.push(`${chalk.bold(comments.length)} comments placed`);
937
- if (totalRefConversions > 0) summaryLines.push(`${chalk.bold(totalRefConversions)} refs converted to @-syntax`);
938
-
939
- console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
940
- console.log();
941
- console.log(chalk.dim('Next steps:'));
942
- console.log(chalk.dim(' 1. rev review <section.md> - Accept/reject changes'));
943
- console.log(chalk.dim(' 2. rev comments <section.md> - View/address comments'));
944
- console.log(chalk.dim(' 3. rev build docx - Rebuild Word doc'));
945
- } else {
946
- console.log(fmt.status('success', 'No changes detected.'));
947
- }
948
- } catch (err) {
949
- spin.stop();
950
- const error = err as Error;
951
- console.error(fmt.status('error', error.message));
952
- if (process.env.DEBUG) console.error(error.stack);
953
- process.exit(1);
954
- }
955
- });
956
-
957
- // ==========================================================================
958
- // MERGE command - Combine feedback from multiple reviewers (three-way merge)
959
- // ==========================================================================
960
-
961
- program
962
- .command('merge')
963
- .description('Merge feedback from multiple Word documents using three-way merge')
964
- .argument('<docx...>', 'Word documents from reviewers')
965
- .option('-b, --base <file>', 'Base document (original sent to reviewers). Auto-detected if not specified.')
966
- .option('-o, --output <file>', 'Output file (default: writes to section files)')
967
- .option('--names <names>', 'Reviewer names (comma-separated, in order of docx files)')
968
- .option('--strategy <strategy>', 'Conflict resolution: first, latest, or interactive (default)', 'interactive')
969
- .option('--diff-level <level>', 'Diff granularity: sentence or word (default: sentence)', 'sentence')
970
- .option('--dry-run', 'Show conflicts without writing')
971
- .option('--sections', 'Split merged output back to section files')
972
- .action(async (docxFiles: string[], options: MergeOptions) => {
973
- const {
974
- mergeThreeWay,
975
- formatConflict,
976
- resolveConflict,
977
- getBaseDocument,
978
- checkBaseMatch,
979
- saveConflicts,
980
- } = await import('../merge.js');
981
-
982
- // Validate reviewer files exist
983
- for (const docx of docxFiles) {
984
- if (!fs.existsSync(docx)) {
985
- console.error(fmt.status('error', `Reviewer file not found: ${docx}`));
986
- process.exit(1);
987
- }
988
- }
989
-
990
- // Determine base document
991
- let basePath = options.base;
992
- let baseSource = 'specified';
993
-
994
- if (!basePath) {
995
- // Try to use .rev/base.docx
996
- const projectDir = process.cwd();
997
- basePath = getBaseDocument(projectDir) ?? undefined;
998
-
999
- if (basePath) {
1000
- baseSource = 'auto (.rev/base.docx)';
1001
- } else {
1002
- console.log(chalk.yellow('\n No base document found in .rev/base.docx'));
1003
- console.log(chalk.dim(' Tip: Run "rev build docx" to automatically save the base document.\n'));
1004
- console.error(fmt.status('error', 'Base document required. Use --base <file.docx>'));
1005
- process.exit(1);
1006
- }
1007
- }
1008
-
1009
- if (!fs.existsSync(basePath)) {
1010
- console.error(fmt.status('error', `Base document not found: ${basePath}`));
1011
- process.exit(1);
1012
- }
1013
-
1014
- // Check similarity between base and reviewer docs
1015
- const { matches, similarity } = await checkBaseMatch(basePath, docxFiles[0]);
1016
- if (!matches) {
1017
- console.log(chalk.yellow(`\n Warning: Base document may not match reviewer file (${Math.round(similarity * 100)}% similar)`));
1018
- console.log(chalk.dim(' If this is wrong, use --base to specify the correct original document.\n'));
1019
- }
1020
-
1021
- // Parse reviewer names
1022
- const names = options.names
1023
- ? options.names.split(',').map(n => n.trim())
1024
- : docxFiles.map((f, i) => {
1025
- // Try to extract name from filename (e.g., paper_reviewer_A.docx)
1026
- const basename = path.basename(f, '.docx');
1027
- const match = basename.match(/_([A-Za-z]+)$/);
1028
- return match ? match[1] : `Reviewer ${i + 1}`;
1029
- });
1030
-
1031
- // Pad names if needed
1032
- while (names.length < docxFiles.length) {
1033
- names.push(`Reviewer ${names.length + 1}`);
1034
- }
1035
-
1036
- const reviewerDocs = docxFiles.map((p, i) => ({
1037
- path: p,
1038
- name: names[i],
1039
- }));
1040
-
1041
- console.log(fmt.header('Three-Way Merge'));
1042
- console.log();
1043
- console.log(chalk.dim(` Base: ${path.basename(basePath)} (${baseSource})`));
1044
- console.log(chalk.dim(` Reviewers: ${names.join(', ')}`));
1045
- console.log(chalk.dim(` Diff level: ${options.diffLevel}`));
1046
- console.log();
1047
-
1048
- const spin = fmt.spinner('Analyzing changes...').start();
1049
-
1050
- try {
1051
- const { merged, conflicts, stats, baseText } = await mergeThreeWay(basePath, reviewerDocs, {
1052
- diffLevel: options.diffLevel,
1053
- });
1054
-
1055
- spin.stop();
1056
-
1057
- // Display stats
1058
- console.log(fmt.table(['Metric', 'Count'], [
1059
- ['Total changes', stats.totalChanges.toString()],
1060
- ['Non-conflicting', stats.nonConflicting.toString()],
1061
- ['Conflicts', stats.conflicts.toString()],
1062
- ['Comments', stats.comments.toString()],
1063
- ]));
1064
- console.log();
1065
-
1066
- let finalMerged = merged;
1067
-
1068
- // Handle conflicts
1069
- if (conflicts.length > 0) {
1070
- console.log(chalk.yellow(`Found ${conflicts.length} conflict(s):\n`));
1071
-
1072
- if (options.strategy === 'first') {
1073
- // Auto-resolve: take first reviewer's change
1074
- for (const conflict of conflicts) {
1075
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[0].reviewer}'s change`));
1076
- resolveConflict(conflict, 0);
1077
- }
1078
- } else if (options.strategy === 'latest') {
1079
- // Auto-resolve: take last reviewer's change
1080
- for (const conflict of conflicts) {
1081
- const lastIdx = conflict.changes.length - 1;
1082
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[lastIdx].reviewer}'s change`));
1083
- resolveConflict(conflict, lastIdx);
1084
- }
1085
- } else if (!options.dryRun) {
1086
- // Interactive resolution
1087
- for (let i = 0; i < conflicts.length; i++) {
1088
- const conflict = conflicts[i];
1089
- console.log(chalk.bold(`\nConflict ${i + 1}/${conflicts.length} (${conflict.id}):`));
1090
- console.log(formatConflict(conflict, baseText));
1091
- console.log();
1092
-
1093
- const rl = readline.createInterface({
1094
- input: process.stdin,
1095
- output: process.stdout,
1096
- });
1097
-
1098
- const answer = await new Promise<string>((resolve) =>
1099
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip): `), resolve)
1100
- );
1101
- rl.close();
1102
-
1103
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
1104
- const choice = parseInt(answer) - 1;
1105
- if (choice >= 0 && choice < conflict.changes.length) {
1106
- resolveConflict(conflict, choice);
1107
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
1108
- }
1109
- } else {
1110
- console.log(chalk.dim(' Skipped (will need manual resolution)'));
1111
- }
1112
- }
1113
- }
1114
-
1115
- // Save unresolved conflicts for later
1116
- const unresolved = conflicts.filter(c => c.resolved === null);
1117
- if (unresolved.length > 0) {
1118
- saveConflicts(process.cwd(), conflicts, basePath);
1119
- console.log(chalk.yellow(`\n ${unresolved.length} unresolved conflict(s) saved to .rev/conflicts.json`));
1120
- console.log(chalk.dim(' Run "rev conflicts" to view, "rev merge-resolve" to resolve'));
1121
- }
1122
- }
1123
-
1124
- // Write output
1125
- if (!options.dryRun) {
1126
- if (options.output) {
1127
- // Write to single file
1128
- fs.writeFileSync(options.output, finalMerged, 'utf-8');
1129
- console.log(fmt.status('success', `Merged output written to ${options.output}`));
1130
- } else if (options.sections) {
1131
- // Split to section files (TODO: implement section splitting)
1132
- console.log(chalk.yellow(' Section splitting not yet implemented'));
1133
- console.log(chalk.dim(' Use -o to specify output file'));
1134
- } else {
1135
- // Default: write to merged.md
1136
- const outPath = 'merged.md';
1137
- fs.writeFileSync(outPath, finalMerged, 'utf-8');
1138
- console.log(fmt.status('success', `Merged output written to ${outPath}`));
1139
- }
1140
-
1141
- console.log();
1142
- console.log(chalk.dim('Next steps:'));
1143
- console.log(chalk.dim(' 1. rev review merged.md - Accept/reject changes'));
1144
- console.log(chalk.dim(' 2. rev comments merged.md - Address comments'));
1145
- if (conflicts.some(c => c.resolved === null)) {
1146
- console.log(chalk.dim(' 3. rev merge-resolve - Resolve remaining conflicts'));
1147
- }
1148
- } else {
1149
- console.log(fmt.status('info', 'Dry run - no output written'));
1150
- }
1151
- } catch (err) {
1152
- spin.stop();
1153
- const error = err as Error;
1154
- console.error(fmt.status('error', error.message));
1155
- if (process.env.DEBUG) console.error(error.stack);
1156
- process.exit(1);
1157
- }
1158
- });
1159
-
1160
- // ==========================================================================
1161
- // CONFLICTS command - List unresolved conflicts
1162
- // ==========================================================================
1163
-
1164
- program
1165
- .command('conflicts')
1166
- .description('List unresolved merge conflicts')
1167
- .action(async () => {
1168
- const { loadConflicts, formatConflict } = await import('../merge.js');
1169
- const projectDir = process.cwd();
1170
- const data = loadConflicts(projectDir);
1171
-
1172
- if (!data) {
1173
- console.log(fmt.status('info', 'No conflicts file found'));
1174
- return;
1175
- }
1176
-
1177
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
1178
-
1179
- if (unresolved.length === 0) {
1180
- console.log(fmt.status('success', 'All conflicts resolved!'));
1181
- return;
1182
- }
1183
-
1184
- console.log(fmt.header(`Unresolved Conflicts (${unresolved.length})`));
1185
- console.log();
1186
- console.log(chalk.dim(` Base: ${data.base}`));
1187
- console.log(chalk.dim(` Merged: ${data.merged}`));
1188
- console.log();
1189
-
1190
- for (const conflict of unresolved) {
1191
- console.log(chalk.bold(`Conflict ${conflict.id}:`));
1192
- // Show abbreviated info
1193
- console.log(chalk.dim(` Original: "${conflict.original.slice(0, 50)}${conflict.original.length > 50 ? '...' : ''}"`));
1194
- console.log(chalk.dim(` Options: ${conflict.changes.map((c: any) => c.reviewer).join(', ')}`));
1195
- console.log();
1196
- }
1197
-
1198
- console.log(chalk.dim('Run "rev merge-resolve" to resolve conflicts interactively'));
1199
- });
1200
-
1201
- // ==========================================================================
1202
- // MERGE-RESOLVE command - Interactively resolve merge conflicts
1203
- // ==========================================================================
1204
-
1205
- program
1206
- .command('merge-resolve')
1207
- .alias('mresolve')
1208
- .description('Resolve merge conflicts interactively')
1209
- .option('--theirs', 'Accept all changes from last reviewer')
1210
- .option('--ours', 'Accept all changes from first reviewer')
1211
- .action(async (options: { theirs?: boolean; ours?: boolean }) => {
1212
- const { loadConflicts, saveConflicts, clearConflicts, resolveConflict, formatConflict } = await import('../merge.js');
1213
- const projectDir = process.cwd();
1214
- const data = loadConflicts(projectDir);
1215
-
1216
- if (!data) {
1217
- console.log(fmt.status('info', 'No conflicts to resolve'));
1218
- return;
1219
- }
1220
-
1221
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
1222
-
1223
- if (unresolved.length === 0) {
1224
- console.log(fmt.status('success', 'All conflicts already resolved!'));
1225
- clearConflicts(projectDir);
1226
- return;
1227
- }
1228
-
1229
- console.log(fmt.header(`Resolving ${unresolved.length} Conflict(s)`));
1230
- console.log();
1231
-
1232
- if (options.theirs) {
1233
- // Accept all from last reviewer
1234
- for (const conflict of unresolved) {
1235
- const lastIdx = conflict.changes.length - 1;
1236
- resolveConflict(conflict, lastIdx);
1237
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[lastIdx].reviewer}'s change`));
1238
- }
1239
- saveConflicts(projectDir, data.conflicts, data.base);
1240
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--theirs)`));
1241
- } else if (options.ours) {
1242
- // Accept all from first reviewer
1243
- for (const conflict of unresolved) {
1244
- resolveConflict(conflict, 0);
1245
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[0].reviewer}'s change`));
1246
- }
1247
- saveConflicts(projectDir, data.conflicts, data.base);
1248
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--ours)`));
1249
- } else {
1250
- // Interactive resolution
1251
- // Read base text for context display
1252
- let baseText = '';
1253
- try {
1254
- const { extractFromWord } = await import('../import.js');
1255
- const { text } = await extractFromWord(data.base);
1256
- baseText = text;
1257
- } catch {
1258
- // Can't read base, show without context
1259
- }
1260
-
1261
- for (let i = 0; i < unresolved.length; i++) {
1262
- const conflict = unresolved[i];
1263
- console.log(chalk.bold(`\nConflict ${i + 1}/${unresolved.length} (${conflict.id}):`));
1264
- console.log(formatConflict(conflict, baseText));
1265
- console.log();
1266
-
1267
- const rl = readline.createInterface({
1268
- input: process.stdin,
1269
- output: process.stdout,
1270
- });
1271
-
1272
- const answer = await new Promise<string>((resolve) =>
1273
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip, q=quit): `), resolve)
1274
- );
1275
- rl.close();
1276
-
1277
- if (answer.toLowerCase() === 'q') {
1278
- console.log(chalk.dim('\n Saving progress...'));
1279
- break;
1280
- }
1281
-
1282
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
1283
- const choice = parseInt(answer) - 1;
1284
- if (choice >= 0 && choice < conflict.changes.length) {
1285
- resolveConflict(conflict, choice);
1286
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
1287
- }
1288
- } else {
1289
- console.log(chalk.dim(' Skipped'));
1290
- }
1291
- }
1292
-
1293
- saveConflicts(projectDir, data.conflicts, data.base);
1294
-
1295
- const remaining = data.conflicts.filter((c: any) => c.resolved === null).length;
1296
- if (remaining === 0) {
1297
- console.log(fmt.status('success', '\nAll conflicts resolved!'));
1298
- clearConflicts(projectDir);
1299
- } else {
1300
- console.log(chalk.yellow(`\n ${remaining} conflict(s) remaining`));
1301
- }
1302
- }
1303
- });
1304
-
1305
451
  }