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,454 +1,454 @@
1
- /**
2
- * Response commands: response, validate, profiles, anonymize
3
- *
4
- * Commands for generating reviewer responses and validating manuscripts.
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- collectComments,
14
- generateResponseLetter,
15
- groupByReviewer,
16
- getUserName,
17
- } from './context.js';
18
-
19
- interface ResponseOptions {
20
- output?: string;
21
- author?: string;
22
- context?: boolean;
23
- location?: boolean;
24
- }
25
-
26
- interface ValidateOptions {
27
- journal?: string;
28
- list?: boolean;
29
- }
30
-
31
- interface ProfilesOptions {
32
- list?: boolean;
33
- new?: string;
34
- project?: boolean;
35
- dirs?: boolean;
36
- fetchCsl?: string;
37
- listCsl?: boolean;
38
- }
39
-
40
- interface AnonymizeOptions {
41
- output?: string;
42
- authors?: string;
43
- dryRun?: boolean;
44
- }
45
-
46
- /**
47
- * Register response commands with the program
48
- */
49
- export function register(program: Command): void {
50
- // ==========================================================================
51
- // RESPONSE command - Generate response letter for reviewers
52
- // ==========================================================================
53
-
54
- program
55
- .command('response')
56
- .description('Generate response letter from reviewer comments')
57
- .argument('[files...]', 'Markdown files to process (default: all section files)')
58
- .option('-o, --output <file>', 'Output file (default: response-letter.md)')
59
- .option('-a, --author <name>', 'Author name for identifying replies')
60
- .option('--no-context', 'Omit context snippets')
61
- .option('--no-location', 'Omit file:line references')
62
- .action(async (files: string[] | undefined, options: ResponseOptions) => {
63
- let mdFiles = files;
64
- if (!mdFiles || mdFiles.length === 0) {
65
- const allFiles = fs.readdirSync('.').filter(f =>
66
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
67
- );
68
- mdFiles = allFiles;
69
- }
70
-
71
- if (mdFiles.length === 0) {
72
- console.error(fmt.status('error', 'No markdown files found'));
73
- process.exit(1);
74
- }
75
-
76
- const spin = fmt.spinner('Collecting comments...').start();
77
-
78
- const comments = collectComments(mdFiles);
79
- spin.stop();
80
-
81
- if (comments.length === 0) {
82
- console.log(fmt.status('info', 'No comments found in files'));
83
- return;
84
- }
85
-
86
- const letter = generateResponseLetter(comments, {
87
- authorName: options.author || getUserName() || 'Author',
88
- includeContext: options.context !== false,
89
- includeLocation: options.location !== false,
90
- });
91
-
92
- const outputPath = options.output || 'response-letter.md';
93
- fs.writeFileSync(outputPath, letter, 'utf-8');
94
-
95
- const grouped = groupByReviewer(comments);
96
- const reviewers = [...grouped.keys()].filter(r =>
97
- !r.toLowerCase().includes('claude') &&
98
- r.toLowerCase() !== (options.author || '').toLowerCase()
99
- );
100
-
101
- console.log(fmt.header('Response Letter Generated'));
102
- console.log();
103
-
104
- const rows = reviewers.map(r => [r, grouped.get(r)!.length.toString()]);
105
- console.log(fmt.table(['Reviewer', 'Comments'], rows));
106
- console.log();
107
- console.log(fmt.status('success', `Created ${outputPath}`));
108
- });
109
-
110
- // ==========================================================================
111
- // VALIDATE command - Check manuscript against journal requirements
112
- // ==========================================================================
113
-
114
- program
115
- .command('validate')
116
- .description('Validate manuscript against journal requirements')
117
- .argument('[files...]', 'Markdown files to validate (default: all section files)')
118
- .option('-j, --journal <name>', 'Journal profile (e.g., nature, plos-one, science)')
119
- .option('--list', 'List available journal profiles')
120
- .action(async (files: string[] | undefined, options: ValidateOptions) => {
121
- const { listJournals, validateProject, getJournalProfile } = await import('../journals.js');
122
-
123
- if (options.list) {
124
- console.log(fmt.header('Available Journal Profiles'));
125
- console.log();
126
- const journals = listJournals();
127
- const builtIn = journals.filter(j => !j.custom);
128
- const custom = journals.filter(j => j.custom);
129
-
130
- for (const j of builtIn) {
131
- const profile = getJournalProfile(j.id);
132
- const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
133
- console.log(` ${chalk.bold(j.id)} - ${j.name}${fmtTag}`);
134
- if (j.url) console.log(chalk.dim(` ${j.url}`));
135
- }
136
-
137
- if (custom.length > 0) {
138
- console.log();
139
- console.log(chalk.cyan(' Custom Profiles:'));
140
- for (const j of custom) {
141
- const profile = getJournalProfile(j.id);
142
- const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
143
- console.log(` ${chalk.bold(j.id)} - ${j.name} ${chalk.cyan('[custom]')}${fmtTag}`);
144
- if (j.url) console.log(chalk.dim(` ${j.url}`));
145
- }
146
- }
147
-
148
- console.log();
149
- console.log(chalk.dim('Usage: rev validate --journal <name>'));
150
- console.log(chalk.dim('Profiles with [formatting] can also be used with: rev build -j <name>'));
151
- console.log(chalk.dim('Manage custom profiles: rev profiles'));
152
- return;
153
- }
154
-
155
- if (!options.journal) {
156
- console.error(fmt.status('error', 'Please specify a journal with --journal <name>'));
157
- console.error(chalk.dim('Use --list to see available profiles'));
158
- process.exit(1);
159
- }
160
-
161
- const profile = getJournalProfile(options.journal);
162
- if (!profile) {
163
- console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
164
- console.error(chalk.dim('Use --list to see available profiles'));
165
- process.exit(1);
166
- }
167
-
168
- let mdFiles = files;
169
- if (!mdFiles || mdFiles.length === 0) {
170
- mdFiles = fs.readdirSync('.').filter(f =>
171
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
172
- );
173
- }
174
-
175
- if (mdFiles.length === 0) {
176
- console.error(fmt.status('error', 'No markdown files found'));
177
- process.exit(1);
178
- }
179
-
180
- console.log(fmt.header(`Validating for ${profile.name}`));
181
- console.log(chalk.dim(` ${profile.url}`));
182
- console.log();
183
-
184
- const result = validateProject(mdFiles, options.journal);
185
-
186
- if (result.stats) {
187
- console.log(chalk.cyan('Manuscript Stats:'));
188
- console.log(fmt.table(['Metric', 'Value'], [
189
- ['Word count', result.stats.wordCount.toString()],
190
- ['Abstract', `${result.stats.abstractWords} words`],
191
- ['Title', `${result.stats.titleChars} chars`],
192
- ['Figures', result.stats.figures.toString()],
193
- ['Tables', result.stats.tables.toString()],
194
- ['References', result.stats.references.toString()],
195
- ]));
196
- console.log();
197
- }
198
-
199
- if (result.errors.length > 0) {
200
- console.log(chalk.red('Errors:'));
201
- for (const err of result.errors) {
202
- console.log(chalk.red(` ✗ ${err}`));
203
- }
204
- console.log();
205
- }
206
-
207
- if (result.warnings.length > 0) {
208
- console.log(chalk.yellow('Warnings:'));
209
- for (const warn of result.warnings) {
210
- console.log(chalk.yellow(` ⚠ ${warn}`));
211
- }
212
- console.log();
213
- }
214
-
215
- if (result.valid) {
216
- console.log(fmt.status('success', `Manuscript meets ${profile.name} requirements`));
217
- } else {
218
- console.log(fmt.status('error', `Manuscript has ${result.errors.length} error(s)`));
219
- process.exit(1);
220
- }
221
- });
222
-
223
- // ==========================================================================
224
- // PROFILES command - Manage custom journal profiles
225
- // ==========================================================================
226
-
227
- program
228
- .command('profiles')
229
- .description('Manage custom journal profiles')
230
- .option('--list', 'List all custom profiles')
231
- .option('--new <name>', 'Create a new profile template')
232
- .option('--project', 'Create profile in project directory (with --new)')
233
- .option('--dirs', 'Show profile directory locations')
234
- .option('--fetch-csl <name>', 'Download a CSL citation style to cache')
235
- .option('--list-csl', 'List cached CSL citation styles')
236
- .action(async (options: ProfilesOptions) => {
237
- const {
238
- listCustomProfiles,
239
- saveProfileTemplate,
240
- getPluginDirs,
241
- } = await import('../plugins.js');
242
- const { listJournals } = await import('../journals.js');
243
-
244
- if (options.listCsl) {
245
- const { listCachedCSL, getCSLCacheDir } = await import('../csl.js');
246
- const cached = listCachedCSL();
247
- console.log(fmt.header('Cached CSL Styles'));
248
- console.log(chalk.dim(` ${getCSLCacheDir()}`));
249
- console.log();
250
- if (cached.length === 0) {
251
- console.log(chalk.dim(' No cached styles. Download with: rev profiles --fetch-csl <name>'));
252
- } else {
253
- for (const c of cached) {
254
- console.log(` ${chalk.bold(c.name)}`);
255
- }
256
- console.log();
257
- console.log(chalk.dim(` ${cached.length} cached style(s)`));
258
- }
259
- return;
260
- }
261
-
262
- if (options.fetchCsl) {
263
- const { fetchCSL, resolveCSL, getCSLAliases } = await import('../csl.js');
264
-
265
- // Check if already cached
266
- const existing = resolveCSL(options.fetchCsl);
267
- if (existing) {
268
- console.log(fmt.status('info', `Already cached: ${existing}`));
269
- return;
270
- }
271
-
272
- const spin = fmt.spinner(`Downloading CSL style "${options.fetchCsl}"...`).start();
273
- const result = await fetchCSL(options.fetchCsl);
274
- spin.stop();
275
-
276
- if (result) {
277
- console.log(fmt.status('success', `Downloaded: ${result}`));
278
- } else {
279
- console.error(fmt.status('error', `Could not download CSL style "${options.fetchCsl}"`));
280
- const aliases = getCSLAliases();
281
- const names = Object.keys(aliases).sort().join(', ');
282
- console.error(chalk.dim(` Known short names: ${names}`));
283
- process.exit(1);
284
- }
285
- return;
286
- }
287
-
288
- if (options.dirs) {
289
- const dirs = getPluginDirs();
290
- console.log(fmt.header('Profile Directories'));
291
- console.log();
292
- console.log(` User: ${dirs.user}`);
293
- console.log(chalk.dim(` ${dirs.userExists ? 'exists' : 'not created'}`));
294
- console.log();
295
- console.log(` Project: ${dirs.project}`);
296
- console.log(chalk.dim(` ${dirs.projectExists ? 'exists' : 'not created'}`));
297
- console.log();
298
- console.log(chalk.dim('Use --new <name> to create a profile template'));
299
- return;
300
- }
301
-
302
- if (options.new) {
303
- try {
304
- const filePath = saveProfileTemplate(options.new, options.project);
305
- console.log(fmt.status('success', `Created profile template: ${filePath}`));
306
- console.log(chalk.dim('Edit the file to customize journal requirements'));
307
- } catch (err) {
308
- console.error(fmt.status('error', (err as Error).message));
309
- process.exit(1);
310
- }
311
- return;
312
- }
313
-
314
- console.log(fmt.header('Custom Journal Profiles'));
315
- console.log();
316
-
317
- const customProfiles = listCustomProfiles();
318
-
319
- if (customProfiles.length === 0) {
320
- console.log(chalk.dim(' No custom profiles found'));
321
- console.log();
322
- console.log(chalk.dim(' Create one with: rev profiles --new "Journal Name"'));
323
- console.log();
324
- const dirs = getPluginDirs();
325
- console.log(chalk.dim(` User profiles: ${dirs.user}`));
326
- console.log(chalk.dim(` Project profiles: ${dirs.project}`));
327
- } else {
328
- for (const p of customProfiles) {
329
- const source = p.source === 'project' ? chalk.cyan('[project]') : chalk.dim('[user]');
330
- console.log(` ${chalk.bold(p.id)} - ${p.name} ${source}`);
331
- console.log(chalk.dim(` ${p.path}`));
332
- }
333
- console.log();
334
- console.log(chalk.dim(` ${customProfiles.length} custom profile(s)`));
335
- }
336
-
337
- console.log();
338
-
339
- const allJournals = listJournals();
340
- const builtIn = allJournals.filter(j => !j.custom).length;
341
- console.log(chalk.dim(` ${builtIn} built-in profiles available (rev validate --list)`));
342
- });
343
-
344
- // ==========================================================================
345
- // ANONYMIZE command - Prepare document for blind review
346
- // ==========================================================================
347
-
348
- program
349
- .command('anonymize')
350
- .description('Prepare document for blind review')
351
- .argument('<input>', 'Input markdown file or directory')
352
- .option('-o, --output <file>', 'Output file (default: input-anonymous.md)')
353
- .option('--authors <names>', 'Author names to redact (comma-separated)')
354
- .option('--dry-run', 'Show what would be changed without writing')
355
- .action(async (input: string, options: AnonymizeOptions) => {
356
- const { default: YAML } = await import('yaml');
357
-
358
- const isDir = fs.existsSync(input) && fs.statSync(input).isDirectory();
359
- const files = isDir
360
- ? fs.readdirSync(input)
361
- .filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f))
362
- .map(f => path.join(input, f))
363
- : [input];
364
-
365
- if (files.length === 0) {
366
- console.error(fmt.status('error', 'No markdown files found'));
367
- process.exit(1);
368
- }
369
-
370
- let authorNames: string[] = [];
371
- if (options.authors) {
372
- authorNames = options.authors.split(',').map(n => n.trim());
373
- } else {
374
- const configPath = isDir ? path.join(input, 'rev.yaml') : 'rev.yaml';
375
- if (fs.existsSync(configPath)) {
376
- try {
377
- const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
378
- if (config.authors) {
379
- authorNames = config.authors.map((a: string | { name: string }) => typeof a === 'string' ? a : a.name).filter(Boolean);
380
- }
381
- } catch { /* ignore */ }
382
- }
383
- }
384
-
385
- console.log(fmt.header('Anonymizing Document'));
386
- console.log();
387
-
388
- let totalChanges = 0;
389
-
390
- for (const file of files) {
391
- if (!fs.existsSync(file)) {
392
- console.error(chalk.yellow(` Skipping: ${file} (not found)`));
393
- continue;
394
- }
395
-
396
- let text = fs.readFileSync(file, 'utf-8');
397
- let changes = 0;
398
-
399
- text = text.replace(/^---\n([\s\S]*?)\n---/, (match, fm) => {
400
- let modified = fm;
401
- modified = modified.replace(/^author:.*(?:\n(?: |\t).*)*$/m, '');
402
- modified = modified.replace(/^authors:.*(?:\n(?: |\t|-\s+).*)*$/m, '');
403
- modified = modified.replace(/^affiliation:.*$/m, '');
404
- modified = modified.replace(/^email:.*$/m, '');
405
- if (modified !== fm) changes++;
406
- return '---\n' + modified.replace(/\n{3,}/g, '\n\n').trim() + '\n---';
407
- });
408
-
409
- const ackPatterns = [
410
- /^#+\s*Acknowledgments?[\s\S]*?(?=^#|\Z)/gmi,
411
- /^#+\s*Funding[\s\S]*?(?=^#|\Z)/gmi,
412
- ];
413
- for (const pattern of ackPatterns) {
414
- const before = text;
415
- text = text.replace(pattern, '');
416
- if (text !== before) changes++;
417
- }
418
-
419
- for (const name of authorNames) {
420
- const namePattern = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi');
421
- const before = text;
422
- text = text.replace(namePattern, '[AUTHOR]');
423
- if (text !== before) changes++;
424
- }
425
-
426
- for (const name of authorNames) {
427
- const lastName = name.split(/\s+/).pop();
428
- if (lastName && lastName.length > 2) {
429
- const citePat = new RegExp(`@${lastName}(\\d{4})`, 'gi');
430
- const before = text;
431
- text = text.replace(citePat, '@AUTHOR$1');
432
- if (text !== before) changes++;
433
- }
434
- }
435
-
436
- totalChanges += changes;
437
-
438
- if (options.dryRun) {
439
- console.log(chalk.dim(` ${path.basename(file)}: ${changes} change(s)`));
440
- } else {
441
- const outPath = options.output || file.replace(/\.md$/, '-anonymous.md');
442
- fs.writeFileSync(outPath, text, 'utf-8');
443
- console.log(fmt.status('success', `${path.basename(file)} → ${path.basename(outPath)} (${changes} changes)`));
444
- }
445
- }
446
-
447
- console.log();
448
- if (options.dryRun) {
449
- console.log(chalk.dim(` Total: ${totalChanges} change(s) would be made`));
450
- } else {
451
- console.log(fmt.status('success', `Anonymized ${files.length} file(s)`));
452
- }
453
- });
454
- }
1
+ /**
2
+ * Response commands: response, validate, profiles, anonymize
3
+ *
4
+ * Commands for generating reviewer responses and validating manuscripts.
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ collectComments,
14
+ generateResponseLetter,
15
+ groupByReviewer,
16
+ getUserName,
17
+ } from './context.js';
18
+
19
+ interface ResponseOptions {
20
+ output?: string;
21
+ author?: string;
22
+ context?: boolean;
23
+ location?: boolean;
24
+ }
25
+
26
+ interface ValidateOptions {
27
+ journal?: string;
28
+ list?: boolean;
29
+ }
30
+
31
+ interface ProfilesOptions {
32
+ list?: boolean;
33
+ new?: string;
34
+ project?: boolean;
35
+ dirs?: boolean;
36
+ fetchCsl?: string;
37
+ listCsl?: boolean;
38
+ }
39
+
40
+ interface AnonymizeOptions {
41
+ output?: string;
42
+ authors?: string;
43
+ dryRun?: boolean;
44
+ }
45
+
46
+ /**
47
+ * Register response commands with the program
48
+ */
49
+ export function register(program: Command): void {
50
+ // ==========================================================================
51
+ // RESPONSE command - Generate response letter for reviewers
52
+ // ==========================================================================
53
+
54
+ program
55
+ .command('response')
56
+ .description('Generate response letter from reviewer comments')
57
+ .argument('[files...]', 'Markdown files to process (default: all section files)')
58
+ .option('-o, --output <file>', 'Output file (default: response-letter.md)')
59
+ .option('-a, --author <name>', 'Author name for identifying replies')
60
+ .option('--no-context', 'Omit context snippets')
61
+ .option('--no-location', 'Omit file:line references')
62
+ .action(async (files: string[] | undefined, options: ResponseOptions) => {
63
+ let mdFiles = files;
64
+ if (!mdFiles || mdFiles.length === 0) {
65
+ const allFiles = fs.readdirSync('.').filter(f =>
66
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
67
+ );
68
+ mdFiles = allFiles;
69
+ }
70
+
71
+ if (mdFiles.length === 0) {
72
+ console.error(fmt.status('error', 'No markdown files found'));
73
+ process.exit(1);
74
+ }
75
+
76
+ const spin = fmt.spinner('Collecting comments...').start();
77
+
78
+ const comments = collectComments(mdFiles);
79
+ spin.stop();
80
+
81
+ if (comments.length === 0) {
82
+ console.log(fmt.status('info', 'No comments found in files'));
83
+ return;
84
+ }
85
+
86
+ const letter = generateResponseLetter(comments, {
87
+ authorName: options.author || getUserName() || 'Author',
88
+ includeContext: options.context !== false,
89
+ includeLocation: options.location !== false,
90
+ });
91
+
92
+ const outputPath = options.output || 'response-letter.md';
93
+ fs.writeFileSync(outputPath, letter, 'utf-8');
94
+
95
+ const grouped = groupByReviewer(comments);
96
+ const reviewers = [...grouped.keys()].filter(r =>
97
+ !r.toLowerCase().includes('claude') &&
98
+ r.toLowerCase() !== (options.author || '').toLowerCase()
99
+ );
100
+
101
+ console.log(fmt.header('Response Letter Generated'));
102
+ console.log();
103
+
104
+ const rows = reviewers.map(r => [r, grouped.get(r)!.length.toString()]);
105
+ console.log(fmt.table(['Reviewer', 'Comments'], rows));
106
+ console.log();
107
+ console.log(fmt.status('success', `Created ${outputPath}`));
108
+ });
109
+
110
+ // ==========================================================================
111
+ // VALIDATE command - Check manuscript against journal requirements
112
+ // ==========================================================================
113
+
114
+ program
115
+ .command('validate')
116
+ .description('Validate manuscript against journal requirements')
117
+ .argument('[files...]', 'Markdown files to validate (default: all section files)')
118
+ .option('-j, --journal <name>', 'Journal profile (e.g., nature, plos-one, science)')
119
+ .option('--list', 'List available journal profiles')
120
+ .action(async (files: string[] | undefined, options: ValidateOptions) => {
121
+ const { listJournals, validateProject, getJournalProfile } = await import('../journals.js');
122
+
123
+ if (options.list) {
124
+ console.log(fmt.header('Available Journal Profiles'));
125
+ console.log();
126
+ const journals = listJournals();
127
+ const builtIn = journals.filter(j => !j.custom);
128
+ const custom = journals.filter(j => j.custom);
129
+
130
+ for (const j of builtIn) {
131
+ const profile = getJournalProfile(j.id);
132
+ const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
133
+ console.log(` ${chalk.bold(j.id)} - ${j.name}${fmtTag}`);
134
+ if (j.url) console.log(chalk.dim(` ${j.url}`));
135
+ }
136
+
137
+ if (custom.length > 0) {
138
+ console.log();
139
+ console.log(chalk.cyan(' Custom Profiles:'));
140
+ for (const j of custom) {
141
+ const profile = getJournalProfile(j.id);
142
+ const fmtTag = profile?.formatting ? chalk.green(' [formatting]') : '';
143
+ console.log(` ${chalk.bold(j.id)} - ${j.name} ${chalk.cyan('[custom]')}${fmtTag}`);
144
+ if (j.url) console.log(chalk.dim(` ${j.url}`));
145
+ }
146
+ }
147
+
148
+ console.log();
149
+ console.log(chalk.dim('Usage: rev validate --journal <name>'));
150
+ console.log(chalk.dim('Profiles with [formatting] can also be used with: rev build -j <name>'));
151
+ console.log(chalk.dim('Manage custom profiles: rev profiles'));
152
+ return;
153
+ }
154
+
155
+ if (!options.journal) {
156
+ console.error(fmt.status('error', 'Please specify a journal with --journal <name>'));
157
+ console.error(chalk.dim('Use --list to see available profiles'));
158
+ process.exit(1);
159
+ }
160
+
161
+ const profile = getJournalProfile(options.journal);
162
+ if (!profile) {
163
+ console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
164
+ console.error(chalk.dim('Use --list to see available profiles'));
165
+ process.exit(1);
166
+ }
167
+
168
+ let mdFiles = files;
169
+ if (!mdFiles || mdFiles.length === 0) {
170
+ mdFiles = fs.readdirSync('.').filter(f =>
171
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
172
+ );
173
+ }
174
+
175
+ if (mdFiles.length === 0) {
176
+ console.error(fmt.status('error', 'No markdown files found'));
177
+ process.exit(1);
178
+ }
179
+
180
+ console.log(fmt.header(`Validating for ${profile.name}`));
181
+ console.log(chalk.dim(` ${profile.url}`));
182
+ console.log();
183
+
184
+ const result = validateProject(mdFiles, options.journal);
185
+
186
+ if (result.stats) {
187
+ console.log(chalk.cyan('Manuscript Stats:'));
188
+ console.log(fmt.table(['Metric', 'Value'], [
189
+ ['Word count', result.stats.wordCount.toString()],
190
+ ['Abstract', `${result.stats.abstractWords} words`],
191
+ ['Title', `${result.stats.titleChars} chars`],
192
+ ['Figures', result.stats.figures.toString()],
193
+ ['Tables', result.stats.tables.toString()],
194
+ ['References', result.stats.references.toString()],
195
+ ]));
196
+ console.log();
197
+ }
198
+
199
+ if (result.errors.length > 0) {
200
+ console.log(chalk.red('Errors:'));
201
+ for (const err of result.errors) {
202
+ console.log(chalk.red(` ✗ ${err}`));
203
+ }
204
+ console.log();
205
+ }
206
+
207
+ if (result.warnings.length > 0) {
208
+ console.log(chalk.yellow('Warnings:'));
209
+ for (const warn of result.warnings) {
210
+ console.log(chalk.yellow(` ⚠ ${warn}`));
211
+ }
212
+ console.log();
213
+ }
214
+
215
+ if (result.valid) {
216
+ console.log(fmt.status('success', `Manuscript meets ${profile.name} requirements`));
217
+ } else {
218
+ console.log(fmt.status('error', `Manuscript has ${result.errors.length} error(s)`));
219
+ process.exit(1);
220
+ }
221
+ });
222
+
223
+ // ==========================================================================
224
+ // PROFILES command - Manage custom journal profiles
225
+ // ==========================================================================
226
+
227
+ program
228
+ .command('profiles')
229
+ .description('Manage custom journal profiles')
230
+ .option('--list', 'List all custom profiles')
231
+ .option('--new <name>', 'Create a new profile template')
232
+ .option('--project', 'Create profile in project directory (with --new)')
233
+ .option('--dirs', 'Show profile directory locations')
234
+ .option('--fetch-csl <name>', 'Download a CSL citation style to cache')
235
+ .option('--list-csl', 'List cached CSL citation styles')
236
+ .action(async (options: ProfilesOptions) => {
237
+ const {
238
+ listCustomProfiles,
239
+ saveProfileTemplate,
240
+ getPluginDirs,
241
+ } = await import('../plugins.js');
242
+ const { listJournals } = await import('../journals.js');
243
+
244
+ if (options.listCsl) {
245
+ const { listCachedCSL, getCSLCacheDir } = await import('../csl.js');
246
+ const cached = listCachedCSL();
247
+ console.log(fmt.header('Cached CSL Styles'));
248
+ console.log(chalk.dim(` ${getCSLCacheDir()}`));
249
+ console.log();
250
+ if (cached.length === 0) {
251
+ console.log(chalk.dim(' No cached styles. Download with: rev profiles --fetch-csl <name>'));
252
+ } else {
253
+ for (const c of cached) {
254
+ console.log(` ${chalk.bold(c.name)}`);
255
+ }
256
+ console.log();
257
+ console.log(chalk.dim(` ${cached.length} cached style(s)`));
258
+ }
259
+ return;
260
+ }
261
+
262
+ if (options.fetchCsl) {
263
+ const { fetchCSL, resolveCSL, getCSLAliases } = await import('../csl.js');
264
+
265
+ // Check if already cached
266
+ const existing = resolveCSL(options.fetchCsl);
267
+ if (existing) {
268
+ console.log(fmt.status('info', `Already cached: ${existing}`));
269
+ return;
270
+ }
271
+
272
+ const spin = fmt.spinner(`Downloading CSL style "${options.fetchCsl}"...`).start();
273
+ const result = await fetchCSL(options.fetchCsl);
274
+ spin.stop();
275
+
276
+ if (result) {
277
+ console.log(fmt.status('success', `Downloaded: ${result}`));
278
+ } else {
279
+ console.error(fmt.status('error', `Could not download CSL style "${options.fetchCsl}"`));
280
+ const aliases = getCSLAliases();
281
+ const names = Object.keys(aliases).sort().join(', ');
282
+ console.error(chalk.dim(` Known short names: ${names}`));
283
+ process.exit(1);
284
+ }
285
+ return;
286
+ }
287
+
288
+ if (options.dirs) {
289
+ const dirs = getPluginDirs();
290
+ console.log(fmt.header('Profile Directories'));
291
+ console.log();
292
+ console.log(` User: ${dirs.user}`);
293
+ console.log(chalk.dim(` ${dirs.userExists ? 'exists' : 'not created'}`));
294
+ console.log();
295
+ console.log(` Project: ${dirs.project}`);
296
+ console.log(chalk.dim(` ${dirs.projectExists ? 'exists' : 'not created'}`));
297
+ console.log();
298
+ console.log(chalk.dim('Use --new <name> to create a profile template'));
299
+ return;
300
+ }
301
+
302
+ if (options.new) {
303
+ try {
304
+ const filePath = saveProfileTemplate(options.new, options.project);
305
+ console.log(fmt.status('success', `Created profile template: ${filePath}`));
306
+ console.log(chalk.dim('Edit the file to customize journal requirements'));
307
+ } catch (err) {
308
+ console.error(fmt.status('error', (err as Error).message));
309
+ process.exit(1);
310
+ }
311
+ return;
312
+ }
313
+
314
+ console.log(fmt.header('Custom Journal Profiles'));
315
+ console.log();
316
+
317
+ const customProfiles = listCustomProfiles();
318
+
319
+ if (customProfiles.length === 0) {
320
+ console.log(chalk.dim(' No custom profiles found'));
321
+ console.log();
322
+ console.log(chalk.dim(' Create one with: rev profiles --new "Journal Name"'));
323
+ console.log();
324
+ const dirs = getPluginDirs();
325
+ console.log(chalk.dim(` User profiles: ${dirs.user}`));
326
+ console.log(chalk.dim(` Project profiles: ${dirs.project}`));
327
+ } else {
328
+ for (const p of customProfiles) {
329
+ const source = p.source === 'project' ? chalk.cyan('[project]') : chalk.dim('[user]');
330
+ console.log(` ${chalk.bold(p.id)} - ${p.name} ${source}`);
331
+ console.log(chalk.dim(` ${p.path}`));
332
+ }
333
+ console.log();
334
+ console.log(chalk.dim(` ${customProfiles.length} custom profile(s)`));
335
+ }
336
+
337
+ console.log();
338
+
339
+ const allJournals = listJournals();
340
+ const builtIn = allJournals.filter(j => !j.custom).length;
341
+ console.log(chalk.dim(` ${builtIn} built-in profiles available (rev validate --list)`));
342
+ });
343
+
344
+ // ==========================================================================
345
+ // ANONYMIZE command - Prepare document for blind review
346
+ // ==========================================================================
347
+
348
+ program
349
+ .command('anonymize')
350
+ .description('Prepare document for blind review')
351
+ .argument('<input>', 'Input markdown file or directory')
352
+ .option('-o, --output <file>', 'Output file (default: input-anonymous.md)')
353
+ .option('--authors <names>', 'Author names to redact (comma-separated)')
354
+ .option('--dry-run', 'Show what would be changed without writing')
355
+ .action(async (input: string, options: AnonymizeOptions) => {
356
+ const { default: YAML } = await import('yaml');
357
+
358
+ const isDir = fs.existsSync(input) && fs.statSync(input).isDirectory();
359
+ const files = isDir
360
+ ? fs.readdirSync(input)
361
+ .filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f))
362
+ .map(f => path.join(input, f))
363
+ : [input];
364
+
365
+ if (files.length === 0) {
366
+ console.error(fmt.status('error', 'No markdown files found'));
367
+ process.exit(1);
368
+ }
369
+
370
+ let authorNames: string[] = [];
371
+ if (options.authors) {
372
+ authorNames = options.authors.split(',').map(n => n.trim());
373
+ } else {
374
+ const configPath = isDir ? path.join(input, 'rev.yaml') : 'rev.yaml';
375
+ if (fs.existsSync(configPath)) {
376
+ try {
377
+ const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
378
+ if (config.authors) {
379
+ authorNames = config.authors.map((a: string | { name: string }) => typeof a === 'string' ? a : a.name).filter(Boolean);
380
+ }
381
+ } catch { /* ignore */ }
382
+ }
383
+ }
384
+
385
+ console.log(fmt.header('Anonymizing Document'));
386
+ console.log();
387
+
388
+ let totalChanges = 0;
389
+
390
+ for (const file of files) {
391
+ if (!fs.existsSync(file)) {
392
+ console.error(chalk.yellow(` Skipping: ${file} (not found)`));
393
+ continue;
394
+ }
395
+
396
+ let text = fs.readFileSync(file, 'utf-8');
397
+ let changes = 0;
398
+
399
+ text = text.replace(/^---\n([\s\S]*?)\n---/, (match, fm) => {
400
+ let modified = fm;
401
+ modified = modified.replace(/^author:.*(?:\n(?: |\t).*)*$/m, '');
402
+ modified = modified.replace(/^authors:.*(?:\n(?: |\t|-\s+).*)*$/m, '');
403
+ modified = modified.replace(/^affiliation:.*$/m, '');
404
+ modified = modified.replace(/^email:.*$/m, '');
405
+ if (modified !== fm) changes++;
406
+ return '---\n' + modified.replace(/\n{3,}/g, '\n\n').trim() + '\n---';
407
+ });
408
+
409
+ const ackPatterns = [
410
+ /^#+\s*Acknowledgments?[\s\S]*?(?=^#|\Z)/gmi,
411
+ /^#+\s*Funding[\s\S]*?(?=^#|\Z)/gmi,
412
+ ];
413
+ for (const pattern of ackPatterns) {
414
+ const before = text;
415
+ text = text.replace(pattern, '');
416
+ if (text !== before) changes++;
417
+ }
418
+
419
+ for (const name of authorNames) {
420
+ const namePattern = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi');
421
+ const before = text;
422
+ text = text.replace(namePattern, '[AUTHOR]');
423
+ if (text !== before) changes++;
424
+ }
425
+
426
+ for (const name of authorNames) {
427
+ const lastName = name.split(/\s+/).pop();
428
+ if (lastName && lastName.length > 2) {
429
+ const citePat = new RegExp(`@${lastName}(\\d{4})`, 'gi');
430
+ const before = text;
431
+ text = text.replace(citePat, '@AUTHOR$1');
432
+ if (text !== before) changes++;
433
+ }
434
+ }
435
+
436
+ totalChanges += changes;
437
+
438
+ if (options.dryRun) {
439
+ console.log(chalk.dim(` ${path.basename(file)}: ${changes} change(s)`));
440
+ } else {
441
+ const outPath = options.output || file.replace(/\.md$/, '-anonymous.md');
442
+ fs.writeFileSync(outPath, text, 'utf-8');
443
+ console.log(fmt.status('success', `${path.basename(file)} → ${path.basename(outPath)} (${changes} changes)`));
444
+ }
445
+ }
446
+
447
+ console.log();
448
+ if (options.dryRun) {
449
+ console.log(chalk.dim(` Total: ${totalChanges} change(s) would be made`));
450
+ } else {
451
+ console.log(fmt.status('success', `Anonymized ${files.length} file(s)`));
452
+ }
453
+ });
454
+ }