docrev 0.9.5 → 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 (76) hide show
  1. package/dist/lib/commands/file-ops.d.ts +11 -0
  2. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  3. package/dist/lib/commands/file-ops.js +301 -0
  4. package/dist/lib/commands/file-ops.js.map +1 -0
  5. package/dist/lib/commands/index.d.ts +9 -1
  6. package/dist/lib/commands/index.d.ts.map +1 -1
  7. package/dist/lib/commands/index.js +17 -1
  8. package/dist/lib/commands/index.js.map +1 -1
  9. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  10. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  11. package/dist/lib/commands/merge-resolve.js +318 -0
  12. package/dist/lib/commands/merge-resolve.js.map +1 -0
  13. package/dist/lib/commands/preview.d.ts +11 -0
  14. package/dist/lib/commands/preview.d.ts.map +1 -0
  15. package/dist/lib/commands/preview.js +138 -0
  16. package/dist/lib/commands/preview.js.map +1 -0
  17. package/dist/lib/commands/project-info.d.ts +11 -0
  18. package/dist/lib/commands/project-info.d.ts.map +1 -0
  19. package/dist/lib/commands/project-info.js +187 -0
  20. package/dist/lib/commands/project-info.js.map +1 -0
  21. package/dist/lib/commands/quality.d.ts +11 -0
  22. package/dist/lib/commands/quality.d.ts.map +1 -0
  23. package/dist/lib/commands/quality.js +384 -0
  24. package/dist/lib/commands/quality.js.map +1 -0
  25. package/dist/lib/commands/sections.d.ts +3 -2
  26. package/dist/lib/commands/sections.d.ts.map +1 -1
  27. package/dist/lib/commands/sections.js +4 -736
  28. package/dist/lib/commands/sections.js.map +1 -1
  29. package/dist/lib/commands/sync.d.ts +11 -0
  30. package/dist/lib/commands/sync.d.ts.map +1 -0
  31. package/dist/lib/commands/sync.js +441 -0
  32. package/dist/lib/commands/sync.js.map +1 -0
  33. package/dist/lib/commands/text-ops.d.ts +11 -0
  34. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  35. package/dist/lib/commands/text-ops.js +357 -0
  36. package/dist/lib/commands/text-ops.js.map +1 -0
  37. package/dist/lib/commands/utilities.d.ts +2 -4
  38. package/dist/lib/commands/utilities.d.ts.map +1 -1
  39. package/dist/lib/commands/utilities.js +3 -1572
  40. package/dist/lib/commands/utilities.js.map +1 -1
  41. package/dist/lib/commands/word-tools.d.ts +11 -0
  42. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  43. package/dist/lib/commands/word-tools.js +272 -0
  44. package/dist/lib/commands/word-tools.js.map +1 -0
  45. package/dist/lib/diff-engine.d.ts +25 -0
  46. package/dist/lib/diff-engine.d.ts.map +1 -0
  47. package/dist/lib/diff-engine.js +354 -0
  48. package/dist/lib/diff-engine.js.map +1 -0
  49. package/dist/lib/import.d.ts +37 -117
  50. package/dist/lib/import.d.ts.map +1 -1
  51. package/dist/lib/import.js +10 -1030
  52. package/dist/lib/import.js.map +1 -1
  53. package/dist/lib/restore-references.d.ts +35 -0
  54. package/dist/lib/restore-references.d.ts.map +1 -0
  55. package/dist/lib/restore-references.js +188 -0
  56. package/dist/lib/restore-references.js.map +1 -0
  57. package/dist/lib/word-extraction.d.ts +77 -0
  58. package/dist/lib/word-extraction.d.ts.map +1 -0
  59. package/dist/lib/word-extraction.js +515 -0
  60. package/dist/lib/word-extraction.js.map +1 -0
  61. package/lib/commands/file-ops.ts +372 -0
  62. package/lib/commands/index.ts +24 -0
  63. package/lib/commands/merge-resolve.ts +378 -0
  64. package/lib/commands/preview.ts +178 -0
  65. package/lib/commands/project-info.ts +244 -0
  66. package/lib/commands/quality.ts +517 -0
  67. package/lib/commands/sections.ts +3 -870
  68. package/lib/commands/sync.ts +536 -0
  69. package/lib/commands/text-ops.ts +449 -0
  70. package/lib/commands/utilities.ts +62 -2043
  71. package/lib/commands/word-tools.ts +340 -0
  72. package/lib/diff-engine.ts +465 -0
  73. package/lib/import.ts +78 -1338
  74. package/lib/restore-references.ts +240 -0
  75. package/lib/word-extraction.ts +666 -0
  76. 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,846 +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
- // Preserve any preamble content (YAML frontmatter, author blocks, metadata)
877
- // that exists before the first heading in the original file.
878
- // This content is never included in the Word build output, so it won't
879
- // appear in the Word doc and would otherwise be lost during sync.
880
- const originalContent = fs.readFileSync(sectionPath, 'utf-8');
881
- const firstHeadingMatch = originalContent.match(/^(#\s)/m);
882
- if (firstHeadingMatch && firstHeadingMatch.index !== undefined && firstHeadingMatch.index > 0) {
883
- const preamble = originalContent.slice(0, firstHeadingMatch.index);
884
- // Only prepend if preamble has non-whitespace content
885
- if (preamble.trim().length > 0) {
886
- annotated = preamble + annotated;
887
- }
888
- }
889
- fs.writeFileSync(sectionPath, annotated, 'utf-8');
890
- }
891
- }
892
-
893
- const tableRows = sectionResults.map((r) => {
894
- if (r.status === 'skipped') {
895
- return [
896
- chalk.dim(r.file),
897
- chalk.dim(r.header.slice(0, 25)),
898
- chalk.yellow('skipped'),
899
- '',
900
- '',
901
- '',
902
- '',
903
- ];
904
- }
905
- const s = r.stats!;
906
- return [
907
- chalk.bold(r.file),
908
- r.header.length > 25 ? r.header.slice(0, 22) + '...' : r.header,
909
- s.insertions > 0 ? chalk.green(`+${s.insertions}`) : chalk.dim('-'),
910
- s.deletions > 0 ? chalk.red(`-${s.deletions}`) : chalk.dim('-'),
911
- s.substitutions > 0 ? chalk.yellow(`~${s.substitutions}`) : chalk.dim('-'),
912
- s.comments > 0 ? chalk.blue(`#${s.comments}`) : chalk.dim('-'),
913
- r.refs! > 0 ? chalk.magenta(`@${r.refs}`) : chalk.dim('-'),
914
- ];
915
- });
916
-
917
- console.log(fmt.table(
918
- ['File', 'Section', 'Ins', 'Del', 'Sub', 'Cmt', 'Ref'],
919
- tableRows,
920
- { align: ['left', 'left', 'right', 'right', 'right', 'right', 'right'] }
921
- ));
922
- console.log();
923
-
924
- if (options.diff !== false && totalChanges > 0) {
925
- console.log(fmt.header('Changes Preview'));
926
- console.log();
927
- for (const result of sectionResults) {
928
- if (result.status === 'ok' && result.stats && result.stats.total > 0) {
929
- const sectionPath = path.join(options.dir, result.file);
930
- if (fs.existsSync(sectionPath)) {
931
- const content = fs.readFileSync(sectionPath, 'utf-8');
932
- const preview = inlineDiffPreview(content, { maxLines: 3 });
933
- if (preview) {
934
- console.log(chalk.bold(result.file) + ':');
935
- console.log(preview);
936
- console.log();
937
- }
938
- }
939
- }
940
- }
941
- }
942
-
943
- if (options.dryRun) {
944
- console.log(fmt.box(chalk.yellow('Dry run - no files written'), { padding: 0 }));
945
- } else if (totalChanges > 0 || totalRefConversions > 0 || comments.length > 0) {
946
- const summaryLines: string[] = [];
947
- summaryLines.push(`${chalk.bold(wordSections.length)} sections processed`);
948
- if (totalChanges > 0) summaryLines.push(`${chalk.bold(totalChanges)} annotations imported`);
949
- if (comments.length > 0) summaryLines.push(`${chalk.bold(comments.length)} comments placed`);
950
- if (totalRefConversions > 0) summaryLines.push(`${chalk.bold(totalRefConversions)} refs converted to @-syntax`);
951
-
952
- console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
953
- console.log();
954
- console.log(chalk.dim('Next steps:'));
955
- console.log(chalk.dim(' 1. rev review <section.md> - Accept/reject changes'));
956
- console.log(chalk.dim(' 2. rev comments <section.md> - View/address comments'));
957
- console.log(chalk.dim(' 3. rev build docx - Rebuild Word doc'));
958
- } else {
959
- console.log(fmt.status('success', 'No changes detected.'));
960
- }
961
- } catch (err) {
962
- spin.stop();
963
- const error = err as Error;
964
- console.error(fmt.status('error', error.message));
965
- if (process.env.DEBUG) console.error(error.stack);
966
- process.exit(1);
967
- }
968
- });
969
-
970
- // ==========================================================================
971
- // MERGE command - Combine feedback from multiple reviewers (three-way merge)
972
- // ==========================================================================
973
-
974
- program
975
- .command('merge')
976
- .description('Merge feedback from multiple Word documents using three-way merge')
977
- .argument('<docx...>', 'Word documents from reviewers')
978
- .option('-b, --base <file>', 'Base document (original sent to reviewers). Auto-detected if not specified.')
979
- .option('-o, --output <file>', 'Output file (default: writes to section files)')
980
- .option('--names <names>', 'Reviewer names (comma-separated, in order of docx files)')
981
- .option('--strategy <strategy>', 'Conflict resolution: first, latest, or interactive (default)', 'interactive')
982
- .option('--diff-level <level>', 'Diff granularity: sentence or word (default: sentence)', 'sentence')
983
- .option('--dry-run', 'Show conflicts without writing')
984
- .option('--sections', 'Split merged output back to section files')
985
- .action(async (docxFiles: string[], options: MergeOptions) => {
986
- const {
987
- mergeThreeWay,
988
- formatConflict,
989
- resolveConflict,
990
- getBaseDocument,
991
- checkBaseMatch,
992
- saveConflicts,
993
- } = await import('../merge.js');
994
-
995
- // Validate reviewer files exist
996
- for (const docx of docxFiles) {
997
- if (!fs.existsSync(docx)) {
998
- console.error(fmt.status('error', `Reviewer file not found: ${docx}`));
999
- process.exit(1);
1000
- }
1001
- }
1002
-
1003
- // Determine base document
1004
- let basePath = options.base;
1005
- let baseSource = 'specified';
1006
-
1007
- if (!basePath) {
1008
- // Try to use .rev/base.docx
1009
- const projectDir = process.cwd();
1010
- basePath = getBaseDocument(projectDir) ?? undefined;
1011
-
1012
- if (basePath) {
1013
- baseSource = 'auto (.rev/base.docx)';
1014
- } else {
1015
- console.log(chalk.yellow('\n No base document found in .rev/base.docx'));
1016
- console.log(chalk.dim(' Tip: Run "rev build docx" to automatically save the base document.\n'));
1017
- console.error(fmt.status('error', 'Base document required. Use --base <file.docx>'));
1018
- process.exit(1);
1019
- }
1020
- }
1021
-
1022
- if (!fs.existsSync(basePath)) {
1023
- console.error(fmt.status('error', `Base document not found: ${basePath}`));
1024
- process.exit(1);
1025
- }
1026
-
1027
- // Check similarity between base and reviewer docs
1028
- const { matches, similarity } = await checkBaseMatch(basePath, docxFiles[0]);
1029
- if (!matches) {
1030
- console.log(chalk.yellow(`\n Warning: Base document may not match reviewer file (${Math.round(similarity * 100)}% similar)`));
1031
- console.log(chalk.dim(' If this is wrong, use --base to specify the correct original document.\n'));
1032
- }
1033
-
1034
- // Parse reviewer names
1035
- const names = options.names
1036
- ? options.names.split(',').map(n => n.trim())
1037
- : docxFiles.map((f, i) => {
1038
- // Try to extract name from filename (e.g., paper_reviewer_A.docx)
1039
- const basename = path.basename(f, '.docx');
1040
- const match = basename.match(/_([A-Za-z]+)$/);
1041
- return match ? match[1] : `Reviewer ${i + 1}`;
1042
- });
1043
-
1044
- // Pad names if needed
1045
- while (names.length < docxFiles.length) {
1046
- names.push(`Reviewer ${names.length + 1}`);
1047
- }
1048
-
1049
- const reviewerDocs = docxFiles.map((p, i) => ({
1050
- path: p,
1051
- name: names[i],
1052
- }));
1053
-
1054
- console.log(fmt.header('Three-Way Merge'));
1055
- console.log();
1056
- console.log(chalk.dim(` Base: ${path.basename(basePath)} (${baseSource})`));
1057
- console.log(chalk.dim(` Reviewers: ${names.join(', ')}`));
1058
- console.log(chalk.dim(` Diff level: ${options.diffLevel}`));
1059
- console.log();
1060
-
1061
- const spin = fmt.spinner('Analyzing changes...').start();
1062
-
1063
- try {
1064
- const { merged, conflicts, stats, baseText } = await mergeThreeWay(basePath, reviewerDocs, {
1065
- diffLevel: options.diffLevel,
1066
- });
1067
-
1068
- spin.stop();
1069
-
1070
- // Display stats
1071
- console.log(fmt.table(['Metric', 'Count'], [
1072
- ['Total changes', stats.totalChanges.toString()],
1073
- ['Non-conflicting', stats.nonConflicting.toString()],
1074
- ['Conflicts', stats.conflicts.toString()],
1075
- ['Comments', stats.comments.toString()],
1076
- ]));
1077
- console.log();
1078
-
1079
- let finalMerged = merged;
1080
-
1081
- // Handle conflicts
1082
- if (conflicts.length > 0) {
1083
- console.log(chalk.yellow(`Found ${conflicts.length} conflict(s):\n`));
1084
-
1085
- if (options.strategy === 'first') {
1086
- // Auto-resolve: take first reviewer's change
1087
- for (const conflict of conflicts) {
1088
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[0].reviewer}'s change`));
1089
- resolveConflict(conflict, 0);
1090
- }
1091
- } else if (options.strategy === 'latest') {
1092
- // Auto-resolve: take last reviewer's change
1093
- for (const conflict of conflicts) {
1094
- const lastIdx = conflict.changes.length - 1;
1095
- console.log(chalk.dim(` Conflict ${conflict.id}: using ${conflict.changes[lastIdx].reviewer}'s change`));
1096
- resolveConflict(conflict, lastIdx);
1097
- }
1098
- } else if (!options.dryRun) {
1099
- // Interactive resolution
1100
- for (let i = 0; i < conflicts.length; i++) {
1101
- const conflict = conflicts[i];
1102
- console.log(chalk.bold(`\nConflict ${i + 1}/${conflicts.length} (${conflict.id}):`));
1103
- console.log(formatConflict(conflict, baseText));
1104
- console.log();
1105
-
1106
- const rl = readline.createInterface({
1107
- input: process.stdin,
1108
- output: process.stdout,
1109
- });
1110
-
1111
- const answer = await new Promise<string>((resolve) =>
1112
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip): `), resolve)
1113
- );
1114
- rl.close();
1115
-
1116
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
1117
- const choice = parseInt(answer) - 1;
1118
- if (choice >= 0 && choice < conflict.changes.length) {
1119
- resolveConflict(conflict, choice);
1120
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
1121
- }
1122
- } else {
1123
- console.log(chalk.dim(' Skipped (will need manual resolution)'));
1124
- }
1125
- }
1126
- }
1127
-
1128
- // Save unresolved conflicts for later
1129
- const unresolved = conflicts.filter(c => c.resolved === null);
1130
- if (unresolved.length > 0) {
1131
- saveConflicts(process.cwd(), conflicts, basePath);
1132
- console.log(chalk.yellow(`\n ${unresolved.length} unresolved conflict(s) saved to .rev/conflicts.json`));
1133
- console.log(chalk.dim(' Run "rev conflicts" to view, "rev merge-resolve" to resolve'));
1134
- }
1135
- }
1136
-
1137
- // Write output
1138
- if (!options.dryRun) {
1139
- if (options.output) {
1140
- // Write to single file
1141
- fs.writeFileSync(options.output, finalMerged, 'utf-8');
1142
- console.log(fmt.status('success', `Merged output written to ${options.output}`));
1143
- } else if (options.sections) {
1144
- // Split to section files (TODO: implement section splitting)
1145
- console.log(chalk.yellow(' Section splitting not yet implemented'));
1146
- console.log(chalk.dim(' Use -o to specify output file'));
1147
- } else {
1148
- // Default: write to merged.md
1149
- const outPath = 'merged.md';
1150
- fs.writeFileSync(outPath, finalMerged, 'utf-8');
1151
- console.log(fmt.status('success', `Merged output written to ${outPath}`));
1152
- }
1153
-
1154
- console.log();
1155
- console.log(chalk.dim('Next steps:'));
1156
- console.log(chalk.dim(' 1. rev review merged.md - Accept/reject changes'));
1157
- console.log(chalk.dim(' 2. rev comments merged.md - Address comments'));
1158
- if (conflicts.some(c => c.resolved === null)) {
1159
- console.log(chalk.dim(' 3. rev merge-resolve - Resolve remaining conflicts'));
1160
- }
1161
- } else {
1162
- console.log(fmt.status('info', 'Dry run - no output written'));
1163
- }
1164
- } catch (err) {
1165
- spin.stop();
1166
- const error = err as Error;
1167
- console.error(fmt.status('error', error.message));
1168
- if (process.env.DEBUG) console.error(error.stack);
1169
- process.exit(1);
1170
- }
1171
- });
1172
-
1173
- // ==========================================================================
1174
- // CONFLICTS command - List unresolved conflicts
1175
- // ==========================================================================
1176
-
1177
- program
1178
- .command('conflicts')
1179
- .description('List unresolved merge conflicts')
1180
- .action(async () => {
1181
- const { loadConflicts, formatConflict } = await import('../merge.js');
1182
- const projectDir = process.cwd();
1183
- const data = loadConflicts(projectDir);
1184
-
1185
- if (!data) {
1186
- console.log(fmt.status('info', 'No conflicts file found'));
1187
- return;
1188
- }
1189
-
1190
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
1191
-
1192
- if (unresolved.length === 0) {
1193
- console.log(fmt.status('success', 'All conflicts resolved!'));
1194
- return;
1195
- }
1196
-
1197
- console.log(fmt.header(`Unresolved Conflicts (${unresolved.length})`));
1198
- console.log();
1199
- console.log(chalk.dim(` Base: ${data.base}`));
1200
- console.log(chalk.dim(` Merged: ${data.merged}`));
1201
- console.log();
1202
-
1203
- for (const conflict of unresolved) {
1204
- console.log(chalk.bold(`Conflict ${conflict.id}:`));
1205
- // Show abbreviated info
1206
- console.log(chalk.dim(` Original: "${conflict.original.slice(0, 50)}${conflict.original.length > 50 ? '...' : ''}"`));
1207
- console.log(chalk.dim(` Options: ${conflict.changes.map((c: any) => c.reviewer).join(', ')}`));
1208
- console.log();
1209
- }
1210
-
1211
- console.log(chalk.dim('Run "rev merge-resolve" to resolve conflicts interactively'));
1212
- });
1213
-
1214
- // ==========================================================================
1215
- // MERGE-RESOLVE command - Interactively resolve merge conflicts
1216
- // ==========================================================================
1217
-
1218
- program
1219
- .command('merge-resolve')
1220
- .alias('mresolve')
1221
- .description('Resolve merge conflicts interactively')
1222
- .option('--theirs', 'Accept all changes from last reviewer')
1223
- .option('--ours', 'Accept all changes from first reviewer')
1224
- .action(async (options: { theirs?: boolean; ours?: boolean }) => {
1225
- const { loadConflicts, saveConflicts, clearConflicts, resolveConflict, formatConflict } = await import('../merge.js');
1226
- const projectDir = process.cwd();
1227
- const data = loadConflicts(projectDir);
1228
-
1229
- if (!data) {
1230
- console.log(fmt.status('info', 'No conflicts to resolve'));
1231
- return;
1232
- }
1233
-
1234
- const unresolved = data.conflicts.filter((c: any) => c.resolved === null);
1235
-
1236
- if (unresolved.length === 0) {
1237
- console.log(fmt.status('success', 'All conflicts already resolved!'));
1238
- clearConflicts(projectDir);
1239
- return;
1240
- }
1241
-
1242
- console.log(fmt.header(`Resolving ${unresolved.length} Conflict(s)`));
1243
- console.log();
1244
-
1245
- if (options.theirs) {
1246
- // Accept all from last reviewer
1247
- for (const conflict of unresolved) {
1248
- const lastIdx = conflict.changes.length - 1;
1249
- resolveConflict(conflict, lastIdx);
1250
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[lastIdx].reviewer}'s change`));
1251
- }
1252
- saveConflicts(projectDir, data.conflicts, data.base);
1253
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--theirs)`));
1254
- } else if (options.ours) {
1255
- // Accept all from first reviewer
1256
- for (const conflict of unresolved) {
1257
- resolveConflict(conflict, 0);
1258
- console.log(chalk.dim(` ${conflict.id}: accepted ${conflict.changes[0].reviewer}'s change`));
1259
- }
1260
- saveConflicts(projectDir, data.conflicts, data.base);
1261
- console.log(fmt.status('success', `Resolved ${unresolved.length} conflicts (--ours)`));
1262
- } else {
1263
- // Interactive resolution
1264
- // Read base text for context display
1265
- let baseText = '';
1266
- try {
1267
- const { extractFromWord } = await import('../import.js');
1268
- const { text } = await extractFromWord(data.base);
1269
- baseText = text;
1270
- } catch {
1271
- // Can't read base, show without context
1272
- }
1273
-
1274
- for (let i = 0; i < unresolved.length; i++) {
1275
- const conflict = unresolved[i];
1276
- console.log(chalk.bold(`\nConflict ${i + 1}/${unresolved.length} (${conflict.id}):`));
1277
- console.log(formatConflict(conflict, baseText));
1278
- console.log();
1279
-
1280
- const rl = readline.createInterface({
1281
- input: process.stdin,
1282
- output: process.stdout,
1283
- });
1284
-
1285
- const answer = await new Promise<string>((resolve) =>
1286
- rl.question(chalk.cyan(` Choose (1-${conflict.changes.length}, s=skip, q=quit): `), resolve)
1287
- );
1288
- rl.close();
1289
-
1290
- if (answer.toLowerCase() === 'q') {
1291
- console.log(chalk.dim('\n Saving progress...'));
1292
- break;
1293
- }
1294
-
1295
- if (answer.toLowerCase() !== 's' && !isNaN(parseInt(answer))) {
1296
- const choice = parseInt(answer) - 1;
1297
- if (choice >= 0 && choice < conflict.changes.length) {
1298
- resolveConflict(conflict, choice);
1299
- console.log(chalk.green(` ✓ Applied: ${conflict.changes[choice].reviewer}'s change`));
1300
- }
1301
- } else {
1302
- console.log(chalk.dim(' Skipped'));
1303
- }
1304
- }
1305
-
1306
- saveConflicts(projectDir, data.conflicts, data.base);
1307
-
1308
- const remaining = data.conflicts.filter((c: any) => c.resolved === null).length;
1309
- if (remaining === 0) {
1310
- console.log(fmt.status('success', '\nAll conflicts resolved!'));
1311
- clearConflicts(projectDir);
1312
- } else {
1313
- console.log(chalk.yellow(`\n ${remaining} conflict(s) remaining`));
1314
- }
1315
- }
1316
- });
1317
-
1318
451
  }