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