docrev 0.9.13 → 0.9.15

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 (126) hide show
  1. package/.claude/settings.local.json +9 -9
  2. package/.gitattributes +1 -1
  3. package/CHANGELOG.md +149 -149
  4. package/PLAN-tables-and-postprocess.md +850 -850
  5. package/README.md +411 -391
  6. package/bin/rev.js +11 -11
  7. package/bin/rev.ts +145 -145
  8. package/completions/rev.bash +127 -127
  9. package/completions/rev.ps1 +210 -210
  10. package/completions/rev.zsh +207 -207
  11. package/dev_notes/stress2/build_adversarial.ts +186 -186
  12. package/dev_notes/stress2/drift_matcher.ts +62 -62
  13. package/dev_notes/stress2/probe_anchors.ts +35 -35
  14. package/dev_notes/stress2/project/discussion.before.md +3 -3
  15. package/dev_notes/stress2/project/discussion.md +3 -3
  16. package/dev_notes/stress2/project/methods.before.md +20 -20
  17. package/dev_notes/stress2/project/methods.md +20 -20
  18. package/dev_notes/stress2/project/rev.yaml +5 -5
  19. package/dev_notes/stress2/project/sections.yaml +4 -4
  20. package/dev_notes/stress2/sections.yaml +5 -5
  21. package/dev_notes/stress2/trace_placement.ts +50 -50
  22. package/dev_notes/stresstest_boundaries.ts +27 -27
  23. package/dev_notes/stresstest_drift_apply.ts +43 -43
  24. package/dev_notes/stresstest_drift_compare.ts +43 -43
  25. package/dev_notes/stresstest_drift_v2.ts +54 -54
  26. package/dev_notes/stresstest_inspect.ts +54 -54
  27. package/dev_notes/stresstest_pstyle.ts +55 -55
  28. package/dev_notes/stresstest_section_debug.ts +23 -23
  29. package/dev_notes/stresstest_split.ts +70 -70
  30. package/dev_notes/stresstest_trace.ts +19 -19
  31. package/dev_notes/stresstest_verify_no_overwrite.ts +40 -40
  32. package/dist/lib/build.d.ts +38 -1
  33. package/dist/lib/build.d.ts.map +1 -1
  34. package/dist/lib/build.js +68 -30
  35. package/dist/lib/build.js.map +1 -1
  36. package/dist/lib/commands/build.d.ts.map +1 -1
  37. package/dist/lib/commands/build.js +38 -5
  38. package/dist/lib/commands/build.js.map +1 -1
  39. package/dist/lib/commands/utilities.js +164 -164
  40. package/dist/lib/commands/word-tools.js +8 -8
  41. package/dist/lib/grammar.js +3 -3
  42. package/dist/lib/pdf-comments.js +44 -44
  43. package/dist/lib/plugins.js +57 -57
  44. package/dist/lib/pptx-themes.js +115 -115
  45. package/dist/lib/spelling.js +2 -2
  46. package/dist/lib/templates.js +387 -387
  47. package/dist/lib/themes.js +51 -51
  48. package/eslint.config.js +27 -27
  49. package/lib/anchor-match.ts +276 -276
  50. package/lib/annotations.ts +644 -644
  51. package/lib/build.ts +1300 -1251
  52. package/lib/citations.ts +160 -160
  53. package/lib/commands/build.ts +833 -801
  54. package/lib/commands/citations.ts +515 -515
  55. package/lib/commands/comments.ts +1050 -1050
  56. package/lib/commands/context.ts +174 -174
  57. package/lib/commands/core.ts +309 -309
  58. package/lib/commands/doi.ts +435 -435
  59. package/lib/commands/file-ops.ts +372 -372
  60. package/lib/commands/history.ts +320 -320
  61. package/lib/commands/index.ts +87 -87
  62. package/lib/commands/init.ts +259 -259
  63. package/lib/commands/merge-resolve.ts +378 -378
  64. package/lib/commands/preview.ts +178 -178
  65. package/lib/commands/project-info.ts +244 -244
  66. package/lib/commands/quality.ts +517 -517
  67. package/lib/commands/response.ts +454 -454
  68. package/lib/commands/section-boundaries.ts +82 -82
  69. package/lib/commands/sections.ts +451 -451
  70. package/lib/commands/sync.ts +706 -706
  71. package/lib/commands/text-ops.ts +449 -449
  72. package/lib/commands/utilities.ts +448 -448
  73. package/lib/commands/verify-anchors.ts +272 -272
  74. package/lib/commands/word-tools.ts +340 -340
  75. package/lib/comment-realign.ts +517 -517
  76. package/lib/config.ts +84 -84
  77. package/lib/crossref.ts +781 -781
  78. package/lib/csl.ts +191 -191
  79. package/lib/dependencies.ts +98 -98
  80. package/lib/diff-engine.ts +465 -465
  81. package/lib/doi-cache.ts +115 -115
  82. package/lib/doi.ts +897 -897
  83. package/lib/equations.ts +506 -506
  84. package/lib/errors.ts +346 -346
  85. package/lib/format.ts +541 -541
  86. package/lib/git.ts +326 -326
  87. package/lib/grammar.ts +303 -303
  88. package/lib/image-registry.ts +180 -180
  89. package/lib/import.ts +911 -911
  90. package/lib/journals.ts +543 -543
  91. package/lib/merge.ts +633 -633
  92. package/lib/orcid.ts +144 -144
  93. package/lib/pdf-comments.ts +263 -263
  94. package/lib/pdf-import.ts +524 -524
  95. package/lib/plugins.ts +362 -362
  96. package/lib/postprocess.ts +188 -188
  97. package/lib/pptx-color-filter.lua +37 -37
  98. package/lib/pptx-template.ts +469 -469
  99. package/lib/pptx-themes.ts +483 -483
  100. package/lib/protect-restore.ts +520 -520
  101. package/lib/rate-limiter.ts +94 -94
  102. package/lib/response.ts +197 -197
  103. package/lib/restore-references.ts +240 -240
  104. package/lib/review.ts +327 -327
  105. package/lib/schema.ts +417 -417
  106. package/lib/scientific-words.ts +73 -73
  107. package/lib/sections.ts +335 -335
  108. package/lib/slides.ts +756 -756
  109. package/lib/spelling.ts +334 -334
  110. package/lib/templates.ts +526 -526
  111. package/lib/themes.ts +742 -742
  112. package/lib/trackchanges.ts +247 -247
  113. package/lib/tui.ts +450 -450
  114. package/lib/types.ts +550 -550
  115. package/lib/undo.ts +250 -250
  116. package/lib/utils.ts +69 -69
  117. package/lib/variables.ts +179 -179
  118. package/lib/word-extraction.ts +806 -806
  119. package/lib/word.ts +643 -643
  120. package/lib/wordcomments.ts +817 -817
  121. package/package.json +137 -137
  122. package/scripts/postbuild.js +28 -28
  123. package/skill/REFERENCE.md +473 -431
  124. package/skill/SKILL.md +274 -258
  125. package/tsconfig.json +26 -26
  126. package/types/index.d.ts +525 -525
@@ -1,340 +1,340 @@
1
- /**
2
- * Word document tool commands: annotate, apply, comment
3
- *
4
- * Commands for working with Word documents directly (comments, track changes).
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- getUserName,
14
- parseAnnotations,
15
- } from './context.js';
16
-
17
- // Options interfaces
18
- interface AnnotateOptions {
19
- message?: string;
20
- search?: string;
21
- author?: string;
22
- }
23
-
24
- interface ApplyOptions {
25
- author?: string;
26
- }
27
-
28
- interface CommentOptions {
29
- author?: string;
30
- }
31
-
32
- /**
33
- * Register word-tools commands with the program
34
- */
35
- export function register(program: Command): void {
36
- // ==========================================================================
37
- // ANNOTATE command - Add comments to Word document
38
- // ==========================================================================
39
-
40
- program
41
- .command('annotate')
42
- .description('Add comment to Word document')
43
- .argument('<docx>', 'Word document')
44
- .option('-m, --message <text>', 'Comment text')
45
- .option('-s, --search <text>', 'Text to attach comment to')
46
- .option('-a, --author <name>', 'Comment author')
47
- .action(async (docxPath: string, options: AnnotateOptions) => {
48
- if (!fs.existsSync(docxPath)) {
49
- console.error(chalk.red(`File not found: ${docxPath}`));
50
- process.exit(1);
51
- }
52
-
53
- if (!options.message) {
54
- console.error(chalk.red('Comment message required (-m)'));
55
- process.exit(1);
56
- }
57
-
58
- const { default: AdmZip } = await import('adm-zip');
59
- const zip = new AdmZip(docxPath);
60
-
61
- // Read document.xml
62
- const docEntry = zip.getEntry('word/document.xml');
63
- if (!docEntry) {
64
- console.error(chalk.red('Invalid Word document'));
65
- process.exit(1);
66
- }
67
-
68
- let docXml = zip.readAsText(docEntry);
69
-
70
- // Read or create comments.xml
71
- let commentsEntry = zip.getEntry('word/comments.xml');
72
- let commentsXml: string;
73
- let nextCommentId = 1;
74
-
75
- if (commentsEntry) {
76
- commentsXml = zip.readAsText(commentsEntry);
77
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
- for (const m of idMatches) {
79
- const id = parseInt(m.match(/\d+/)![0]);
80
- if (id >= nextCommentId) nextCommentId = id + 1;
81
- }
82
- } else {
83
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
- </w:comments>`;
86
- }
87
-
88
- const author = options.author || getUserName() || 'Claude';
89
- const date = new Date().toISOString();
90
- const commentId = nextCommentId;
91
-
92
- // Add comment to comments.xml
93
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
- <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
- </w:comment>`;
96
-
97
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
-
99
- // Find text and add comment markers
100
- if (options.search) {
101
- const searchText = options.search;
102
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
-
104
- if (textPattern.test(docXml)) {
105
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
- });
108
- } else {
109
- console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
- }
111
- }
112
-
113
- // Update zip
114
- zip.updateFile('word/document.xml', Buffer.from(docXml));
115
-
116
- if (commentsEntry) {
117
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
- } else {
119
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
-
121
- // Update [Content_Types].xml
122
- const ctEntry = zip.getEntry('[Content_Types].xml');
123
- if (ctEntry) {
124
- let ctXml = zip.readAsText(ctEntry);
125
- if (!ctXml.includes('comments.xml')) {
126
- ctXml = ctXml.replace('</Types>',
127
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
- }
130
- }
131
-
132
- // Update document.xml.rels
133
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
- if (relsEntry) {
135
- let relsXml = zip.readAsText(relsEntry);
136
- if (!relsXml.includes('comments.xml')) {
137
- const newRelId = `rId${Date.now()}`;
138
- relsXml = relsXml.replace('</Relationships>',
139
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
- }
142
- }
143
- }
144
-
145
- // Write back
146
- zip.writeZip(docxPath);
147
- console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
- });
149
-
150
- // ==========================================================================
151
- // APPLY command - Apply MD annotations as Word track changes
152
- // ==========================================================================
153
-
154
- program
155
- .command('apply')
156
- .description('Apply markdown annotations to Word document as track changes')
157
- .argument('<md>', 'Markdown file with annotations')
158
- .argument('<docx>', 'Output Word document')
159
- .option('-a, --author <name>', 'Author name for track changes')
160
- .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
- if (!fs.existsSync(mdPath)) {
162
- console.error(chalk.red(`File not found: ${mdPath}`));
163
- process.exit(1);
164
- }
165
-
166
- const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
- const annotations = parseAnnotations(mdContent);
168
-
169
- if (annotations.length === 0) {
170
- console.log(chalk.yellow('No annotations found in markdown file'));
171
- }
172
-
173
- const author = options.author || getUserName() || 'Author';
174
-
175
- // Build document with track changes
176
- const { buildWithTrackChanges } = await import('../trackchanges.js');
177
-
178
- try {
179
- const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
-
181
- if (result.success) {
182
- console.log(fmt.status('success', result.message));
183
- console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
- } else {
185
- console.error(chalk.red(result.message));
186
- process.exit(1);
187
- }
188
- } catch (err) {
189
- console.error(chalk.red(`Error: ${(err as Error).message}`));
190
- process.exit(1);
191
- }
192
- });
193
-
194
- // ==========================================================================
195
- // COMMENT command - Interactive comment addition to DOCX
196
- // ==========================================================================
197
-
198
- program
199
- .command('comment')
200
- .description('Add comments to Word document interactively')
201
- .argument('<docx>', 'Word document')
202
- .option('-a, --author <name>', 'Comment author')
203
- .action(async (docxPath: string, options: CommentOptions) => {
204
- if (!fs.existsSync(docxPath)) {
205
- console.error(chalk.red(`File not found: ${docxPath}`));
206
- process.exit(1);
207
- }
208
-
209
- const { default: AdmZip } = await import('adm-zip');
210
- const readline = await import('readline');
211
- const rl = readline.createInterface({
212
- input: process.stdin,
213
- output: process.stdout,
214
- });
215
-
216
- const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
-
218
- const author = options.author || getUserName() || 'Reviewer';
219
-
220
- console.log(fmt.header('Interactive Comment Mode'));
221
- console.log(chalk.dim(` Document: ${docxPath}`));
222
- console.log(chalk.dim(` Author: ${author}`));
223
- console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
- console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
-
226
- let commentsAdded = 0;
227
-
228
- while (true) {
229
- const message = await ask(chalk.cyan('Comment: '));
230
-
231
- if (!message.trim()) {
232
- break;
233
- }
234
-
235
- const searchText = await ask(chalk.cyan('Attach to text: '));
236
-
237
- // Load document fresh each time
238
- const zip = new AdmZip(docxPath);
239
- const docEntry = zip.getEntry('word/document.xml');
240
-
241
- if (!docEntry) {
242
- console.error(chalk.red('Invalid Word document'));
243
- rl.close();
244
- process.exit(1);
245
- }
246
-
247
- let docXml = zip.readAsText(docEntry);
248
-
249
- // Read or create comments.xml
250
- let commentsEntry = zip.getEntry('word/comments.xml');
251
- let commentsXml: string;
252
- let nextCommentId = 1;
253
-
254
- if (commentsEntry) {
255
- commentsXml = zip.readAsText(commentsEntry);
256
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
- for (const m of idMatches) {
258
- const id = parseInt(m.match(/\d+/)![0]);
259
- if (id >= nextCommentId) nextCommentId = id + 1;
260
- }
261
- } else {
262
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
- </w:comments>`;
265
- }
266
-
267
- const date = new Date().toISOString();
268
- const commentId = nextCommentId;
269
-
270
- // Add comment to comments.xml
271
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
- <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
- </w:comment>`;
274
-
275
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
-
277
- // Find text and add comment markers
278
- if (searchText.trim()) {
279
- const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
-
282
- if (textPattern.test(docXml)) {
283
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
- });
286
- console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
- } else {
288
- console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
- }
290
- } else {
291
- console.log(chalk.dim(` Comment added without anchor.`));
292
- }
293
-
294
- // Update zip
295
- zip.updateFile('word/document.xml', Buffer.from(docXml));
296
-
297
- if (commentsEntry) {
298
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
- } else {
300
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
-
302
- // Update [Content_Types].xml
303
- const ctEntry = zip.getEntry('[Content_Types].xml');
304
- if (ctEntry) {
305
- let ctXml = zip.readAsText(ctEntry);
306
- if (!ctXml.includes('comments.xml')) {
307
- ctXml = ctXml.replace('</Types>',
308
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
- }
311
- }
312
-
313
- // Update document.xml.rels
314
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
- if (relsEntry) {
316
- let relsXml = zip.readAsText(relsEntry);
317
- if (!relsXml.includes('comments.xml')) {
318
- const newRelId = `rId${Date.now()}`;
319
- relsXml = relsXml.replace('</Relationships>',
320
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
- }
323
- }
324
- }
325
-
326
- zip.writeZip(docxPath);
327
- commentsAdded++;
328
- console.log();
329
- }
330
-
331
- rl.close();
332
- console.log();
333
-
334
- if (commentsAdded > 0) {
335
- console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
- } else {
337
- console.log(chalk.dim('No comments added.'));
338
- }
339
- });
340
- }
1
+ /**
2
+ * Word document tool commands: annotate, apply, comment
3
+ *
4
+ * Commands for working with Word documents directly (comments, track changes).
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ getUserName,
14
+ parseAnnotations,
15
+ } from './context.js';
16
+
17
+ // Options interfaces
18
+ interface AnnotateOptions {
19
+ message?: string;
20
+ search?: string;
21
+ author?: string;
22
+ }
23
+
24
+ interface ApplyOptions {
25
+ author?: string;
26
+ }
27
+
28
+ interface CommentOptions {
29
+ author?: string;
30
+ }
31
+
32
+ /**
33
+ * Register word-tools commands with the program
34
+ */
35
+ export function register(program: Command): void {
36
+ // ==========================================================================
37
+ // ANNOTATE command - Add comments to Word document
38
+ // ==========================================================================
39
+
40
+ program
41
+ .command('annotate')
42
+ .description('Add comment to Word document')
43
+ .argument('<docx>', 'Word document')
44
+ .option('-m, --message <text>', 'Comment text')
45
+ .option('-s, --search <text>', 'Text to attach comment to')
46
+ .option('-a, --author <name>', 'Comment author')
47
+ .action(async (docxPath: string, options: AnnotateOptions) => {
48
+ if (!fs.existsSync(docxPath)) {
49
+ console.error(chalk.red(`File not found: ${docxPath}`));
50
+ process.exit(1);
51
+ }
52
+
53
+ if (!options.message) {
54
+ console.error(chalk.red('Comment message required (-m)'));
55
+ process.exit(1);
56
+ }
57
+
58
+ const { default: AdmZip } = await import('adm-zip');
59
+ const zip = new AdmZip(docxPath);
60
+
61
+ // Read document.xml
62
+ const docEntry = zip.getEntry('word/document.xml');
63
+ if (!docEntry) {
64
+ console.error(chalk.red('Invalid Word document'));
65
+ process.exit(1);
66
+ }
67
+
68
+ let docXml = zip.readAsText(docEntry);
69
+
70
+ // Read or create comments.xml
71
+ let commentsEntry = zip.getEntry('word/comments.xml');
72
+ let commentsXml: string;
73
+ let nextCommentId = 1;
74
+
75
+ if (commentsEntry) {
76
+ commentsXml = zip.readAsText(commentsEntry);
77
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
+ for (const m of idMatches) {
79
+ const id = parseInt(m.match(/\d+/)![0]);
80
+ if (id >= nextCommentId) nextCommentId = id + 1;
81
+ }
82
+ } else {
83
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
+ </w:comments>`;
86
+ }
87
+
88
+ const author = options.author || getUserName() || 'Claude';
89
+ const date = new Date().toISOString();
90
+ const commentId = nextCommentId;
91
+
92
+ // Add comment to comments.xml
93
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
+ <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
+ </w:comment>`;
96
+
97
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
+
99
+ // Find text and add comment markers
100
+ if (options.search) {
101
+ const searchText = options.search;
102
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
+
104
+ if (textPattern.test(docXml)) {
105
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
+ });
108
+ } else {
109
+ console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
+ }
111
+ }
112
+
113
+ // Update zip
114
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
115
+
116
+ if (commentsEntry) {
117
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
+ } else {
119
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
+
121
+ // Update [Content_Types].xml
122
+ const ctEntry = zip.getEntry('[Content_Types].xml');
123
+ if (ctEntry) {
124
+ let ctXml = zip.readAsText(ctEntry);
125
+ if (!ctXml.includes('comments.xml')) {
126
+ ctXml = ctXml.replace('</Types>',
127
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
+ }
130
+ }
131
+
132
+ // Update document.xml.rels
133
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
+ if (relsEntry) {
135
+ let relsXml = zip.readAsText(relsEntry);
136
+ if (!relsXml.includes('comments.xml')) {
137
+ const newRelId = `rId${Date.now()}`;
138
+ relsXml = relsXml.replace('</Relationships>',
139
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
+ }
142
+ }
143
+ }
144
+
145
+ // Write back
146
+ zip.writeZip(docxPath);
147
+ console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
+ });
149
+
150
+ // ==========================================================================
151
+ // APPLY command - Apply MD annotations as Word track changes
152
+ // ==========================================================================
153
+
154
+ program
155
+ .command('apply')
156
+ .description('Apply markdown annotations to Word document as track changes')
157
+ .argument('<md>', 'Markdown file with annotations')
158
+ .argument('<docx>', 'Output Word document')
159
+ .option('-a, --author <name>', 'Author name for track changes')
160
+ .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
+ if (!fs.existsSync(mdPath)) {
162
+ console.error(chalk.red(`File not found: ${mdPath}`));
163
+ process.exit(1);
164
+ }
165
+
166
+ const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
+ const annotations = parseAnnotations(mdContent);
168
+
169
+ if (annotations.length === 0) {
170
+ console.log(chalk.yellow('No annotations found in markdown file'));
171
+ }
172
+
173
+ const author = options.author || getUserName() || 'Author';
174
+
175
+ // Build document with track changes
176
+ const { buildWithTrackChanges } = await import('../trackchanges.js');
177
+
178
+ try {
179
+ const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
+
181
+ if (result.success) {
182
+ console.log(fmt.status('success', result.message));
183
+ console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
+ } else {
185
+ console.error(chalk.red(result.message));
186
+ process.exit(1);
187
+ }
188
+ } catch (err) {
189
+ console.error(chalk.red(`Error: ${(err as Error).message}`));
190
+ process.exit(1);
191
+ }
192
+ });
193
+
194
+ // ==========================================================================
195
+ // COMMENT command - Interactive comment addition to DOCX
196
+ // ==========================================================================
197
+
198
+ program
199
+ .command('comment')
200
+ .description('Add comments to Word document interactively')
201
+ .argument('<docx>', 'Word document')
202
+ .option('-a, --author <name>', 'Comment author')
203
+ .action(async (docxPath: string, options: CommentOptions) => {
204
+ if (!fs.existsSync(docxPath)) {
205
+ console.error(chalk.red(`File not found: ${docxPath}`));
206
+ process.exit(1);
207
+ }
208
+
209
+ const { default: AdmZip } = await import('adm-zip');
210
+ const readline = await import('readline');
211
+ const rl = readline.createInterface({
212
+ input: process.stdin,
213
+ output: process.stdout,
214
+ });
215
+
216
+ const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
+
218
+ const author = options.author || getUserName() || 'Reviewer';
219
+
220
+ console.log(fmt.header('Interactive Comment Mode'));
221
+ console.log(chalk.dim(` Document: ${docxPath}`));
222
+ console.log(chalk.dim(` Author: ${author}`));
223
+ console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
+ console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
+
226
+ let commentsAdded = 0;
227
+
228
+ while (true) {
229
+ const message = await ask(chalk.cyan('Comment: '));
230
+
231
+ if (!message.trim()) {
232
+ break;
233
+ }
234
+
235
+ const searchText = await ask(chalk.cyan('Attach to text: '));
236
+
237
+ // Load document fresh each time
238
+ const zip = new AdmZip(docxPath);
239
+ const docEntry = zip.getEntry('word/document.xml');
240
+
241
+ if (!docEntry) {
242
+ console.error(chalk.red('Invalid Word document'));
243
+ rl.close();
244
+ process.exit(1);
245
+ }
246
+
247
+ let docXml = zip.readAsText(docEntry);
248
+
249
+ // Read or create comments.xml
250
+ let commentsEntry = zip.getEntry('word/comments.xml');
251
+ let commentsXml: string;
252
+ let nextCommentId = 1;
253
+
254
+ if (commentsEntry) {
255
+ commentsXml = zip.readAsText(commentsEntry);
256
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
+ for (const m of idMatches) {
258
+ const id = parseInt(m.match(/\d+/)![0]);
259
+ if (id >= nextCommentId) nextCommentId = id + 1;
260
+ }
261
+ } else {
262
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
+ </w:comments>`;
265
+ }
266
+
267
+ const date = new Date().toISOString();
268
+ const commentId = nextCommentId;
269
+
270
+ // Add comment to comments.xml
271
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
+ <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
+ </w:comment>`;
274
+
275
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
+
277
+ // Find text and add comment markers
278
+ if (searchText.trim()) {
279
+ const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
+
282
+ if (textPattern.test(docXml)) {
283
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
+ });
286
+ console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
+ } else {
288
+ console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
+ }
290
+ } else {
291
+ console.log(chalk.dim(` Comment added without anchor.`));
292
+ }
293
+
294
+ // Update zip
295
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
296
+
297
+ if (commentsEntry) {
298
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
+ } else {
300
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
+
302
+ // Update [Content_Types].xml
303
+ const ctEntry = zip.getEntry('[Content_Types].xml');
304
+ if (ctEntry) {
305
+ let ctXml = zip.readAsText(ctEntry);
306
+ if (!ctXml.includes('comments.xml')) {
307
+ ctXml = ctXml.replace('</Types>',
308
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
+ }
311
+ }
312
+
313
+ // Update document.xml.rels
314
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
+ if (relsEntry) {
316
+ let relsXml = zip.readAsText(relsEntry);
317
+ if (!relsXml.includes('comments.xml')) {
318
+ const newRelId = `rId${Date.now()}`;
319
+ relsXml = relsXml.replace('</Relationships>',
320
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
+ }
323
+ }
324
+ }
325
+
326
+ zip.writeZip(docxPath);
327
+ commentsAdded++;
328
+ console.log();
329
+ }
330
+
331
+ rl.close();
332
+ console.log();
333
+
334
+ if (commentsAdded > 0) {
335
+ console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
+ } else {
337
+ console.log(chalk.dim('No comments added.'));
338
+ }
339
+ });
340
+ }