docrev 0.9.5 → 0.9.7

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 (99) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dev_notes/bug_repro_comment_parser.md +71 -0
  3. package/dist/lib/anchor-match.d.ts +41 -0
  4. package/dist/lib/anchor-match.d.ts.map +1 -0
  5. package/dist/lib/anchor-match.js +192 -0
  6. package/dist/lib/anchor-match.js.map +1 -0
  7. package/dist/lib/annotations.d.ts.map +1 -1
  8. package/dist/lib/annotations.js +8 -5
  9. package/dist/lib/annotations.js.map +1 -1
  10. package/dist/lib/commands/file-ops.d.ts +11 -0
  11. package/dist/lib/commands/file-ops.d.ts.map +1 -0
  12. package/dist/lib/commands/file-ops.js +301 -0
  13. package/dist/lib/commands/file-ops.js.map +1 -0
  14. package/dist/lib/commands/index.d.ts +10 -1
  15. package/dist/lib/commands/index.d.ts.map +1 -1
  16. package/dist/lib/commands/index.js +19 -1
  17. package/dist/lib/commands/index.js.map +1 -1
  18. package/dist/lib/commands/merge-resolve.d.ts +12 -0
  19. package/dist/lib/commands/merge-resolve.d.ts.map +1 -0
  20. package/dist/lib/commands/merge-resolve.js +318 -0
  21. package/dist/lib/commands/merge-resolve.js.map +1 -0
  22. package/dist/lib/commands/preview.d.ts +11 -0
  23. package/dist/lib/commands/preview.d.ts.map +1 -0
  24. package/dist/lib/commands/preview.js +138 -0
  25. package/dist/lib/commands/preview.js.map +1 -0
  26. package/dist/lib/commands/project-info.d.ts +11 -0
  27. package/dist/lib/commands/project-info.d.ts.map +1 -0
  28. package/dist/lib/commands/project-info.js +187 -0
  29. package/dist/lib/commands/project-info.js.map +1 -0
  30. package/dist/lib/commands/quality.d.ts +11 -0
  31. package/dist/lib/commands/quality.d.ts.map +1 -0
  32. package/dist/lib/commands/quality.js +384 -0
  33. package/dist/lib/commands/quality.js.map +1 -0
  34. package/dist/lib/commands/section-boundaries.d.ts +22 -0
  35. package/dist/lib/commands/section-boundaries.d.ts.map +1 -0
  36. package/dist/lib/commands/section-boundaries.js +53 -0
  37. package/dist/lib/commands/section-boundaries.js.map +1 -0
  38. package/dist/lib/commands/sections.d.ts +3 -2
  39. package/dist/lib/commands/sections.d.ts.map +1 -1
  40. package/dist/lib/commands/sections.js +4 -736
  41. package/dist/lib/commands/sections.js.map +1 -1
  42. package/dist/lib/commands/sync.d.ts +11 -0
  43. package/dist/lib/commands/sync.d.ts.map +1 -0
  44. package/dist/lib/commands/sync.js +576 -0
  45. package/dist/lib/commands/sync.js.map +1 -0
  46. package/dist/lib/commands/text-ops.d.ts +11 -0
  47. package/dist/lib/commands/text-ops.d.ts.map +1 -0
  48. package/dist/lib/commands/text-ops.js +357 -0
  49. package/dist/lib/commands/text-ops.js.map +1 -0
  50. package/dist/lib/commands/utilities.d.ts +2 -4
  51. package/dist/lib/commands/utilities.d.ts.map +1 -1
  52. package/dist/lib/commands/utilities.js +3 -1572
  53. package/dist/lib/commands/utilities.js.map +1 -1
  54. package/dist/lib/commands/verify-anchors.d.ts +17 -0
  55. package/dist/lib/commands/verify-anchors.d.ts.map +1 -0
  56. package/dist/lib/commands/verify-anchors.js +215 -0
  57. package/dist/lib/commands/verify-anchors.js.map +1 -0
  58. package/dist/lib/commands/word-tools.d.ts +11 -0
  59. package/dist/lib/commands/word-tools.d.ts.map +1 -0
  60. package/dist/lib/commands/word-tools.js +272 -0
  61. package/dist/lib/commands/word-tools.js.map +1 -0
  62. package/dist/lib/diff-engine.d.ts +25 -0
  63. package/dist/lib/diff-engine.d.ts.map +1 -0
  64. package/dist/lib/diff-engine.js +354 -0
  65. package/dist/lib/diff-engine.js.map +1 -0
  66. package/dist/lib/import.d.ts +44 -118
  67. package/dist/lib/import.d.ts.map +1 -1
  68. package/dist/lib/import.js +25 -1173
  69. package/dist/lib/import.js.map +1 -1
  70. package/dist/lib/restore-references.d.ts +35 -0
  71. package/dist/lib/restore-references.d.ts.map +1 -0
  72. package/dist/lib/restore-references.js +188 -0
  73. package/dist/lib/restore-references.js.map +1 -0
  74. package/dist/lib/word-extraction.d.ts +100 -0
  75. package/dist/lib/word-extraction.d.ts.map +1 -0
  76. package/dist/lib/word-extraction.js +594 -0
  77. package/dist/lib/word-extraction.js.map +1 -0
  78. package/lib/anchor-match.ts +238 -0
  79. package/lib/annotations.ts +9 -5
  80. package/lib/commands/file-ops.ts +372 -0
  81. package/lib/commands/index.ts +27 -0
  82. package/lib/commands/merge-resolve.ts +378 -0
  83. package/lib/commands/preview.ts +178 -0
  84. package/lib/commands/project-info.ts +244 -0
  85. package/lib/commands/quality.ts +517 -0
  86. package/lib/commands/section-boundaries.ts +72 -0
  87. package/lib/commands/sections.ts +3 -870
  88. package/lib/commands/sync.ts +701 -0
  89. package/lib/commands/text-ops.ts +449 -0
  90. package/lib/commands/utilities.ts +62 -2043
  91. package/lib/commands/verify-anchors.ts +261 -0
  92. package/lib/commands/word-tools.ts +340 -0
  93. package/lib/diff-engine.ts +465 -0
  94. package/lib/import.ts +108 -1504
  95. package/lib/restore-references.ts +240 -0
  96. package/lib/word-extraction.ts +759 -0
  97. package/package.json +1 -1
  98. package/skill/REFERENCE.md +29 -2
  99. package/skill/SKILL.md +12 -2
@@ -0,0 +1,261 @@
1
+ /**
2
+ * VERIFY-ANCHORS command: report drift between Word comment anchors
3
+ * and the current markdown.
4
+ *
5
+ * Useful when prose has been revised between sending the docx out for
6
+ * review and receiving it back. Each comment is classified by how well
7
+ * its anchor still matches the current section prose:
8
+ *
9
+ * clean – exact or whitespace-normalized hit
10
+ * drift – anchor only matches via stripped/partial fallbacks
11
+ * context-only – anchor text is gone, only surrounding context survives
12
+ * ambiguous – multiple matches, can't pick one without context
13
+ * unmatched – nothing maps; user must place the comment manually
14
+ */
15
+
16
+ import {
17
+ chalk,
18
+ fs,
19
+ path,
20
+ fmt,
21
+ loadConfig,
22
+ jsonMode,
23
+ jsonOutput,
24
+ } from './context.js';
25
+ import type { Command } from 'commander';
26
+ import { findAnchorInText, classifyStrategy, type AnchorMatchQuality } from '../anchor-match.js';
27
+ import type { CommentAnchorData } from '../word-extraction.js';
28
+ import { computeSectionBoundaries } from './section-boundaries.js';
29
+
30
+ interface VerifyOptions {
31
+ config: string;
32
+ dir: string;
33
+ json?: boolean;
34
+ }
35
+
36
+ interface CommentReport {
37
+ id: string;
38
+ author: string;
39
+ text: string;
40
+ section: string | null;
41
+ quality: AnchorMatchQuality | 'ambiguous';
42
+ strategy: string;
43
+ anchor: string;
44
+ occurrences: number;
45
+ }
46
+
47
+ export function register(program: Command): void {
48
+ program
49
+ .command('verify-anchors')
50
+ .description('Report drift between Word comment anchors and current markdown')
51
+ .argument('<file>', 'Word document with reviewer comments (.docx)')
52
+ .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
53
+ .option('-d, --dir <directory>', 'Directory with section files', '.')
54
+ .option('--json', 'Output JSON report (for scripting)')
55
+ .action(async (docxPath: string, options: VerifyOptions) => {
56
+ if (!fs.existsSync(docxPath)) {
57
+ console.error(fmt.status('error', `File not found: ${docxPath}`));
58
+ process.exit(1);
59
+ }
60
+
61
+ const configPath = path.resolve(options.dir, options.config);
62
+ if (!fs.existsSync(configPath)) {
63
+ console.error(fmt.status('error', `Config not found: ${configPath}`));
64
+ console.error(chalk.dim(' Run "rev init" first to generate sections.yaml'));
65
+ process.exit(1);
66
+ }
67
+
68
+ const config = loadConfig(configPath);
69
+ const { extractWordComments, extractCommentAnchors, extractHeadings } = await import('../import.js');
70
+
71
+ let comments;
72
+ let anchors;
73
+ let headings;
74
+ try {
75
+ comments = await extractWordComments(docxPath);
76
+ const result = await extractCommentAnchors(docxPath);
77
+ anchors = result.anchors;
78
+ headings = await extractHeadings(docxPath);
79
+ } catch (err) {
80
+ const error = err as Error;
81
+ console.error(fmt.status('error', `Failed to read ${path.basename(docxPath)}: ${error.message}`));
82
+ if (process.env.DEBUG) console.error(error.stack);
83
+ process.exit(1);
84
+ }
85
+
86
+ if (comments.length === 0) {
87
+ console.log(fmt.status('info', 'No comments found in document.'));
88
+ return;
89
+ }
90
+
91
+ const boundaries = computeSectionBoundaries(config.sections, headings);
92
+
93
+ // Cache section markdown contents on first read
94
+ const sectionCache = new Map<string, string>();
95
+ function loadSection(file: string): string | null {
96
+ if (sectionCache.has(file)) return sectionCache.get(file)!;
97
+ const sectionPath = path.join(options.dir, file);
98
+ if (!fs.existsSync(sectionPath)) return null;
99
+ const content = fs.readFileSync(sectionPath, 'utf-8');
100
+ sectionCache.set(file, content);
101
+ return content;
102
+ }
103
+
104
+ const firstBoundaryStart = boundaries.length > 0 ? boundaries[0].start : 0;
105
+ const reports: CommentReport[] = [];
106
+
107
+ for (const c of comments) {
108
+ const anchor: CommentAnchorData | undefined = anchors.get(c.id);
109
+ const anchorText = anchor?.anchor || '';
110
+ if (!anchor) {
111
+ reports.push({
112
+ id: c.id,
113
+ author: c.author,
114
+ text: c.text,
115
+ section: null,
116
+ quality: 'unmatched',
117
+ strategy: 'no-anchor',
118
+ anchor: '',
119
+ occurrences: 0,
120
+ });
121
+ continue;
122
+ }
123
+
124
+ // Determine which section file this comment lives in
125
+ let sectionFile: string | null = null;
126
+ for (const b of boundaries) {
127
+ if (anchor.docPosition >= b.start && anchor.docPosition < b.end) {
128
+ sectionFile = b.file;
129
+ break;
130
+ }
131
+ }
132
+ if (!sectionFile && boundaries.length > 0 && anchor.docPosition < firstBoundaryStart) {
133
+ sectionFile = boundaries[0].file;
134
+ }
135
+
136
+ if (!sectionFile) {
137
+ reports.push({
138
+ id: c.id,
139
+ author: c.author,
140
+ text: c.text,
141
+ section: null,
142
+ quality: 'unmatched',
143
+ strategy: 'no-section',
144
+ anchor: anchorText,
145
+ occurrences: 0,
146
+ });
147
+ continue;
148
+ }
149
+
150
+ const md = loadSection(sectionFile);
151
+ if (md === null) {
152
+ reports.push({
153
+ id: c.id,
154
+ author: c.author,
155
+ text: c.text,
156
+ section: sectionFile,
157
+ quality: 'unmatched',
158
+ strategy: 'missing-file',
159
+ anchor: anchorText,
160
+ occurrences: 0,
161
+ });
162
+ continue;
163
+ }
164
+
165
+ const search = findAnchorInText(anchor.anchor, md, anchor.before, anchor.after);
166
+ let quality: AnchorMatchQuality | 'ambiguous' = classifyStrategy(search.strategy, search.occurrences.length);
167
+ if (quality === 'clean' && search.occurrences.length > 1) {
168
+ quality = 'ambiguous';
169
+ }
170
+
171
+ reports.push({
172
+ id: c.id,
173
+ author: c.author,
174
+ text: c.text,
175
+ section: sectionFile,
176
+ quality,
177
+ strategy: search.strategy,
178
+ anchor: anchorText,
179
+ occurrences: search.occurrences.length,
180
+ });
181
+ }
182
+
183
+ if (options.json || jsonMode) {
184
+ jsonOutput({
185
+ file: docxPath,
186
+ totalComments: comments.length,
187
+ summary: tally(reports),
188
+ comments: reports,
189
+ });
190
+ return;
191
+ }
192
+
193
+ printReport(docxPath, reports);
194
+ });
195
+ }
196
+
197
+ function tally(reports: CommentReport[]): Record<string, number> {
198
+ const out: Record<string, number> = { clean: 0, drift: 0, 'context-only': 0, ambiguous: 0, unmatched: 0 };
199
+ for (const r of reports) out[r.quality] = (out[r.quality] || 0) + 1;
200
+ return out;
201
+ }
202
+
203
+ function printReport(docxPath: string, reports: CommentReport[]): void {
204
+ console.log(fmt.header(`Anchor Verification: ${path.basename(docxPath)}`));
205
+ console.log();
206
+
207
+ const totals = tally(reports);
208
+ const summaryLines: string[] = [];
209
+ summaryLines.push(`${chalk.green(totals.clean)} clean (anchor still matches)`);
210
+ if (totals.drift) summaryLines.push(`${chalk.cyan(totals.drift)} drifted (matched via fallback strategies)`);
211
+ if (totals['context-only']) summaryLines.push(`${chalk.yellow(totals['context-only'])} context-only (anchor text gone, neighbors survive)`);
212
+ if (totals.ambiguous) summaryLines.push(`${chalk.magenta(totals.ambiguous)} ambiguous (multiple candidate positions)`);
213
+ if (totals.unmatched) summaryLines.push(`${chalk.red(totals.unmatched)} unmatched (manual placement needed)`);
214
+ console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
215
+ console.log();
216
+
217
+ // Per-comment table for everything that isn't a clean direct hit
218
+ const problems = reports.filter(r => r.quality !== 'clean');
219
+ if (problems.length === 0) {
220
+ console.log(fmt.status('success', 'All comment anchors match the current markdown.'));
221
+ return;
222
+ }
223
+
224
+ const rows = problems.map(r => [
225
+ chalk.dim(`#${r.id}`),
226
+ qualityColor(r.quality),
227
+ r.section ? chalk.bold(r.section) : chalk.dim('—'),
228
+ chalk.dim(r.strategy),
229
+ truncate(r.anchor, 35),
230
+ truncate(r.text, 35),
231
+ ]);
232
+
233
+ console.log(fmt.table(
234
+ ['ID', 'Quality', 'Section', 'Strategy', 'Anchor (Word)', 'Comment'],
235
+ rows,
236
+ { align: ['right', 'left', 'left', 'left', 'left', 'left'] },
237
+ ));
238
+
239
+ if (totals.unmatched > 0 || totals.ambiguous > 0) {
240
+ console.log();
241
+ console.log(chalk.dim('Comments flagged "unmatched" or "ambiguous" need manual placement.'));
242
+ console.log(chalk.dim('Run "rev sync --no-overwrite" to import the matched ones without touching prose.'));
243
+ }
244
+ }
245
+
246
+ function qualityColor(q: string): string {
247
+ switch (q) {
248
+ case 'clean': return chalk.green('clean');
249
+ case 'drift': return chalk.cyan('drift');
250
+ case 'context-only': return chalk.yellow('context');
251
+ case 'ambiguous': return chalk.magenta('ambiguous');
252
+ case 'unmatched': return chalk.red('unmatched');
253
+ default: return q;
254
+ }
255
+ }
256
+
257
+ function truncate(s: string, max: number): string {
258
+ if (!s) return chalk.dim('—');
259
+ const flat = s.replace(/\s+/g, ' ').trim();
260
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
261
+ }
@@ -0,0 +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
+ }