docrev 0.10.1 → 0.10.2

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 (119) 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 +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +47 -17
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/sync.d.ts.map +1 -1
  16. package/dist/lib/commands/sync.js +78 -100
  17. package/dist/lib/commands/sync.js.map +1 -1
  18. package/dist/lib/commands/utilities.js +164 -164
  19. package/dist/lib/commands/word-tools.js +8 -8
  20. package/dist/lib/grammar.js +3 -3
  21. package/dist/lib/macro-filter.lua +201 -201
  22. package/dist/lib/pdf-comments.js +44 -44
  23. package/dist/lib/plugins.js +57 -57
  24. package/dist/lib/pptx-color-filter.lua +37 -37
  25. package/dist/lib/pptx-themes.js +115 -115
  26. package/dist/lib/sections.d.ts.map +1 -1
  27. package/dist/lib/sections.js +5 -2
  28. package/dist/lib/sections.js.map +1 -1
  29. package/dist/lib/spelling.js +2 -2
  30. package/dist/lib/templates.js +387 -387
  31. package/dist/lib/themes.js +51 -51
  32. package/eslint.config.js +27 -27
  33. package/issues.md +180 -0
  34. package/lib/anchor-match.ts +308 -276
  35. package/lib/annotations.ts +644 -644
  36. package/lib/build.ts +1766 -1766
  37. package/lib/citations.ts +160 -160
  38. package/lib/commands/build.ts +855 -855
  39. package/lib/commands/citations.ts +515 -515
  40. package/lib/commands/comments.ts +1050 -1050
  41. package/lib/commands/context.ts +176 -176
  42. package/lib/commands/core.ts +309 -309
  43. package/lib/commands/doi.ts +435 -435
  44. package/lib/commands/file-ops.ts +372 -372
  45. package/lib/commands/history.ts +320 -320
  46. package/lib/commands/index.ts +87 -87
  47. package/lib/commands/init.ts +259 -259
  48. package/lib/commands/merge-resolve.ts +378 -378
  49. package/lib/commands/preview.ts +178 -178
  50. package/lib/commands/project-info.ts +244 -244
  51. package/lib/commands/quality.ts +517 -517
  52. package/lib/commands/response.ts +454 -454
  53. package/lib/commands/section-boundaries.ts +82 -82
  54. package/lib/commands/sections.ts +451 -451
  55. package/lib/commands/sync.ts +676 -709
  56. package/lib/commands/text-ops.ts +449 -449
  57. package/lib/commands/utilities.ts +448 -448
  58. package/lib/commands/verify-anchors.ts +272 -272
  59. package/lib/commands/word-tools.ts +340 -340
  60. package/lib/comment-realign.ts +517 -517
  61. package/lib/config.ts +84 -84
  62. package/lib/crossref.ts +781 -781
  63. package/lib/csl.ts +191 -191
  64. package/lib/dependencies.ts +98 -98
  65. package/lib/diff-engine.ts +465 -465
  66. package/lib/doi-cache.ts +115 -115
  67. package/lib/doi.ts +897 -897
  68. package/lib/equations.ts +506 -506
  69. package/lib/errors.ts +346 -346
  70. package/lib/format.ts +541 -541
  71. package/lib/git.ts +326 -326
  72. package/lib/grammar.ts +303 -303
  73. package/lib/image-registry.ts +180 -180
  74. package/lib/import.ts +911 -911
  75. package/lib/journals.ts +543 -543
  76. package/lib/macro-filter.lua +201 -201
  77. package/lib/macros.ts +273 -273
  78. package/lib/merge.ts +633 -633
  79. package/lib/orcid.ts +144 -144
  80. package/lib/pdf-comments.ts +263 -263
  81. package/lib/pdf-import.ts +524 -524
  82. package/lib/plugins.ts +362 -362
  83. package/lib/postprocess.ts +188 -188
  84. package/lib/pptx-color-filter.lua +37 -37
  85. package/lib/pptx-template.ts +469 -469
  86. package/lib/pptx-themes.ts +483 -483
  87. package/lib/protect-restore.ts +520 -520
  88. package/lib/rate-limiter.ts +94 -94
  89. package/lib/response.ts +197 -197
  90. package/lib/restore-references.ts +240 -240
  91. package/lib/review.ts +327 -327
  92. package/lib/schema.ts +488 -488
  93. package/lib/scientific-words.ts +73 -73
  94. package/lib/sections.ts +428 -425
  95. package/lib/slides.ts +756 -756
  96. package/lib/spelling.ts +334 -334
  97. package/lib/templates.ts +526 -526
  98. package/lib/themes.ts +742 -742
  99. package/lib/trackchanges.ts +247 -247
  100. package/lib/tui.ts +450 -450
  101. package/lib/types.ts +550 -550
  102. package/lib/undo.ts +250 -250
  103. package/lib/utils.ts +69 -69
  104. package/lib/variables.ts +179 -179
  105. package/lib/word-extraction.ts +806 -806
  106. package/lib/word.ts +643 -643
  107. package/lib/wordcomments.ts +840 -840
  108. package/package.json +137 -137
  109. package/scripts/postbuild.js +47 -47
  110. package/site/assets/extra.css +208 -0
  111. package/site/commands.html +926 -0
  112. package/site/configuration.html +469 -0
  113. package/site/index.html +288 -0
  114. package/site/troubleshooting.html +461 -0
  115. package/site/workflow.html +518 -0
  116. package/skill/REFERENCE.md +539 -539
  117. package/skill/SKILL.md +295 -295
  118. package/tsconfig.json +26 -26
  119. package/types/index.d.ts +525 -525
@@ -1,709 +1,676 @@
1
- /**
2
- * SYNC command: Import feedback from Word/PDF back to section files
3
- *
4
- * Split from sections.ts for maintainability.
5
- */
6
-
7
- import {
8
- chalk,
9
- fs,
10
- path,
11
- fmt,
12
- findFiles,
13
- resolveSectionsConfig,
14
- getOrderedSections,
15
- extractSectionsFromText,
16
- countAnnotations,
17
- buildRegistry,
18
- convertHardcodedRefs,
19
- inlineDiffPreview,
20
- } from './context.js';
21
- import type { Command } from 'commander';
22
- import type { SectionsConfig } from '../types.js';
23
- import * as readline from 'readline';
24
-
25
- interface ImportStats {
26
- insertions: number;
27
- deletions: number;
28
- substitutions: number;
29
- comments: number;
30
- total: number;
31
- }
32
-
33
- interface SyncOptions {
34
- config: string;
35
- dir: string;
36
- crossref?: boolean;
37
- diff?: boolean;
38
- force?: boolean;
39
- dryRun?: boolean;
40
- /** Commander maps `--comments-only` (a positive flag) cleanly. `--no-overwrite`
41
- * conflicts with the existing `overwrite` semantics in `--force`-style flags
42
- * and Commander's `--no-X` convention assigns `options.x === false`. */
43
- commentsOnly?: boolean;
44
- }
45
-
46
- /**
47
- * Register the sync command with the program
48
- */
49
- export function register(program: Command): void {
50
- // ==========================================================================
51
- // SYNC command - Import with section awareness
52
- // ==========================================================================
53
-
54
- program
55
- .command('sync')
56
- .alias('sections')
57
- .description('Sync feedback from Word/PDF back to section files')
58
- .argument('[file]', 'Word (.docx) or PDF file from reviewer (default: most recent)')
59
- .argument('[sections...]', 'Specific sections to sync (default: all)')
60
- .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
61
- .option('-d, --dir <directory>', 'Directory with section files', '.')
62
- .option('--no-crossref', 'Skip converting hardcoded figure/table refs')
63
- .option('--no-diff', 'Skip showing diff preview')
64
- .option('--force', 'Overwrite files without conflict warning')
65
- .option('--dry-run', 'Preview without writing files')
66
- .option('--comments-only', 'Insert comments at fuzzy-matched anchors only; never modify existing prose or apply track changes (use when markdown was revised after the docx was sent for review)')
67
- .action(async (docx: string | undefined, sections: string[], options: SyncOptions) => {
68
- // Auto-detect most recent docx or pdf if not provided
69
- if (!docx) {
70
- const docxFiles = findFiles('.docx');
71
- const pdfFiles = findFiles('.pdf');
72
- const allFiles = [...docxFiles, ...pdfFiles];
73
-
74
- if (allFiles.length === 0) {
75
- console.error(fmt.status('error', 'No .docx or .pdf files found in current directory.'));
76
- process.exit(1);
77
- }
78
- const sorted = allFiles
79
- .map(f => ({ name: f, mtime: fs.statSync(f).mtime }))
80
- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
81
- docx = sorted[0].name;
82
- console.log(fmt.status('info', `Using most recent: ${docx}`));
83
- console.log();
84
- }
85
-
86
- if (!fs.existsSync(docx)) {
87
- console.error(fmt.status('error', `File not found: ${docx}`));
88
- process.exit(1);
89
- }
90
-
91
- // Handle PDF files
92
- if (docx.toLowerCase().endsWith('.pdf')) {
93
- const { extractPdfComments, formatPdfComments, getPdfCommentStats } = await import('../pdf-import.js');
94
-
95
- const spin = fmt.spinner(`Extracting comments from ${path.basename(docx)}...`).start();
96
-
97
- try {
98
- const comments = await extractPdfComments(docx);
99
- spin.stop();
100
-
101
- if (comments.length === 0) {
102
- console.log(fmt.status('info', 'No comments found in PDF.'));
103
- return;
104
- }
105
-
106
- const stats = getPdfCommentStats(comments);
107
- console.log(fmt.header(`PDF Comments from ${path.basename(docx)}`));
108
- console.log();
109
- console.log(formatPdfComments(comments));
110
- console.log();
111
-
112
- const authorList = Object.entries(stats.byAuthor)
113
- .map(([author, count]) => `${author} (${count})`)
114
- .join(', ');
115
- console.log(chalk.dim(`Total: ${stats.total} comments from ${authorList}`));
116
- console.log();
117
-
118
- const resolved = resolveSectionsConfig(options.dir, options.config);
119
- if (resolved && !options.dryRun) {
120
- const mainSection = getOrderedSections(resolved.config)[0];
121
-
122
- if (mainSection) {
123
- const mainPath = path.join(options.dir, mainSection);
124
- if (fs.existsSync(mainPath)) {
125
- console.log(chalk.dim(`Use 'rev pdf-comments ${docx} --append ${mainSection}' to add comments to markdown.`));
126
- }
127
- }
128
- }
129
- } catch (err) {
130
- spin.stop();
131
- const error = err as Error;
132
- console.error(fmt.status('error', `Failed to extract PDF comments: ${error.message}`));
133
- if (process.env.DEBUG) console.error(error.stack);
134
- process.exit(1);
135
- }
136
- return;
137
- }
138
-
139
- // Resolve the section config: an explicit sections.yaml if present,
140
- // otherwise the `sections:` list in rev.yaml (single source of truth).
141
- const resolved = resolveSectionsConfig(options.dir, options.config);
142
- if (!resolved) {
143
- console.error(fmt.status('error', `No section config found in ${path.resolve(options.dir)}`));
144
- console.error(chalk.dim(' Add a `sections:` list to rev.yaml, or run "rev init" to generate sections.yaml.'));
145
- process.exit(1);
146
- }
147
- const sectionsConfig = resolved.config;
148
-
149
- // --comments-only: import comments only, never modify existing prose.
150
- // Use this when the markdown has been revised since the docx was sent
151
- // out — track changes from a stale draft would clobber newer edits.
152
- if (options.commentsOnly) {
153
- await syncCommentsOnly(docx, sections, options, sectionsConfig);
154
- return;
155
- }
156
-
157
- // Check pandoc availability upfront and warn
158
- const { hasPandoc, getInstallInstructions } = await import('../dependencies.js');
159
- if (!hasPandoc()) {
160
- console.log(fmt.status('warning', `Pandoc not installed. Track changes will be extracted from XML (formatting may differ).`));
161
- console.log(chalk.dim(` Install for best results: ${getInstallInstructions('pandoc')}`));
162
- console.log();
163
- }
164
-
165
- const spin = fmt.spinner(`Importing ${path.basename(docx)}...`).start();
166
-
167
- try {
168
- const config = sectionsConfig;
169
- const { importFromWord, extractWordComments, extractCommentAnchors, insertCommentsIntoMarkdown, extractFromWord } = await import('../import.js');
170
-
171
- let registry = null;
172
- let totalRefConversions = 0;
173
- if (options.crossref !== false) {
174
- registry = buildRegistry(options.dir);
175
- }
176
-
177
- const comments = await extractWordComments(docx);
178
- const { anchors, fullDocText: xmlDocText } = await extractCommentAnchors(docx);
179
-
180
- // Extract Word text (uses pandoc if available, falls back to XML extraction)
181
- const wordExtraction = await extractFromWord(docx, { mediaDir: options.dir });
182
- let wordText = wordExtraction.text;
183
- const wordTables = wordExtraction.tables || [];
184
-
185
- // Log extraction messages (warnings about pandoc, track change stats, etc.)
186
- for (const msg of wordExtraction.messages || []) {
187
- if (msg.type === 'warning') {
188
- spin.stop();
189
- console.log(fmt.status('warning', msg.message));
190
- spin.start();
191
- }
192
- }
193
-
194
- // Restore crossref on FULL text BEFORE splitting into sections
195
- // This ensures duplicate labels from track changes are handled correctly
196
- // (the same figure may appear multiple times in old/new versions)
197
- const { restoreCrossrefFromWord, restoreImagesFromRegistry } = await import('../import.js');
198
- const crossrefResult = restoreCrossrefFromWord(wordText, options.dir);
199
- wordText = crossrefResult.text;
200
- if (crossrefResult.restored > 0) {
201
- console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
202
- }
203
-
204
- // Also restore images from registry using shared restoredLabels
205
- const imageRestoreResult = restoreImagesFromRegistry(wordText, options.dir, crossrefResult.restoredLabels);
206
- wordText = imageRestoreResult.text;
207
- if (imageRestoreResult.restored > 0) {
208
- console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
209
- }
210
-
211
- let wordSections = extractSectionsFromText(wordText, config.sections);
212
-
213
- if (wordSections.length === 0) {
214
- spin.stop();
215
- console.error(fmt.status('warning', 'No sections detected in Word document.'));
216
- console.error(chalk.dim(' Check that headings match sections.yaml'));
217
- process.exit(1);
218
- }
219
-
220
- if (sections && sections.length > 0) {
221
- const onlyList = sections.map(s => s.trim().toLowerCase());
222
- wordSections = wordSections.filter(section => {
223
- const fileName = section.file.replace(/\.md$/i, '').toLowerCase();
224
- const header = section.header.toLowerCase();
225
- return onlyList.some(name => fileName === name || fileName.includes(name) || header.includes(name));
226
- });
227
- if (wordSections.length === 0) {
228
- spin.stop();
229
- console.error(fmt.status('error', `No sections matched: ${sections.join(', ')}`));
230
- console.error(chalk.dim(` Available: ${extractSectionsFromText(wordText, config.sections).map(s => s.file.replace(/\.md$/i, '')).join(', ')}`));
231
- process.exit(1);
232
- }
233
- }
234
-
235
- spin.stop();
236
- console.log(fmt.header(`Import from ${path.basename(docx)}`));
237
- console.log();
238
-
239
- // Conflict detection
240
- if (!options.force && !options.dryRun) {
241
- const conflicts: Array<{ file: string; annotations: number }> = [];
242
- for (const section of wordSections) {
243
- const sectionPath = path.join(options.dir, section.file);
244
- if (fs.existsSync(sectionPath)) {
245
- const existing = fs.readFileSync(sectionPath, 'utf-8');
246
- const existingCounts = countAnnotations(existing);
247
- if (existingCounts.total > 0) {
248
- conflicts.push({
249
- file: section.file,
250
- annotations: existingCounts.total,
251
- });
252
- }
253
- }
254
- }
255
-
256
- if (conflicts.length > 0) {
257
- console.log(fmt.status('warning', 'Files with existing annotations will be overwritten:'));
258
- for (const c of conflicts) {
259
- console.log(chalk.yellow(` - ${c.file} (${c.annotations} annotations)`));
260
- }
261
- console.log();
262
-
263
- const rl = readline.createInterface({
264
- input: process.stdin,
265
- output: process.stdout,
266
- });
267
-
268
- const answer = await new Promise<string>((resolve) =>
269
- rl.question(chalk.cyan('Continue and overwrite? [y/N] '), resolve)
270
- );
271
- rl.close();
272
-
273
- if (answer.toLowerCase() !== 'y') {
274
- console.log(chalk.dim('Aborted. Use --force to skip this check.'));
275
- process.exit(0);
276
- }
277
- console.log();
278
- }
279
- }
280
-
281
- const sectionResults: Array<{
282
- file: string;
283
- header: string;
284
- status: string;
285
- stats?: ImportStats;
286
- refs?: number;
287
- }> = [];
288
- let totalChanges = 0;
289
-
290
- // Calculate section boundaries in the XML document text for comment filtering
291
- // Comment positions (docPosition) are relative to xmlDocText, NOT wordText
292
- // So we must find section headers in xmlDocText to get matching boundaries
293
- const sectionBoundaries: Array<{ file: string; start: number; end: number }> = [];
294
- const xmlLower = xmlDocText.toLowerCase();
295
-
296
- // Standard section header keywords to search for in XML
297
- // Map from file name pattern to search terms
298
- const sectionKeywords: Record<string, string[]> = {
299
- 'abstract': ['abstract', 'summary'],
300
- 'introduction': ['introduction', 'background'],
301
- 'methods': ['methods', 'materials and methods', 'methodology'],
302
- 'results': ['results'],
303
- 'discussion': ['discussion'],
304
- 'conclusion': ['conclusion', 'conclusions'],
305
- };
306
-
307
- // Helper: find section header (skip labels like "Methods:" in structured abstracts)
308
- // Real section headers are NOT followed by ":" immediately
309
- function findSectionHeader(text: string, keyword: string, startFrom: number = 0): number {
310
- const lower = text.toLowerCase();
311
- let idx = startFrom;
312
- while ((idx = lower.indexOf(keyword, idx)) !== -1) {
313
- // Check what follows the keyword
314
- const afterKeyword = text.slice(idx + keyword.length, idx + keyword.length + 5);
315
- // Skip if followed by ":" (this is a label, not a section header)
316
- // Real headers are followed by text content, a newline, or a subheading
317
- if (!afterKeyword.startsWith(':') && !afterKeyword.startsWith(' :')) {
318
- return idx;
319
- }
320
- idx++;
321
- }
322
- return -1;
323
- }
324
-
325
- for (const section of wordSections) {
326
- const fileBase = section.file.replace(/\.md$/i, '').toLowerCase();
327
-
328
- // Get keywords for this section
329
- const keywords = sectionKeywords[fileBase] || [fileBase];
330
-
331
- // Find the first valid keyword that exists in XML (not a label)
332
- let headerIdx = -1;
333
- for (const kw of keywords) {
334
- const idx = findSectionHeader(xmlDocText, kw, 0);
335
- if (idx >= 0 && (headerIdx < 0 || idx < headerIdx)) {
336
- headerIdx = idx;
337
- }
338
- }
339
-
340
- if (headerIdx >= 0) {
341
- // Find the next section's start to determine end boundary
342
- let nextHeaderIdx = xmlDocText.length;
343
- const sectionIdx = wordSections.indexOf(section);
344
- if (sectionIdx < wordSections.length - 1) {
345
- const nextFileBase = wordSections[sectionIdx + 1].file.replace(/\.md$/i, '').toLowerCase();
346
- const nextKeywords = sectionKeywords[nextFileBase] || [nextFileBase];
347
- for (const nkw of nextKeywords) {
348
- const foundNext = findSectionHeader(xmlDocText, nkw, headerIdx + 10);
349
- if (foundNext >= 0 && foundNext < nextHeaderIdx) {
350
- nextHeaderIdx = foundNext;
351
- }
352
- }
353
- }
354
-
355
- sectionBoundaries.push({
356
- file: section.file,
357
- start: headerIdx,
358
- end: nextHeaderIdx
359
- });
360
-
361
- }
362
- }
363
-
364
- // Document length is the XML text length (same coordinate system as docPosition)
365
- const docLength = xmlDocText.length;
366
-
367
- for (const section of wordSections) {
368
- const sectionPath = path.join(options.dir, section.file);
369
-
370
- if (!fs.existsSync(sectionPath)) {
371
- sectionResults.push({
372
- file: section.file,
373
- header: section.header,
374
- status: 'skipped',
375
- stats: undefined,
376
- });
377
- continue;
378
- }
379
-
380
- const result = await importFromWord(docx, sectionPath, {
381
- sectionContent: section.content,
382
- author: 'Reviewer',
383
- wordTables: wordTables,
384
- });
385
-
386
- let { annotated, stats } = result;
387
-
388
- let refConversions: Array<{ from: string; to: string }> = [];
389
- if (registry && options.crossref !== false) {
390
- const crossrefResult = convertHardcodedRefs(annotated, registry);
391
- annotated = crossrefResult.converted;
392
- refConversions = crossrefResult.conversions;
393
- totalRefConversions += refConversions.length;
394
- }
395
-
396
- let commentsInserted = 0;
397
- if (comments.length > 0 && anchors.size > 0) {
398
- // Filter comments to only those that belong to this section
399
- // Use exact position matching: docPosition is in xmlDocText coordinates,
400
- // and sectionBoundaries are also in xmlDocText coordinates (same source!)
401
- const boundary = sectionBoundaries.find(b => b.file === section.file);
402
- const isFirstSection = wordSections.indexOf(section) === 0;
403
- const firstBoundaryStart = sectionBoundaries.length > 0 ? Math.min(...sectionBoundaries.map(b => b.start)) : 0;
404
-
405
- const sectionComments = comments.filter((c: any) => {
406
- const anchorData = anchors.get(c.id);
407
- if (!anchorData) return false;
408
-
409
- // Use exact position - no scaling needed since both are in xmlDocText coordinates
410
- if (anchorData.docPosition !== undefined && boundary) {
411
- // Include comments within section boundaries
412
- if (anchorData.docPosition >= boundary.start && anchorData.docPosition < boundary.end) {
413
- return true;
414
- }
415
- // Also include "outside" comments (before first section) in the first section file
416
- if (isFirstSection && anchorData.docPosition < firstBoundaryStart) {
417
- return true;
418
- }
419
- }
420
-
421
- return false;
422
- });
423
-
424
- if (process.env.DEBUG) {
425
- console.log(`[DEBUG] ${section.file}: ${sectionComments.length} comments to place (boundary: ${boundary?.start}-${boundary?.end})`);
426
- }
427
-
428
- if (sectionComments.length > 0) {
429
- // Use a more robust pattern that handles < in comment text
430
- const commentPattern = /\{>>.*?<<\}/gs;
431
- const beforeCount = (annotated.match(commentPattern) || []).length;
432
- annotated = insertCommentsIntoMarkdown(annotated, sectionComments, anchors, {
433
- quiet: !process.env.DEBUG,
434
- sectionBoundary: boundary // Pass section boundary for position-based insertion
435
- });
436
- const afterCount = (annotated.match(commentPattern) || []).length;
437
- commentsInserted = afterCount - beforeCount;
438
-
439
- if (process.env.DEBUG) {
440
- console.log(`[DEBUG] ${section.file}: inserted ${commentsInserted} of ${sectionComments.length} comments`);
441
- }
442
-
443
- if (commentsInserted > 0) {
444
- stats.comments = (stats.comments || 0) + commentsInserted;
445
- }
446
- }
447
- }
448
-
449
- totalChanges += stats.total;
450
-
451
- sectionResults.push({
452
- file: section.file,
453
- header: section.header,
454
- status: 'ok',
455
- stats,
456
- refs: refConversions.length,
457
- });
458
-
459
- if (!options.dryRun) {
460
- // Preserve any preamble content (YAML frontmatter, author blocks, metadata)
461
- // that exists before the first heading in the original file.
462
- // This content is never included in the Word build output, so it won't
463
- // appear in the Word doc and would otherwise be lost during sync.
464
- const originalContent = fs.readFileSync(sectionPath, 'utf-8');
465
- const firstHeadingMatch = originalContent.match(/^(#\s)/m);
466
- if (firstHeadingMatch && firstHeadingMatch.index !== undefined && firstHeadingMatch.index > 0) {
467
- const preamble = originalContent.slice(0, firstHeadingMatch.index);
468
- // Only prepend if preamble has non-whitespace content
469
- if (preamble.trim().length > 0) {
470
- annotated = preamble + annotated;
471
- }
472
- }
473
- fs.writeFileSync(sectionPath, annotated, 'utf-8');
474
- }
475
- }
476
-
477
- const tableRows = sectionResults.map((r) => {
478
- if (r.status === 'skipped') {
479
- return [
480
- chalk.dim(r.file),
481
- chalk.dim(r.header.slice(0, 25)),
482
- chalk.yellow('skipped'),
483
- '',
484
- '',
485
- '',
486
- '',
487
- ];
488
- }
489
- const s = r.stats!;
490
- return [
491
- chalk.bold(r.file),
492
- r.header.length > 25 ? r.header.slice(0, 22) + '...' : r.header,
493
- s.insertions > 0 ? chalk.green(`+${s.insertions}`) : chalk.dim('-'),
494
- s.deletions > 0 ? chalk.red(`-${s.deletions}`) : chalk.dim('-'),
495
- s.substitutions > 0 ? chalk.yellow(`~${s.substitutions}`) : chalk.dim('-'),
496
- s.comments > 0 ? chalk.blue(`#${s.comments}`) : chalk.dim('-'),
497
- r.refs! > 0 ? chalk.magenta(`@${r.refs}`) : chalk.dim('-'),
498
- ];
499
- });
500
-
501
- console.log(fmt.table(
502
- ['File', 'Section', 'Ins', 'Del', 'Sub', 'Cmt', 'Ref'],
503
- tableRows,
504
- { align: ['left', 'left', 'right', 'right', 'right', 'right', 'right'] }
505
- ));
506
- console.log();
507
-
508
- if (options.diff !== false && totalChanges > 0) {
509
- console.log(fmt.header('Changes Preview'));
510
- console.log();
511
- for (const result of sectionResults) {
512
- if (result.status === 'ok' && result.stats && result.stats.total > 0) {
513
- const sectionPath = path.join(options.dir, result.file);
514
- if (fs.existsSync(sectionPath)) {
515
- const content = fs.readFileSync(sectionPath, 'utf-8');
516
- const preview = inlineDiffPreview(content, { maxLines: 3 });
517
- if (preview) {
518
- console.log(chalk.bold(result.file) + ':');
519
- console.log(preview);
520
- console.log();
521
- }
522
- }
523
- }
524
- }
525
- }
526
-
527
- if (options.dryRun) {
528
- console.log(fmt.box(chalk.yellow('Dry run - no files written'), { padding: 0 }));
529
- } else if (totalChanges > 0 || totalRefConversions > 0 || comments.length > 0) {
530
- const summaryLines: string[] = [];
531
- summaryLines.push(`${chalk.bold(wordSections.length)} sections processed`);
532
- if (totalChanges > 0) summaryLines.push(`${chalk.bold(totalChanges)} annotations imported`);
533
- if (comments.length > 0) summaryLines.push(`${chalk.bold(comments.length)} comments placed`);
534
- if (totalRefConversions > 0) summaryLines.push(`${chalk.bold(totalRefConversions)} refs converted to @-syntax`);
535
-
536
- console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
537
- console.log();
538
- console.log(chalk.dim('Next steps:'));
539
- console.log(chalk.dim(' 1. rev review <section.md> - Accept/reject changes'));
540
- console.log(chalk.dim(' 2. rev comments <section.md> - View/address comments'));
541
- console.log(chalk.dim(' 3. rev build docx - Rebuild Word doc'));
542
- } else {
543
- console.log(fmt.status('success', 'No changes detected.'));
544
- }
545
- } catch (err) {
546
- spin.stop();
547
- const error = err as Error;
548
- console.error(fmt.status('error', error.message));
549
- if (process.env.DEBUG) console.error(error.stack);
550
- process.exit(1);
551
- }
552
- });
553
- }
554
-
555
- /**
556
- * `sync --comments-only`: import only Word comments at fuzzy-matched anchors.
557
- *
558
- * Skips the Word→Markdown diff entirely (no track changes, no pandoc, no
559
- * prose modifications). Useful when the markdown has been edited after the
560
- * docx was sent for review — applying track changes from a stale draft
561
- * would overwrite newer edits.
562
- */
563
- async function syncCommentsOnly(
564
- docx: string,
565
- sectionFilter: string[] | undefined,
566
- options: SyncOptions,
567
- config: SectionsConfig,
568
- ): Promise<void> {
569
- const { extractWordComments, extractCommentAnchors, extractHeadings, insertCommentsIntoMarkdown } = await import('../import.js');
570
- const { computeSectionBoundaries } = await import('./section-boundaries.js');
571
-
572
- const spin = fmt.spinner(`Reading comments from ${path.basename(docx)}...`).start();
573
-
574
- let comments;
575
- let anchors;
576
- let headings;
577
- let fullDocText = '';
578
- try {
579
- comments = await extractWordComments(docx);
580
- const result = await extractCommentAnchors(docx);
581
- anchors = result.anchors;
582
- fullDocText = result.fullDocText;
583
- headings = await extractHeadings(docx);
584
- spin.stop();
585
- } catch (err) {
586
- spin.stop();
587
- const error = err as Error;
588
- console.error(fmt.status('error', error.message));
589
- process.exit(1);
590
- }
591
-
592
- console.log(fmt.header(`Comments from ${path.basename(docx)} (comments-only)`));
593
- console.log();
594
-
595
- if (comments.length === 0) {
596
- console.log(fmt.status('info', 'No comments found in document.'));
597
- return;
598
- }
599
-
600
- const boundaries = computeSectionBoundaries(config.sections, headings, fullDocText.length);
601
-
602
- if (boundaries.length === 0) {
603
- console.error(fmt.status('warning', 'No section headings detected in Word document.'));
604
- console.error(chalk.dim(' Check that headers in sections.yaml match heading paragraphs in the docx.'));
605
- process.exit(1);
606
- }
607
-
608
- // Apply optional section filter from CLI
609
- let activeBoundaries = boundaries;
610
- if (sectionFilter && sectionFilter.length > 0) {
611
- const wanted = sectionFilter.map(s => s.trim().toLowerCase());
612
- activeBoundaries = boundaries.filter(b => {
613
- const base = b.file.replace(/\.md$/i, '').toLowerCase();
614
- return wanted.some(name => base === name || base.includes(name));
615
- });
616
- if (activeBoundaries.length === 0) {
617
- console.error(fmt.status('error', `No sections matched: ${sectionFilter.join(', ')}`));
618
- process.exit(1);
619
- }
620
- }
621
-
622
- const firstBoundaryStart = boundaries[0].start;
623
- const results: Array<{ file: string; placed: number; deduped: number; unmatched: number; skipped: boolean }> = [];
624
-
625
- for (const boundary of activeBoundaries) {
626
- const sectionPath = path.join(options.dir, boundary.file);
627
- if (!fs.existsSync(sectionPath)) {
628
- results.push({ file: boundary.file, placed: 0, deduped: 0, unmatched: 0, skipped: true });
629
- continue;
630
- }
631
-
632
- const isFirstSection = boundary === activeBoundaries[0];
633
- const sectionComments = comments.filter((c: { id: string }) => {
634
- const anchor = anchors.get(c.id);
635
- if (!anchor || anchor.docPosition === undefined) return false;
636
- if (anchor.docPosition >= boundary.start && anchor.docPosition < boundary.end) return true;
637
- // Comments before the first heading land in the first matched section
638
- if (isFirstSection && anchor.docPosition < firstBoundaryStart) return true;
639
- return false;
640
- });
641
-
642
- if (sectionComments.length === 0) {
643
- results.push({ file: boundary.file, placed: 0, deduped: 0, unmatched: 0, skipped: false });
644
- continue;
645
- }
646
-
647
- const original = fs.readFileSync(sectionPath, 'utf-8');
648
-
649
- const stats = { placed: 0, deduped: 0, unmatched: 0 };
650
- const annotated = insertCommentsIntoMarkdown(original, sectionComments, anchors, {
651
- quiet: !process.env.DEBUG,
652
- sectionBoundary: { start: boundary.start, end: boundary.end },
653
- wrapAnchor: false,
654
- outStats: stats,
655
- });
656
-
657
- if (!options.dryRun && stats.placed > 0) {
658
- fs.writeFileSync(sectionPath, annotated, 'utf-8');
659
- }
660
- results.push({ file: boundary.file, ...stats, skipped: false });
661
- }
662
-
663
- const tableRows = results.map(r => {
664
- if (r.skipped) {
665
- return [chalk.dim(r.file), chalk.yellow('missing'), '', '', ''];
666
- }
667
- return [
668
- chalk.bold(r.file),
669
- chalk.green(`${r.placed}`),
670
- r.deduped > 0 ? chalk.cyan(`${r.deduped}`) : chalk.dim('-'),
671
- r.unmatched > 0 ? chalk.yellow(`${r.unmatched}`) : chalk.dim('-'),
672
- chalk.dim('comments only'),
673
- ];
674
- });
675
-
676
- console.log(fmt.table(
677
- ['File', 'Placed', 'Already', 'Unmatched', 'Mode'],
678
- tableRows,
679
- { align: ['left', 'right', 'right', 'right', 'left'] },
680
- ));
681
- console.log();
682
-
683
- const totalPlaced = results.reduce((s, r) => s + r.placed, 0);
684
- const totalDeduped = results.reduce((s, r) => s + r.deduped, 0);
685
- const totalUnmatched = results.reduce((s, r) => s + r.unmatched, 0);
686
-
687
- const lines: string[] = [];
688
- lines.push(`${chalk.bold(comments.length)} comments in document`);
689
- if (totalPlaced > 0) {
690
- lines.push(`${chalk.bold(totalPlaced)} placed at anchors`);
691
- }
692
- if (totalDeduped > 0) {
693
- lines.push(`${chalk.cyan(totalDeduped)} already present (skipped to avoid duplication)`);
694
- }
695
- if (totalUnmatched > 0) {
696
- lines.push(`${chalk.yellow(totalUnmatched)} unmatched (no anchor in current prose)`);
697
- }
698
- if (options.dryRun) {
699
- lines.push(chalk.yellow('Dry run — no files written'));
700
- } else if (totalPlaced > 0) {
701
- lines.push(chalk.dim('Existing prose unchanged.'));
702
- }
703
- console.log(fmt.box(lines.join('\n'), { title: 'Summary', padding: 0 }));
704
-
705
- if (totalUnmatched > 0) {
706
- console.log();
707
- console.log(chalk.dim('Tip: run "rev verify-anchors" to see which comments drifted.'));
708
- }
709
- }
1
+ /**
2
+ * SYNC command: Import feedback from Word/PDF back to section files
3
+ *
4
+ * Split from sections.ts for maintainability.
5
+ */
6
+
7
+ import {
8
+ chalk,
9
+ fs,
10
+ path,
11
+ fmt,
12
+ findFiles,
13
+ resolveSectionsConfig,
14
+ getOrderedSections,
15
+ extractSectionsFromText,
16
+ countAnnotations,
17
+ buildRegistry,
18
+ convertHardcodedRefs,
19
+ inlineDiffPreview,
20
+ } from './context.js';
21
+ import type { Command } from 'commander';
22
+ import type { SectionsConfig } from '../types.js';
23
+ import * as readline from 'readline';
24
+
25
+ interface ImportStats {
26
+ insertions: number;
27
+ deletions: number;
28
+ substitutions: number;
29
+ comments: number;
30
+ total: number;
31
+ }
32
+
33
+ interface SyncOptions {
34
+ config: string;
35
+ dir: string;
36
+ crossref?: boolean;
37
+ diff?: boolean;
38
+ force?: boolean;
39
+ dryRun?: boolean;
40
+ /** Commander maps `--comments-only` (a positive flag) cleanly. `--no-overwrite`
41
+ * conflicts with the existing `overwrite` semantics in `--force`-style flags
42
+ * and Commander's `--no-X` convention assigns `options.x === false`. */
43
+ commentsOnly?: boolean;
44
+ }
45
+
46
+ /**
47
+ * Register the sync command with the program
48
+ */
49
+ export function register(program: Command): void {
50
+ // ==========================================================================
51
+ // SYNC command - Import with section awareness
52
+ // ==========================================================================
53
+
54
+ program
55
+ .command('sync')
56
+ .alias('sections')
57
+ .description('Sync feedback from Word/PDF back to section files')
58
+ .argument('[file]', 'Word (.docx) or PDF file from reviewer (default: most recent)')
59
+ .argument('[sections...]', 'Specific sections to sync (default: all)')
60
+ .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
61
+ .option('-d, --dir <directory>', 'Directory with section files', '.')
62
+ .option('--no-crossref', 'Skip converting hardcoded figure/table refs')
63
+ .option('--no-diff', 'Skip showing diff preview')
64
+ .option('--force', 'Overwrite files without conflict warning')
65
+ .option('--dry-run', 'Preview without writing files')
66
+ .option('--comments-only', 'Insert comments at fuzzy-matched anchors only; never modify existing prose or apply track changes (use when markdown was revised after the docx was sent for review)')
67
+ .action(async (docx: string | undefined, sections: string[], options: SyncOptions) => {
68
+ // Auto-detect most recent docx or pdf if not provided
69
+ if (!docx) {
70
+ const docxFiles = findFiles('.docx');
71
+ const pdfFiles = findFiles('.pdf');
72
+ const allFiles = [...docxFiles, ...pdfFiles];
73
+
74
+ if (allFiles.length === 0) {
75
+ console.error(fmt.status('error', 'No .docx or .pdf files found in current directory.'));
76
+ process.exit(1);
77
+ }
78
+ const sorted = allFiles
79
+ .map(f => ({ name: f, mtime: fs.statSync(f).mtime }))
80
+ .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
81
+ docx = sorted[0].name;
82
+ console.log(fmt.status('info', `Using most recent: ${docx}`));
83
+ console.log();
84
+ }
85
+
86
+ if (!fs.existsSync(docx)) {
87
+ console.error(fmt.status('error', `File not found: ${docx}`));
88
+ process.exit(1);
89
+ }
90
+
91
+ // Handle PDF files
92
+ if (docx.toLowerCase().endsWith('.pdf')) {
93
+ const { extractPdfComments, formatPdfComments, getPdfCommentStats } = await import('../pdf-import.js');
94
+
95
+ const spin = fmt.spinner(`Extracting comments from ${path.basename(docx)}...`).start();
96
+
97
+ try {
98
+ const comments = await extractPdfComments(docx);
99
+ spin.stop();
100
+
101
+ if (comments.length === 0) {
102
+ console.log(fmt.status('info', 'No comments found in PDF.'));
103
+ return;
104
+ }
105
+
106
+ const stats = getPdfCommentStats(comments);
107
+ console.log(fmt.header(`PDF Comments from ${path.basename(docx)}`));
108
+ console.log();
109
+ console.log(formatPdfComments(comments));
110
+ console.log();
111
+
112
+ const authorList = Object.entries(stats.byAuthor)
113
+ .map(([author, count]) => `${author} (${count})`)
114
+ .join(', ');
115
+ console.log(chalk.dim(`Total: ${stats.total} comments from ${authorList}`));
116
+ console.log();
117
+
118
+ const resolved = resolveSectionsConfig(options.dir, options.config);
119
+ if (resolved && !options.dryRun) {
120
+ const mainSection = getOrderedSections(resolved.config)[0];
121
+
122
+ if (mainSection) {
123
+ const mainPath = path.join(options.dir, mainSection);
124
+ if (fs.existsSync(mainPath)) {
125
+ console.log(chalk.dim(`Use 'rev pdf-comments ${docx} --append ${mainSection}' to add comments to markdown.`));
126
+ }
127
+ }
128
+ }
129
+ } catch (err) {
130
+ spin.stop();
131
+ const error = err as Error;
132
+ console.error(fmt.status('error', `Failed to extract PDF comments: ${error.message}`));
133
+ if (process.env.DEBUG) console.error(error.stack);
134
+ process.exit(1);
135
+ }
136
+ return;
137
+ }
138
+
139
+ // Resolve the section config: an explicit sections.yaml if present,
140
+ // otherwise the `sections:` list in rev.yaml (single source of truth).
141
+ const resolved = resolveSectionsConfig(options.dir, options.config);
142
+ if (!resolved) {
143
+ console.error(fmt.status('error', `No section config found in ${path.resolve(options.dir)}`));
144
+ console.error(chalk.dim(' Add a `sections:` list to rev.yaml, or run "rev init" to generate sections.yaml.'));
145
+ process.exit(1);
146
+ }
147
+ const sectionsConfig = resolved.config;
148
+
149
+ // --comments-only: import comments only, never modify existing prose.
150
+ // Use this when the markdown has been revised since the docx was sent
151
+ // out — track changes from a stale draft would clobber newer edits.
152
+ if (options.commentsOnly) {
153
+ await syncCommentsOnly(docx, sections, options, sectionsConfig);
154
+ return;
155
+ }
156
+
157
+ // Check pandoc availability upfront and warn
158
+ const { hasPandoc, getInstallInstructions } = await import('../dependencies.js');
159
+ if (!hasPandoc()) {
160
+ console.log(fmt.status('warning', `Pandoc not installed. Track changes will be extracted from XML (formatting may differ).`));
161
+ console.log(chalk.dim(` Install for best results: ${getInstallInstructions('pandoc')}`));
162
+ console.log();
163
+ }
164
+
165
+ const spin = fmt.spinner(`Importing ${path.basename(docx)}...`).start();
166
+
167
+ try {
168
+ const config = sectionsConfig;
169
+ const { importFromWord, extractWordComments, extractCommentAnchors, insertCommentsIntoMarkdown, extractFromWord, extractHeadings } = await import('../import.js');
170
+ const { computeSectionBoundaries } = await import('./section-boundaries.js');
171
+
172
+ let registry = null;
173
+ let totalRefConversions = 0;
174
+ if (options.crossref !== false) {
175
+ registry = buildRegistry(options.dir);
176
+ }
177
+
178
+ const comments = await extractWordComments(docx);
179
+ const { anchors, fullDocText: xmlDocText } = await extractCommentAnchors(docx);
180
+
181
+ // Extract Word text (uses pandoc if available, falls back to XML extraction)
182
+ const wordExtraction = await extractFromWord(docx, { mediaDir: options.dir });
183
+ let wordText = wordExtraction.text;
184
+ const wordTables = wordExtraction.tables || [];
185
+
186
+ // Log extraction messages (warnings about pandoc, track change stats, etc.)
187
+ for (const msg of wordExtraction.messages || []) {
188
+ if (msg.type === 'warning') {
189
+ spin.stop();
190
+ console.log(fmt.status('warning', msg.message));
191
+ spin.start();
192
+ }
193
+ }
194
+
195
+ // Restore crossref on FULL text BEFORE splitting into sections
196
+ // This ensures duplicate labels from track changes are handled correctly
197
+ // (the same figure may appear multiple times in old/new versions)
198
+ const { restoreCrossrefFromWord, restoreImagesFromRegistry } = await import('../import.js');
199
+ const crossrefResult = restoreCrossrefFromWord(wordText, options.dir);
200
+ wordText = crossrefResult.text;
201
+ if (crossrefResult.restored > 0) {
202
+ console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
203
+ }
204
+
205
+ // Also restore images from registry using shared restoredLabels
206
+ const imageRestoreResult = restoreImagesFromRegistry(wordText, options.dir, crossrefResult.restoredLabels);
207
+ wordText = imageRestoreResult.text;
208
+ if (imageRestoreResult.restored > 0) {
209
+ console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
210
+ }
211
+
212
+ let wordSections = extractSectionsFromText(wordText, config.sections);
213
+
214
+ if (wordSections.length === 0) {
215
+ spin.stop();
216
+ console.error(fmt.status('warning', 'No sections detected in Word document.'));
217
+ console.error(chalk.dim(' Check that headings match sections.yaml'));
218
+ process.exit(1);
219
+ }
220
+
221
+ if (sections && sections.length > 0) {
222
+ const onlyList = sections.map(s => s.trim().toLowerCase());
223
+ wordSections = wordSections.filter(section => {
224
+ const fileName = section.file.replace(/\.md$/i, '').toLowerCase();
225
+ const header = section.header.toLowerCase();
226
+ return onlyList.some(name => fileName === name || fileName.includes(name) || header.includes(name));
227
+ });
228
+ if (wordSections.length === 0) {
229
+ spin.stop();
230
+ console.error(fmt.status('error', `No sections matched: ${sections.join(', ')}`));
231
+ console.error(chalk.dim(` Available: ${extractSectionsFromText(wordText, config.sections).map(s => s.file.replace(/\.md$/i, '')).join(', ')}`));
232
+ process.exit(1);
233
+ }
234
+ }
235
+
236
+ spin.stop();
237
+ console.log(fmt.header(`Import from ${path.basename(docx)}`));
238
+ console.log();
239
+
240
+ // Conflict detection
241
+ if (!options.force && !options.dryRun) {
242
+ const conflicts: Array<{ file: string; annotations: number }> = [];
243
+ for (const section of wordSections) {
244
+ const sectionPath = path.join(options.dir, section.file);
245
+ if (fs.existsSync(sectionPath)) {
246
+ const existing = fs.readFileSync(sectionPath, 'utf-8');
247
+ const existingCounts = countAnnotations(existing);
248
+ if (existingCounts.total > 0) {
249
+ conflicts.push({
250
+ file: section.file,
251
+ annotations: existingCounts.total,
252
+ });
253
+ }
254
+ }
255
+ }
256
+
257
+ if (conflicts.length > 0) {
258
+ console.log(fmt.status('warning', 'Files with existing annotations will be overwritten:'));
259
+ for (const c of conflicts) {
260
+ console.log(chalk.yellow(` - ${c.file} (${c.annotations} annotations)`));
261
+ }
262
+ console.log();
263
+
264
+ const rl = readline.createInterface({
265
+ input: process.stdin,
266
+ output: process.stdout,
267
+ });
268
+
269
+ const answer = await new Promise<string>((resolve) =>
270
+ rl.question(chalk.cyan('Continue and overwrite? [y/N] '), resolve)
271
+ );
272
+ rl.close();
273
+
274
+ if (answer.toLowerCase() !== 'y') {
275
+ console.log(chalk.dim('Aborted. Use --force to skip this check.'));
276
+ process.exit(0);
277
+ }
278
+ console.log();
279
+ }
280
+ }
281
+
282
+ const sectionResults: Array<{
283
+ file: string;
284
+ header: string;
285
+ status: string;
286
+ stats?: ImportStats;
287
+ refs?: number;
288
+ }> = [];
289
+ let totalChanges = 0;
290
+
291
+ // Route comments to sections using boundaries from the document's real
292
+ // heading paragraphs. docPosition (from extractCommentAnchors) and each
293
+ // heading's docPosition share one coordinate system over xmlDocText, so
294
+ // every configured section gets a boundary — not only the handful that
295
+ // matched a hardcoded keyword list. Sections named "Objectives" or
296
+ // "Annex 2" used to get no boundary, so their comments were silently
297
+ // dropped while the summary still claimed every comment was placed.
298
+ // This is the same routing path as `sync --comments-only`.
299
+ const headings = await extractHeadings(docx);
300
+ const sectionBoundaries = computeSectionBoundaries(config.sections, headings, xmlDocText.length);
301
+ const firstBoundaryStart = sectionBoundaries.length > 0 ? sectionBoundaries[0].start : 0;
302
+
303
+ // Truthful comment accounting: track which comments were routed to a
304
+ // synced section and how many were actually written, so the summary
305
+ // reports placements rather than the raw extracted count.
306
+ const routedCommentIds = new Set<string>();
307
+ let totalCommentsPlaced = 0;
308
+ let totalCommentsDeduped = 0;
309
+ let totalCommentsUnmatched = 0;
310
+
311
+ for (const section of wordSections) {
312
+ const sectionPath = path.join(options.dir, section.file);
313
+
314
+ if (!fs.existsSync(sectionPath)) {
315
+ sectionResults.push({
316
+ file: section.file,
317
+ header: section.header,
318
+ status: 'skipped',
319
+ stats: undefined,
320
+ });
321
+ continue;
322
+ }
323
+
324
+ // A section that appears in the reviewed document as a bare heading
325
+ // with no body was not really part of this build (e.g. a "no-annex"
326
+ // export synced against the full project). Importing it would diff
327
+ // real prose against an empty body and rewrite the file to near-empty.
328
+ // Leave it untouched.
329
+ const bodyEmpty = section.content.trim() === section.header.trim();
330
+ if (bodyEmpty) {
331
+ sectionResults.push({
332
+ file: section.file,
333
+ header: section.header,
334
+ status: 'untouched',
335
+ stats: undefined,
336
+ });
337
+ continue;
338
+ }
339
+
340
+ const result = await importFromWord(docx, sectionPath, {
341
+ sectionContent: section.content,
342
+ author: 'Reviewer',
343
+ wordTables: wordTables,
344
+ });
345
+
346
+ let { annotated, stats } = result;
347
+
348
+ let refConversions: Array<{ from: string; to: string }> = [];
349
+ if (registry && options.crossref !== false) {
350
+ const crossrefResult = convertHardcodedRefs(annotated, registry);
351
+ annotated = crossrefResult.converted;
352
+ refConversions = crossrefResult.conversions;
353
+ totalRefConversions += refConversions.length;
354
+ }
355
+
356
+ if (comments.length > 0 && anchors.size > 0) {
357
+ // Filter comments to those whose docPosition falls in this section's
358
+ // boundary (docPosition and boundaries share xmlDocText coordinates).
359
+ // The section owning the first boundary also catches comments placed
360
+ // before any heading.
361
+ const boundary = sectionBoundaries.find(b => b.file === section.file);
362
+ const ownsFirstBoundary = !!boundary && boundary.start === firstBoundaryStart;
363
+
364
+ const sectionComments = comments.filter((c: { id: string }) => {
365
+ const anchorData = anchors.get(c.id);
366
+ if (!anchorData || anchorData.docPosition === undefined || !boundary) return false;
367
+ if (anchorData.docPosition >= boundary.start && anchorData.docPosition < boundary.end) return true;
368
+ if (ownsFirstBoundary && anchorData.docPosition < firstBoundaryStart) return true;
369
+ return false;
370
+ });
371
+
372
+ if (process.env.DEBUG) {
373
+ console.log(`[DEBUG] ${section.file}: ${sectionComments.length} comments to place (boundary: ${boundary?.start}-${boundary?.end})`);
374
+ }
375
+
376
+ if (sectionComments.length > 0) {
377
+ for (const c of sectionComments) routedCommentIds.add(c.id);
378
+ const cstats = { placed: 0, deduped: 0, unmatched: 0 };
379
+ annotated = insertCommentsIntoMarkdown(annotated, sectionComments, anchors, {
380
+ quiet: !process.env.DEBUG,
381
+ sectionBoundary: boundary,
382
+ outStats: cstats,
383
+ });
384
+ stats.comments = (stats.comments || 0) + cstats.placed;
385
+ totalCommentsPlaced += cstats.placed;
386
+ totalCommentsDeduped += cstats.deduped;
387
+ totalCommentsUnmatched += cstats.unmatched;
388
+
389
+ if (process.env.DEBUG) {
390
+ console.log(`[DEBUG] ${section.file}: placed ${cstats.placed}, deduped ${cstats.deduped}, unmatched ${cstats.unmatched} of ${sectionComments.length}`);
391
+ }
392
+ }
393
+ }
394
+
395
+ totalChanges += stats.total;
396
+
397
+ sectionResults.push({
398
+ file: section.file,
399
+ header: section.header,
400
+ status: 'ok',
401
+ stats,
402
+ refs: refConversions.length,
403
+ });
404
+
405
+ if (!options.dryRun) {
406
+ // Preserve any preamble content (YAML frontmatter, author blocks, metadata)
407
+ // that exists before the first heading in the original file.
408
+ // This content is never included in the Word build output, so it won't
409
+ // appear in the Word doc and would otherwise be lost during sync.
410
+ const originalContent = fs.readFileSync(sectionPath, 'utf-8');
411
+ const firstHeadingMatch = originalContent.match(/^(#\s)/m);
412
+ if (firstHeadingMatch && firstHeadingMatch.index !== undefined && firstHeadingMatch.index > 0) {
413
+ const preamble = originalContent.slice(0, firstHeadingMatch.index);
414
+ // Only prepend if preamble has non-whitespace content
415
+ if (preamble.trim().length > 0) {
416
+ annotated = preamble + annotated;
417
+ }
418
+ }
419
+ fs.writeFileSync(sectionPath, annotated, 'utf-8');
420
+ }
421
+ }
422
+
423
+ const tableRows = sectionResults.map((r) => {
424
+ if (r.status === 'skipped' || r.status === 'untouched') {
425
+ return [
426
+ chalk.dim(r.file),
427
+ chalk.dim(r.header.slice(0, 25)),
428
+ chalk.yellow(r.status),
429
+ '',
430
+ '',
431
+ '',
432
+ '',
433
+ ];
434
+ }
435
+ const s = r.stats!;
436
+ return [
437
+ chalk.bold(r.file),
438
+ r.header.length > 25 ? r.header.slice(0, 22) + '...' : r.header,
439
+ s.insertions > 0 ? chalk.green(`+${s.insertions}`) : chalk.dim('-'),
440
+ s.deletions > 0 ? chalk.red(`-${s.deletions}`) : chalk.dim('-'),
441
+ s.substitutions > 0 ? chalk.yellow(`~${s.substitutions}`) : chalk.dim('-'),
442
+ s.comments > 0 ? chalk.blue(`#${s.comments}`) : chalk.dim('-'),
443
+ r.refs! > 0 ? chalk.magenta(`@${r.refs}`) : chalk.dim('-'),
444
+ ];
445
+ });
446
+
447
+ console.log(fmt.table(
448
+ ['File', 'Section', 'Ins', 'Del', 'Sub', 'Cmt', 'Ref'],
449
+ tableRows,
450
+ { align: ['left', 'left', 'right', 'right', 'right', 'right', 'right'] }
451
+ ));
452
+ console.log();
453
+
454
+ if (options.diff !== false && totalChanges > 0) {
455
+ console.log(fmt.header('Changes Preview'));
456
+ console.log();
457
+ for (const result of sectionResults) {
458
+ if (result.status === 'ok' && result.stats && result.stats.total > 0) {
459
+ const sectionPath = path.join(options.dir, result.file);
460
+ if (fs.existsSync(sectionPath)) {
461
+ const content = fs.readFileSync(sectionPath, 'utf-8');
462
+ const preview = inlineDiffPreview(content, { maxLines: 3 });
463
+ if (preview) {
464
+ console.log(chalk.bold(result.file) + ':');
465
+ console.log(preview);
466
+ console.log();
467
+ }
468
+ }
469
+ }
470
+ }
471
+ }
472
+
473
+ // Comments carried by the document but never routed to a synced section
474
+ // (they fell in a skipped/untouched/absent section). Surfacing these
475
+ // keeps the summary honest instead of reporting every extracted comment
476
+ // as placed.
477
+ const unroutedComments = comments.length - routedCommentIds.size;
478
+
479
+ if (options.dryRun) {
480
+ console.log(fmt.box(chalk.yellow('Dry run - no files written'), { padding: 0 }));
481
+ } else if (totalChanges > 0 || totalRefConversions > 0 || comments.length > 0) {
482
+ const summaryLines: string[] = [];
483
+ summaryLines.push(`${chalk.bold(wordSections.length)} sections processed`);
484
+ if (totalChanges > 0) summaryLines.push(`${chalk.bold(totalChanges)} annotations imported`);
485
+ if (totalCommentsPlaced > 0) {
486
+ summaryLines.push(`${chalk.bold(totalCommentsPlaced)} of ${comments.length} comments placed`);
487
+ }
488
+ if (totalCommentsDeduped > 0) {
489
+ summaryLines.push(`${chalk.cyan(totalCommentsDeduped)} already present (skipped)`);
490
+ }
491
+ if (totalCommentsUnmatched > 0) {
492
+ summaryLines.push(`${chalk.yellow(totalCommentsUnmatched)} unmatched (anchor not in current prose)`);
493
+ }
494
+ if (unroutedComments > 0) {
495
+ summaryLines.push(`${chalk.yellow(unroutedComments)} not routed to any synced section`);
496
+ }
497
+ if (totalRefConversions > 0) summaryLines.push(`${chalk.bold(totalRefConversions)} refs converted to @-syntax`);
498
+
499
+ console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
500
+ console.log();
501
+ if (totalCommentsUnmatched > 0 || unroutedComments > 0) {
502
+ console.log(chalk.yellow(` ${totalCommentsUnmatched + unroutedComments} comment(s) were not written. Run "rev verify-anchors" or re-sync with the full document.`));
503
+ console.log();
504
+ }
505
+ console.log(chalk.dim('Next steps:'));
506
+ console.log(chalk.dim(' 1. rev review <section.md> - Accept/reject changes'));
507
+ console.log(chalk.dim(' 2. rev comments <section.md> - View/address comments'));
508
+ console.log(chalk.dim(' 3. rev build docx - Rebuild Word doc'));
509
+ } else {
510
+ console.log(fmt.status('success', 'No changes detected.'));
511
+ }
512
+ } catch (err) {
513
+ spin.stop();
514
+ const error = err as Error;
515
+ console.error(fmt.status('error', error.message));
516
+ if (process.env.DEBUG) console.error(error.stack);
517
+ process.exit(1);
518
+ }
519
+ });
520
+ }
521
+
522
+ /**
523
+ * `sync --comments-only`: import only Word comments at fuzzy-matched anchors.
524
+ *
525
+ * Skips the Word→Markdown diff entirely (no track changes, no pandoc, no
526
+ * prose modifications). Useful when the markdown has been edited after the
527
+ * docx was sent for review — applying track changes from a stale draft
528
+ * would overwrite newer edits.
529
+ */
530
+ async function syncCommentsOnly(
531
+ docx: string,
532
+ sectionFilter: string[] | undefined,
533
+ options: SyncOptions,
534
+ config: SectionsConfig,
535
+ ): Promise<void> {
536
+ const { extractWordComments, extractCommentAnchors, extractHeadings, insertCommentsIntoMarkdown } = await import('../import.js');
537
+ const { computeSectionBoundaries } = await import('./section-boundaries.js');
538
+
539
+ const spin = fmt.spinner(`Reading comments from ${path.basename(docx)}...`).start();
540
+
541
+ let comments;
542
+ let anchors;
543
+ let headings;
544
+ let fullDocText = '';
545
+ try {
546
+ comments = await extractWordComments(docx);
547
+ const result = await extractCommentAnchors(docx);
548
+ anchors = result.anchors;
549
+ fullDocText = result.fullDocText;
550
+ headings = await extractHeadings(docx);
551
+ spin.stop();
552
+ } catch (err) {
553
+ spin.stop();
554
+ const error = err as Error;
555
+ console.error(fmt.status('error', error.message));
556
+ process.exit(1);
557
+ }
558
+
559
+ console.log(fmt.header(`Comments from ${path.basename(docx)} (comments-only)`));
560
+ console.log();
561
+
562
+ if (comments.length === 0) {
563
+ console.log(fmt.status('info', 'No comments found in document.'));
564
+ return;
565
+ }
566
+
567
+ const boundaries = computeSectionBoundaries(config.sections, headings, fullDocText.length);
568
+
569
+ if (boundaries.length === 0) {
570
+ console.error(fmt.status('warning', 'No section headings detected in Word document.'));
571
+ console.error(chalk.dim(' Check that headers in sections.yaml match heading paragraphs in the docx.'));
572
+ process.exit(1);
573
+ }
574
+
575
+ // Apply optional section filter from CLI
576
+ let activeBoundaries = boundaries;
577
+ if (sectionFilter && sectionFilter.length > 0) {
578
+ const wanted = sectionFilter.map(s => s.trim().toLowerCase());
579
+ activeBoundaries = boundaries.filter(b => {
580
+ const base = b.file.replace(/\.md$/i, '').toLowerCase();
581
+ return wanted.some(name => base === name || base.includes(name));
582
+ });
583
+ if (activeBoundaries.length === 0) {
584
+ console.error(fmt.status('error', `No sections matched: ${sectionFilter.join(', ')}`));
585
+ process.exit(1);
586
+ }
587
+ }
588
+
589
+ const firstBoundaryStart = boundaries[0].start;
590
+ const results: Array<{ file: string; placed: number; deduped: number; unmatched: number; skipped: boolean }> = [];
591
+
592
+ for (const boundary of activeBoundaries) {
593
+ const sectionPath = path.join(options.dir, boundary.file);
594
+ if (!fs.existsSync(sectionPath)) {
595
+ results.push({ file: boundary.file, placed: 0, deduped: 0, unmatched: 0, skipped: true });
596
+ continue;
597
+ }
598
+
599
+ const isFirstSection = boundary === activeBoundaries[0];
600
+ const sectionComments = comments.filter((c: { id: string }) => {
601
+ const anchor = anchors.get(c.id);
602
+ if (!anchor || anchor.docPosition === undefined) return false;
603
+ if (anchor.docPosition >= boundary.start && anchor.docPosition < boundary.end) return true;
604
+ // Comments before the first heading land in the first matched section
605
+ if (isFirstSection && anchor.docPosition < firstBoundaryStart) return true;
606
+ return false;
607
+ });
608
+
609
+ if (sectionComments.length === 0) {
610
+ results.push({ file: boundary.file, placed: 0, deduped: 0, unmatched: 0, skipped: false });
611
+ continue;
612
+ }
613
+
614
+ const original = fs.readFileSync(sectionPath, 'utf-8');
615
+
616
+ const stats = { placed: 0, deduped: 0, unmatched: 0 };
617
+ const annotated = insertCommentsIntoMarkdown(original, sectionComments, anchors, {
618
+ quiet: !process.env.DEBUG,
619
+ sectionBoundary: { start: boundary.start, end: boundary.end },
620
+ wrapAnchor: false,
621
+ outStats: stats,
622
+ });
623
+
624
+ if (!options.dryRun && stats.placed > 0) {
625
+ fs.writeFileSync(sectionPath, annotated, 'utf-8');
626
+ }
627
+ results.push({ file: boundary.file, ...stats, skipped: false });
628
+ }
629
+
630
+ const tableRows = results.map(r => {
631
+ if (r.skipped) {
632
+ return [chalk.dim(r.file), chalk.yellow('missing'), '', '', ''];
633
+ }
634
+ return [
635
+ chalk.bold(r.file),
636
+ chalk.green(`${r.placed}`),
637
+ r.deduped > 0 ? chalk.cyan(`${r.deduped}`) : chalk.dim('-'),
638
+ r.unmatched > 0 ? chalk.yellow(`${r.unmatched}`) : chalk.dim('-'),
639
+ chalk.dim('comments only'),
640
+ ];
641
+ });
642
+
643
+ console.log(fmt.table(
644
+ ['File', 'Placed', 'Already', 'Unmatched', 'Mode'],
645
+ tableRows,
646
+ { align: ['left', 'right', 'right', 'right', 'left'] },
647
+ ));
648
+ console.log();
649
+
650
+ const totalPlaced = results.reduce((s, r) => s + r.placed, 0);
651
+ const totalDeduped = results.reduce((s, r) => s + r.deduped, 0);
652
+ const totalUnmatched = results.reduce((s, r) => s + r.unmatched, 0);
653
+
654
+ const lines: string[] = [];
655
+ lines.push(`${chalk.bold(comments.length)} comments in document`);
656
+ if (totalPlaced > 0) {
657
+ lines.push(`${chalk.bold(totalPlaced)} placed at anchors`);
658
+ }
659
+ if (totalDeduped > 0) {
660
+ lines.push(`${chalk.cyan(totalDeduped)} already present (skipped to avoid duplication)`);
661
+ }
662
+ if (totalUnmatched > 0) {
663
+ lines.push(`${chalk.yellow(totalUnmatched)} unmatched (no anchor in current prose)`);
664
+ }
665
+ if (options.dryRun) {
666
+ lines.push(chalk.yellow('Dry run — no files written'));
667
+ } else if (totalPlaced > 0) {
668
+ lines.push(chalk.dim('Existing prose unchanged.'));
669
+ }
670
+ console.log(fmt.box(lines.join('\n'), { title: 'Summary', padding: 0 }));
671
+
672
+ if (totalUnmatched > 0) {
673
+ console.log();
674
+ console.log(chalk.dim('Tip: run "rev verify-anchors" to see which comments drifted.'));
675
+ }
676
+ }