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,517 +1,517 @@
1
- /**
2
- * Quality commands: lint, grammar, check
3
- *
4
- * Commands for checking project quality before submission.
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- loadBuildConfig,
14
- getComments,
15
- } from './context.js';
16
-
17
- // Use the actual BuildConfig from build.ts which allows string|Author[]
18
- type BuildConfig = ReturnType<typeof loadBuildConfig>;
19
-
20
- // Options interfaces
21
- interface LintOptions {
22
- fix?: boolean;
23
- }
24
-
25
- interface GrammarOptions {
26
- learn?: string;
27
- forget?: string;
28
- list?: boolean;
29
- rules?: boolean;
30
- scientific?: boolean;
31
- severity?: string;
32
- }
33
-
34
- interface CheckOptions {
35
- fix?: boolean;
36
- severity?: string;
37
- }
38
-
39
- // Grammar issue interface (from grammar.ts)
40
- interface GrammarIssue {
41
- rule: string;
42
- severity: 'error' | 'warning' | 'info';
43
- message: string;
44
- line: number;
45
- column: number;
46
- match: string;
47
- context: string;
48
- file?: string;
49
- }
50
-
51
- // Grammar summary interface (from grammar.ts)
52
- interface GrammarSummary {
53
- total: number;
54
- errors: number;
55
- warnings: number;
56
- info: number;
57
- byRule?: Record<string, number>;
58
- }
59
-
60
- // Lint issue interface
61
- interface LintIssue {
62
- type: 'error' | 'warning';
63
- message: string;
64
- fix?: string | null;
65
- file?: string;
66
- }
67
-
68
- // Build result interface - matches build.ts export
69
- interface BuildResult {
70
- format: string;
71
- success: boolean;
72
- outputPath?: string;
73
- error?: string;
74
- }
75
-
76
- // Full build result interface - matches build.ts FullBuildResult
77
- interface FullBuildResult {
78
- results: BuildResult[];
79
- paperPath: string;
80
- warnings: string[];
81
- forwardRefsResolved: number;
82
- refsAutoInjected?: boolean;
83
- }
84
-
85
- /**
86
- * Register quality commands with the program
87
- */
88
- export function register(program: Command): void {
89
- // ==========================================================================
90
- // LINT command - Check for common issues
91
- // ==========================================================================
92
-
93
- program
94
- .command('lint')
95
- .description('Check for common issues in the project')
96
- .option('--fix', 'Auto-fix issues where possible')
97
- .action(async (_options: LintOptions) => {
98
- let config: Partial<BuildConfig> = {};
99
- try {
100
- config = loadBuildConfig('.') || {};
101
- } catch {
102
- // Not in a rev project, that's ok
103
- }
104
- let sections = config.sections || [];
105
-
106
- if (sections.length === 0) {
107
- sections = fs.readdirSync('.').filter(f =>
108
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
109
- );
110
- }
111
-
112
- const issues: LintIssue[] = [];
113
- const warnings: LintIssue[] = [];
114
-
115
- // Collect all content
116
- let allText = '';
117
- for (const section of sections) {
118
- if (fs.existsSync(section)) {
119
- allText += fs.readFileSync(section, 'utf-8') + '\n';
120
- }
121
- }
122
-
123
- // Check 1: Broken cross-references
124
- const figAnchors = new Set<string>();
125
- const tblAnchors = new Set<string>();
126
- const eqAnchors = new Set<string>();
127
-
128
- const anchorPattern = /\{#(fig|tbl|eq):([^}]+)\}/g;
129
- let match: RegExpExecArray | null;
130
- while ((match = anchorPattern.exec(allText)) !== null) {
131
- if (match[1] === 'fig') figAnchors.add(match[2]);
132
- else if (match[1] === 'tbl') tblAnchors.add(match[2]);
133
- else if (match[1] === 'eq') eqAnchors.add(match[2]);
134
- }
135
-
136
- const refPattern = /@(fig|tbl|eq):([a-zA-Z0-9_-]+)/g;
137
- while ((match = refPattern.exec(allText)) !== null) {
138
- const type = match[1];
139
- const label = match[2];
140
- const anchors = type === 'fig' ? figAnchors : type === 'tbl' ? tblAnchors : eqAnchors;
141
-
142
- if (!anchors.has(label)) {
143
- issues.push({
144
- type: 'error',
145
- message: `Broken reference: @${type}:${label}`,
146
- fix: null
147
- });
148
- }
149
- }
150
-
151
- // Check 2: Orphaned figures
152
- for (const label of figAnchors) {
153
- if (!allText.includes(`@fig:${label}`)) {
154
- warnings.push({
155
- type: 'warning',
156
- message: `Unreferenced figure: {#fig:${label}}`,
157
- });
158
- }
159
- }
160
-
161
- // Check 3: Missing citations
162
- const bibPath = config.bibliography || 'references.bib';
163
- if (fs.existsSync(bibPath)) {
164
- const bibContent = fs.readFileSync(bibPath, 'utf-8');
165
- const bibKeys = new Set<string>();
166
- const bibPattern = /@\w+\s*\{\s*([^,]+)/g;
167
- while ((match = bibPattern.exec(bibContent)) !== null) {
168
- bibKeys.add(match[1].trim());
169
- }
170
-
171
- const citePattern = /@([a-zA-Z][a-zA-Z0-9_-]*)(?![:\w])/g;
172
- while ((match = citePattern.exec(allText)) !== null) {
173
- const key = match[1];
174
- if (!bibKeys.has(key) && !['fig', 'tbl', 'eq'].includes(key)) {
175
- issues.push({
176
- type: 'error',
177
- message: `Missing citation: @${key}`,
178
- });
179
- }
180
- }
181
- }
182
-
183
- // Check 4: Unresolved comments
184
- const comments = getComments(allText);
185
- const pending = comments.filter(c => !c.resolved);
186
- if (pending.length > 0) {
187
- warnings.push({
188
- type: 'warning',
189
- message: `${pending.length} unresolved comment${pending.length === 1 ? '' : 's'}`,
190
- });
191
- }
192
-
193
- // Check 5: Empty sections
194
- for (const section of sections) {
195
- if (fs.existsSync(section)) {
196
- const content = fs.readFileSync(section, 'utf-8').trim();
197
- if (content.length < 50) {
198
- warnings.push({
199
- type: 'warning',
200
- message: `Section appears empty: ${section}`,
201
- });
202
- }
203
- }
204
- }
205
-
206
- // Output results
207
- console.log(fmt.header('Lint Results'));
208
- console.log();
209
-
210
- if (issues.length === 0 && warnings.length === 0) {
211
- console.log(chalk.green('✓ No issues found'));
212
- return;
213
- }
214
-
215
- for (const issue of issues) {
216
- console.log(chalk.red(` ✗ ${issue.message}`));
217
- }
218
-
219
- for (const warning of warnings) {
220
- console.log(chalk.yellow(` ⚠ ${warning.message}`));
221
- }
222
-
223
- console.log();
224
- console.log(chalk.dim(`${issues.length} error${issues.length === 1 ? '' : 's'}, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`));
225
-
226
- if (issues.length > 0) {
227
- process.exit(1);
228
- }
229
- });
230
-
231
- // ==========================================================================
232
- // GRAMMAR command - Check grammar and style
233
- // ==========================================================================
234
-
235
- program
236
- .command('grammar')
237
- .description('Check grammar and style issues')
238
- .argument('[files...]', 'Markdown files to check')
239
- .option('--learn <word>', 'Add word to custom dictionary')
240
- .option('--forget <word>', 'Remove word from custom dictionary')
241
- .option('--list', 'List custom dictionary words')
242
- .option('--rules', 'List available grammar rules')
243
- .option('--no-scientific', 'Disable scientific writing rules')
244
- .option('-s, --severity <level>', 'Minimum severity: error, warning, info', 'info')
245
- .action(async (files: string[] | undefined, options: GrammarOptions) => {
246
- const {
247
- checkGrammar,
248
- getGrammarSummary,
249
- loadDictionary,
250
- addToDictionary,
251
- removeFromDictionary,
252
- listRules,
253
- } = await import('../grammar.js');
254
-
255
- // Handle dictionary management
256
- if (options.learn) {
257
- const added = addToDictionary(options.learn);
258
- if (added) {
259
- console.log(fmt.status('success', `Added "${options.learn}" to dictionary`));
260
- } else {
261
- console.log(chalk.dim(`"${options.learn}" already in dictionary`));
262
- }
263
- return;
264
- }
265
-
266
- if (options.forget) {
267
- const removed = removeFromDictionary(options.forget);
268
- if (removed) {
269
- console.log(fmt.status('success', `Removed "${options.forget}" from dictionary`));
270
- } else {
271
- console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
272
- }
273
- return;
274
- }
275
-
276
- if (options.list) {
277
- const words = loadDictionary();
278
- console.log(fmt.header('Custom Dictionary'));
279
- console.log();
280
- if (words.size === 0) {
281
- console.log(chalk.dim(' No custom words defined'));
282
- console.log(chalk.dim(' Use --learn <word> to add words'));
283
- } else {
284
- const sorted = [...words].sort();
285
- for (const word of sorted) {
286
- console.log(` ${word}`);
287
- }
288
- console.log();
289
- console.log(chalk.dim(`${words.size} word(s)`));
290
- }
291
- return;
292
- }
293
-
294
- if (options.rules) {
295
- const rules = listRules(options.scientific);
296
- console.log(fmt.header('Grammar Rules'));
297
- console.log();
298
- for (const rule of rules) {
299
- const icon = rule.severity === 'error' ? chalk.red('●') :
300
- rule.severity === 'warning' ? chalk.yellow('●') :
301
- chalk.blue('●');
302
- console.log(` ${icon} ${chalk.bold(rule.id)}`);
303
- console.log(chalk.dim(` ${rule.message}`));
304
- }
305
- return;
306
- }
307
-
308
- // Get files to check
309
- let mdFiles = files;
310
- if (!mdFiles || mdFiles.length === 0) {
311
- let config: Partial<BuildConfig> = {};
312
- try {
313
- config = loadBuildConfig('.') || {};
314
- } catch {
315
- // Not in a rev project
316
- }
317
- mdFiles = config.sections || [];
318
-
319
- if (mdFiles.length === 0) {
320
- mdFiles = fs.readdirSync('.').filter(f =>
321
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
322
- );
323
- }
324
- }
325
-
326
- if (mdFiles.length === 0) {
327
- console.error(chalk.red('No markdown files found'));
328
- process.exit(1);
329
- }
330
-
331
- console.log(fmt.header('Grammar Check'));
332
- console.log();
333
-
334
- const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
335
- const minSeverity = severityLevels[options.severity || 'info'] || 1;
336
-
337
- let allIssues: GrammarIssue[] = [];
338
-
339
- for (const file of mdFiles) {
340
- if (!fs.existsSync(file)) continue;
341
-
342
- const text = fs.readFileSync(file, 'utf-8');
343
- const issues = checkGrammar(text, { scientific: options.scientific });
344
-
345
- // Filter by severity
346
- const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
347
-
348
- if (filtered.length > 0) {
349
- console.log(chalk.cyan.bold(file));
350
-
351
- for (const issue of filtered) {
352
- const icon = issue.severity === 'error' ? chalk.red('●') :
353
- issue.severity === 'warning' ? chalk.yellow('●') :
354
- chalk.blue('●');
355
-
356
- console.log(` ${chalk.dim(`L${issue.line}:`)} ${icon} ${issue.message}`);
357
- console.log(chalk.dim(` "${issue.match}" in: ${issue.context.slice(0, 60)}...`));
358
- }
359
- console.log();
360
- allIssues.push(...filtered.map(i => ({ ...i, file })));
361
- }
362
- }
363
-
364
- const summary = getGrammarSummary(allIssues);
365
-
366
- if (summary.total === 0) {
367
- console.log(chalk.green('✓ No issues found'));
368
- } else {
369
- console.log(chalk.dim(`Found ${summary.total} issue(s): ${summary.errors} errors, ${summary.warnings} warnings, ${summary.info} info`));
370
- console.log();
371
- console.log(chalk.dim('Tip: Use --learn <word> to add words to dictionary'));
372
- }
373
- });
374
-
375
- // ==========================================================================
376
- // CHECK command - Pre-submission check
377
- // ==========================================================================
378
-
379
- program
380
- .command('check')
381
- .description('Run all checks before submission (lint + grammar + citations)')
382
- .option('--fix', 'Auto-fix issues where possible')
383
- .option('-s, --severity <level>', 'Minimum grammar severity', 'warning')
384
- .action(async (options: CheckOptions) => {
385
- const { validateCitations } = await import('../citations.js');
386
- const { checkGrammar, getGrammarSummary } = await import('../grammar.js');
387
-
388
- console.log(fmt.header('Pre-Submission Check'));
389
- console.log();
390
-
391
- let hasErrors = false;
392
- let totalIssues = 0;
393
-
394
- // 1. Run lint
395
- console.log(chalk.cyan.bold('1. Linting...'));
396
- let config: Partial<BuildConfig> = {};
397
- try {
398
- config = loadBuildConfig('.') || {};
399
- } catch {
400
- // Not in a rev project
401
- }
402
-
403
- let sections = config.sections || [];
404
- if (sections.length === 0) {
405
- sections = fs.readdirSync('.').filter(f =>
406
- f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
407
- );
408
- }
409
-
410
- const lintIssues: { file: string; message: string }[] = [];
411
- const lintWarnings: { file: string; message: string }[] = [];
412
-
413
- for (const file of sections) {
414
- if (!fs.existsSync(file)) continue;
415
- const content = fs.readFileSync(file, 'utf-8');
416
-
417
- // Check for broken cross-references
418
- const refs = content.match(/@(fig|tbl|eq|sec):\w+/g) || [];
419
- const anchors = content.match(/\{#(fig|tbl|eq|sec):[^}]+\}/g) || [];
420
- const anchorLabels = anchors.map(a => a.match(/#([^}]+)/)![1]);
421
-
422
- for (const ref of refs) {
423
- const label = ref.slice(1);
424
- if (!anchorLabels.includes(label)) {
425
- lintIssues.push({ file, message: `Broken reference: ${ref}` });
426
- }
427
- }
428
-
429
- // Check for unresolved comments
430
- const unresolvedComments = (content.match(/\{>>[\s\S]*?<<\}/g) || [])
431
- .filter(c => !c.includes('[RESOLVED]'));
432
- if (unresolvedComments.length > 0) {
433
- lintWarnings.push({ file, message: `${unresolvedComments.length} unresolved comment(s)` });
434
- }
435
- }
436
-
437
- if (lintIssues.length > 0) {
438
- for (const issue of lintIssues) {
439
- console.log(chalk.red(` ✗ ${issue.file}: ${issue.message}`));
440
- }
441
- hasErrors = true;
442
- totalIssues += lintIssues.length;
443
- }
444
- for (const warning of lintWarnings) {
445
- console.log(chalk.yellow(` ⚠ ${warning.file}: ${warning.message}`));
446
- totalIssues++;
447
- }
448
- if (lintIssues.length === 0 && lintWarnings.length === 0) {
449
- console.log(chalk.green(' ✓ No lint issues'));
450
- }
451
- console.log();
452
-
453
- // 2. Run grammar check
454
- console.log(chalk.cyan.bold('2. Grammar check...'));
455
-
456
- const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
457
- const minSeverity = severityLevels[options.severity || 'warning'] || 2;
458
- let grammarIssues: GrammarIssue[] = [];
459
-
460
- for (const file of sections) {
461
- if (!fs.existsSync(file)) continue;
462
- const text = fs.readFileSync(file, 'utf-8');
463
- const issues = checkGrammar(text, { scientific: true });
464
- const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
465
- grammarIssues.push(...filtered.map(i => ({ ...i, file })));
466
- }
467
-
468
- const grammarSummary = getGrammarSummary(grammarIssues);
469
- if (grammarSummary.errors > 0) {
470
- hasErrors = true;
471
- }
472
- totalIssues += grammarSummary.total;
473
-
474
- if (grammarSummary.total > 0) {
475
- console.log(chalk.yellow(` ⚠ ${grammarSummary.total} grammar issue(s): ${grammarSummary.errors} errors, ${grammarSummary.warnings} warnings`));
476
- } else {
477
- console.log(chalk.green(' ✓ No grammar issues'));
478
- }
479
- console.log();
480
-
481
- // 3. Run citation check
482
- console.log(chalk.cyan.bold('3. Citation check...'));
483
- const bibFile = config.bibliography || 'references.bib';
484
- if (fs.existsSync(bibFile)) {
485
- const existingSections = sections.filter(f => fs.existsSync(f));
486
-
487
- const result = validateCitations(existingSections, bibFile);
488
-
489
- if (result.missing.length > 0) {
490
- console.log(chalk.red(` ✗ ${result.missing.length} missing citation(s): ${result.missing.slice(0, 3).join(', ')}${result.missing.length > 3 ? '...' : ''}`));
491
- hasErrors = true;
492
- totalIssues += result.missing.length;
493
- }
494
- if (result.unused.length > 0) {
495
- console.log(chalk.yellow(` ⚠ ${result.unused.length} unused citation(s)`));
496
- totalIssues += result.unused.length;
497
- }
498
- if (result.missing.length === 0 && result.unused.length === 0) {
499
- console.log(chalk.green(' ✓ All citations valid'));
500
- }
501
- } else {
502
- console.log(chalk.dim(' - No bibliography file found'));
503
- }
504
- console.log();
505
-
506
- // Summary
507
- console.log(chalk.bold('Summary'));
508
- if (hasErrors) {
509
- console.log(chalk.red(` ${totalIssues} issue(s) found. Please fix before submission.`));
510
- process.exit(1);
511
- } else if (totalIssues > 0) {
512
- console.log(chalk.yellow(` ${totalIssues} warning(s). Review before submission.`));
513
- } else {
514
- console.log(chalk.green(' ✓ All checks passed! Ready for submission.'));
515
- }
516
- });
517
- }
1
+ /**
2
+ * Quality commands: lint, grammar, check
3
+ *
4
+ * Commands for checking project quality before submission.
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ loadBuildConfig,
14
+ getComments,
15
+ } from './context.js';
16
+
17
+ // Use the actual BuildConfig from build.ts which allows string|Author[]
18
+ type BuildConfig = ReturnType<typeof loadBuildConfig>;
19
+
20
+ // Options interfaces
21
+ interface LintOptions {
22
+ fix?: boolean;
23
+ }
24
+
25
+ interface GrammarOptions {
26
+ learn?: string;
27
+ forget?: string;
28
+ list?: boolean;
29
+ rules?: boolean;
30
+ scientific?: boolean;
31
+ severity?: string;
32
+ }
33
+
34
+ interface CheckOptions {
35
+ fix?: boolean;
36
+ severity?: string;
37
+ }
38
+
39
+ // Grammar issue interface (from grammar.ts)
40
+ interface GrammarIssue {
41
+ rule: string;
42
+ severity: 'error' | 'warning' | 'info';
43
+ message: string;
44
+ line: number;
45
+ column: number;
46
+ match: string;
47
+ context: string;
48
+ file?: string;
49
+ }
50
+
51
+ // Grammar summary interface (from grammar.ts)
52
+ interface GrammarSummary {
53
+ total: number;
54
+ errors: number;
55
+ warnings: number;
56
+ info: number;
57
+ byRule?: Record<string, number>;
58
+ }
59
+
60
+ // Lint issue interface
61
+ interface LintIssue {
62
+ type: 'error' | 'warning';
63
+ message: string;
64
+ fix?: string | null;
65
+ file?: string;
66
+ }
67
+
68
+ // Build result interface - matches build.ts export
69
+ interface BuildResult {
70
+ format: string;
71
+ success: boolean;
72
+ outputPath?: string;
73
+ error?: string;
74
+ }
75
+
76
+ // Full build result interface - matches build.ts FullBuildResult
77
+ interface FullBuildResult {
78
+ results: BuildResult[];
79
+ paperPath: string;
80
+ warnings: string[];
81
+ forwardRefsResolved: number;
82
+ refsAutoInjected?: boolean;
83
+ }
84
+
85
+ /**
86
+ * Register quality commands with the program
87
+ */
88
+ export function register(program: Command): void {
89
+ // ==========================================================================
90
+ // LINT command - Check for common issues
91
+ // ==========================================================================
92
+
93
+ program
94
+ .command('lint')
95
+ .description('Check for common issues in the project')
96
+ .option('--fix', 'Auto-fix issues where possible')
97
+ .action(async (_options: LintOptions) => {
98
+ let config: Partial<BuildConfig> = {};
99
+ try {
100
+ config = loadBuildConfig('.') || {};
101
+ } catch {
102
+ // Not in a rev project, that's ok
103
+ }
104
+ let sections = config.sections || [];
105
+
106
+ if (sections.length === 0) {
107
+ sections = fs.readdirSync('.').filter(f =>
108
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
109
+ );
110
+ }
111
+
112
+ const issues: LintIssue[] = [];
113
+ const warnings: LintIssue[] = [];
114
+
115
+ // Collect all content
116
+ let allText = '';
117
+ for (const section of sections) {
118
+ if (fs.existsSync(section)) {
119
+ allText += fs.readFileSync(section, 'utf-8') + '\n';
120
+ }
121
+ }
122
+
123
+ // Check 1: Broken cross-references
124
+ const figAnchors = new Set<string>();
125
+ const tblAnchors = new Set<string>();
126
+ const eqAnchors = new Set<string>();
127
+
128
+ const anchorPattern = /\{#(fig|tbl|eq):([^}]+)\}/g;
129
+ let match: RegExpExecArray | null;
130
+ while ((match = anchorPattern.exec(allText)) !== null) {
131
+ if (match[1] === 'fig') figAnchors.add(match[2]);
132
+ else if (match[1] === 'tbl') tblAnchors.add(match[2]);
133
+ else if (match[1] === 'eq') eqAnchors.add(match[2]);
134
+ }
135
+
136
+ const refPattern = /@(fig|tbl|eq):([a-zA-Z0-9_-]+)/g;
137
+ while ((match = refPattern.exec(allText)) !== null) {
138
+ const type = match[1];
139
+ const label = match[2];
140
+ const anchors = type === 'fig' ? figAnchors : type === 'tbl' ? tblAnchors : eqAnchors;
141
+
142
+ if (!anchors.has(label)) {
143
+ issues.push({
144
+ type: 'error',
145
+ message: `Broken reference: @${type}:${label}`,
146
+ fix: null
147
+ });
148
+ }
149
+ }
150
+
151
+ // Check 2: Orphaned figures
152
+ for (const label of figAnchors) {
153
+ if (!allText.includes(`@fig:${label}`)) {
154
+ warnings.push({
155
+ type: 'warning',
156
+ message: `Unreferenced figure: {#fig:${label}}`,
157
+ });
158
+ }
159
+ }
160
+
161
+ // Check 3: Missing citations
162
+ const bibPath = config.bibliography || 'references.bib';
163
+ if (fs.existsSync(bibPath)) {
164
+ const bibContent = fs.readFileSync(bibPath, 'utf-8');
165
+ const bibKeys = new Set<string>();
166
+ const bibPattern = /@\w+\s*\{\s*([^,]+)/g;
167
+ while ((match = bibPattern.exec(bibContent)) !== null) {
168
+ bibKeys.add(match[1].trim());
169
+ }
170
+
171
+ const citePattern = /@([a-zA-Z][a-zA-Z0-9_-]*)(?![:\w])/g;
172
+ while ((match = citePattern.exec(allText)) !== null) {
173
+ const key = match[1];
174
+ if (!bibKeys.has(key) && !['fig', 'tbl', 'eq'].includes(key)) {
175
+ issues.push({
176
+ type: 'error',
177
+ message: `Missing citation: @${key}`,
178
+ });
179
+ }
180
+ }
181
+ }
182
+
183
+ // Check 4: Unresolved comments
184
+ const comments = getComments(allText);
185
+ const pending = comments.filter(c => !c.resolved);
186
+ if (pending.length > 0) {
187
+ warnings.push({
188
+ type: 'warning',
189
+ message: `${pending.length} unresolved comment${pending.length === 1 ? '' : 's'}`,
190
+ });
191
+ }
192
+
193
+ // Check 5: Empty sections
194
+ for (const section of sections) {
195
+ if (fs.existsSync(section)) {
196
+ const content = fs.readFileSync(section, 'utf-8').trim();
197
+ if (content.length < 50) {
198
+ warnings.push({
199
+ type: 'warning',
200
+ message: `Section appears empty: ${section}`,
201
+ });
202
+ }
203
+ }
204
+ }
205
+
206
+ // Output results
207
+ console.log(fmt.header('Lint Results'));
208
+ console.log();
209
+
210
+ if (issues.length === 0 && warnings.length === 0) {
211
+ console.log(chalk.green('✓ No issues found'));
212
+ return;
213
+ }
214
+
215
+ for (const issue of issues) {
216
+ console.log(chalk.red(` ✗ ${issue.message}`));
217
+ }
218
+
219
+ for (const warning of warnings) {
220
+ console.log(chalk.yellow(` ⚠ ${warning.message}`));
221
+ }
222
+
223
+ console.log();
224
+ console.log(chalk.dim(`${issues.length} error${issues.length === 1 ? '' : 's'}, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`));
225
+
226
+ if (issues.length > 0) {
227
+ process.exit(1);
228
+ }
229
+ });
230
+
231
+ // ==========================================================================
232
+ // GRAMMAR command - Check grammar and style
233
+ // ==========================================================================
234
+
235
+ program
236
+ .command('grammar')
237
+ .description('Check grammar and style issues')
238
+ .argument('[files...]', 'Markdown files to check')
239
+ .option('--learn <word>', 'Add word to custom dictionary')
240
+ .option('--forget <word>', 'Remove word from custom dictionary')
241
+ .option('--list', 'List custom dictionary words')
242
+ .option('--rules', 'List available grammar rules')
243
+ .option('--no-scientific', 'Disable scientific writing rules')
244
+ .option('-s, --severity <level>', 'Minimum severity: error, warning, info', 'info')
245
+ .action(async (files: string[] | undefined, options: GrammarOptions) => {
246
+ const {
247
+ checkGrammar,
248
+ getGrammarSummary,
249
+ loadDictionary,
250
+ addToDictionary,
251
+ removeFromDictionary,
252
+ listRules,
253
+ } = await import('../grammar.js');
254
+
255
+ // Handle dictionary management
256
+ if (options.learn) {
257
+ const added = addToDictionary(options.learn);
258
+ if (added) {
259
+ console.log(fmt.status('success', `Added "${options.learn}" to dictionary`));
260
+ } else {
261
+ console.log(chalk.dim(`"${options.learn}" already in dictionary`));
262
+ }
263
+ return;
264
+ }
265
+
266
+ if (options.forget) {
267
+ const removed = removeFromDictionary(options.forget);
268
+ if (removed) {
269
+ console.log(fmt.status('success', `Removed "${options.forget}" from dictionary`));
270
+ } else {
271
+ console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
272
+ }
273
+ return;
274
+ }
275
+
276
+ if (options.list) {
277
+ const words = loadDictionary();
278
+ console.log(fmt.header('Custom Dictionary'));
279
+ console.log();
280
+ if (words.size === 0) {
281
+ console.log(chalk.dim(' No custom words defined'));
282
+ console.log(chalk.dim(' Use --learn <word> to add words'));
283
+ } else {
284
+ const sorted = [...words].sort();
285
+ for (const word of sorted) {
286
+ console.log(` ${word}`);
287
+ }
288
+ console.log();
289
+ console.log(chalk.dim(`${words.size} word(s)`));
290
+ }
291
+ return;
292
+ }
293
+
294
+ if (options.rules) {
295
+ const rules = listRules(options.scientific);
296
+ console.log(fmt.header('Grammar Rules'));
297
+ console.log();
298
+ for (const rule of rules) {
299
+ const icon = rule.severity === 'error' ? chalk.red('●') :
300
+ rule.severity === 'warning' ? chalk.yellow('●') :
301
+ chalk.blue('●');
302
+ console.log(` ${icon} ${chalk.bold(rule.id)}`);
303
+ console.log(chalk.dim(` ${rule.message}`));
304
+ }
305
+ return;
306
+ }
307
+
308
+ // Get files to check
309
+ let mdFiles = files;
310
+ if (!mdFiles || mdFiles.length === 0) {
311
+ let config: Partial<BuildConfig> = {};
312
+ try {
313
+ config = loadBuildConfig('.') || {};
314
+ } catch {
315
+ // Not in a rev project
316
+ }
317
+ mdFiles = config.sections || [];
318
+
319
+ if (mdFiles.length === 0) {
320
+ mdFiles = fs.readdirSync('.').filter(f =>
321
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
322
+ );
323
+ }
324
+ }
325
+
326
+ if (mdFiles.length === 0) {
327
+ console.error(chalk.red('No markdown files found'));
328
+ process.exit(1);
329
+ }
330
+
331
+ console.log(fmt.header('Grammar Check'));
332
+ console.log();
333
+
334
+ const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
335
+ const minSeverity = severityLevels[options.severity || 'info'] || 1;
336
+
337
+ let allIssues: GrammarIssue[] = [];
338
+
339
+ for (const file of mdFiles) {
340
+ if (!fs.existsSync(file)) continue;
341
+
342
+ const text = fs.readFileSync(file, 'utf-8');
343
+ const issues = checkGrammar(text, { scientific: options.scientific });
344
+
345
+ // Filter by severity
346
+ const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
347
+
348
+ if (filtered.length > 0) {
349
+ console.log(chalk.cyan.bold(file));
350
+
351
+ for (const issue of filtered) {
352
+ const icon = issue.severity === 'error' ? chalk.red('●') :
353
+ issue.severity === 'warning' ? chalk.yellow('●') :
354
+ chalk.blue('●');
355
+
356
+ console.log(` ${chalk.dim(`L${issue.line}:`)} ${icon} ${issue.message}`);
357
+ console.log(chalk.dim(` "${issue.match}" in: ${issue.context.slice(0, 60)}...`));
358
+ }
359
+ console.log();
360
+ allIssues.push(...filtered.map(i => ({ ...i, file })));
361
+ }
362
+ }
363
+
364
+ const summary = getGrammarSummary(allIssues);
365
+
366
+ if (summary.total === 0) {
367
+ console.log(chalk.green('✓ No issues found'));
368
+ } else {
369
+ console.log(chalk.dim(`Found ${summary.total} issue(s): ${summary.errors} errors, ${summary.warnings} warnings, ${summary.info} info`));
370
+ console.log();
371
+ console.log(chalk.dim('Tip: Use --learn <word> to add words to dictionary'));
372
+ }
373
+ });
374
+
375
+ // ==========================================================================
376
+ // CHECK command - Pre-submission check
377
+ // ==========================================================================
378
+
379
+ program
380
+ .command('check')
381
+ .description('Run all checks before submission (lint + grammar + citations)')
382
+ .option('--fix', 'Auto-fix issues where possible')
383
+ .option('-s, --severity <level>', 'Minimum grammar severity', 'warning')
384
+ .action(async (options: CheckOptions) => {
385
+ const { validateCitations } = await import('../citations.js');
386
+ const { checkGrammar, getGrammarSummary } = await import('../grammar.js');
387
+
388
+ console.log(fmt.header('Pre-Submission Check'));
389
+ console.log();
390
+
391
+ let hasErrors = false;
392
+ let totalIssues = 0;
393
+
394
+ // 1. Run lint
395
+ console.log(chalk.cyan.bold('1. Linting...'));
396
+ let config: Partial<BuildConfig> = {};
397
+ try {
398
+ config = loadBuildConfig('.') || {};
399
+ } catch {
400
+ // Not in a rev project
401
+ }
402
+
403
+ let sections = config.sections || [];
404
+ if (sections.length === 0) {
405
+ sections = fs.readdirSync('.').filter(f =>
406
+ f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)
407
+ );
408
+ }
409
+
410
+ const lintIssues: { file: string; message: string }[] = [];
411
+ const lintWarnings: { file: string; message: string }[] = [];
412
+
413
+ for (const file of sections) {
414
+ if (!fs.existsSync(file)) continue;
415
+ const content = fs.readFileSync(file, 'utf-8');
416
+
417
+ // Check for broken cross-references
418
+ const refs = content.match(/@(fig|tbl|eq|sec):\w+/g) || [];
419
+ const anchors = content.match(/\{#(fig|tbl|eq|sec):[^}]+\}/g) || [];
420
+ const anchorLabels = anchors.map(a => a.match(/#([^}]+)/)![1]);
421
+
422
+ for (const ref of refs) {
423
+ const label = ref.slice(1);
424
+ if (!anchorLabels.includes(label)) {
425
+ lintIssues.push({ file, message: `Broken reference: ${ref}` });
426
+ }
427
+ }
428
+
429
+ // Check for unresolved comments
430
+ const unresolvedComments = (content.match(/\{>>[\s\S]*?<<\}/g) || [])
431
+ .filter(c => !c.includes('[RESOLVED]'));
432
+ if (unresolvedComments.length > 0) {
433
+ lintWarnings.push({ file, message: `${unresolvedComments.length} unresolved comment(s)` });
434
+ }
435
+ }
436
+
437
+ if (lintIssues.length > 0) {
438
+ for (const issue of lintIssues) {
439
+ console.log(chalk.red(` ✗ ${issue.file}: ${issue.message}`));
440
+ }
441
+ hasErrors = true;
442
+ totalIssues += lintIssues.length;
443
+ }
444
+ for (const warning of lintWarnings) {
445
+ console.log(chalk.yellow(` ⚠ ${warning.file}: ${warning.message}`));
446
+ totalIssues++;
447
+ }
448
+ if (lintIssues.length === 0 && lintWarnings.length === 0) {
449
+ console.log(chalk.green(' ✓ No lint issues'));
450
+ }
451
+ console.log();
452
+
453
+ // 2. Run grammar check
454
+ console.log(chalk.cyan.bold('2. Grammar check...'));
455
+
456
+ const severityLevels: Record<string, number> = { error: 3, warning: 2, info: 1 };
457
+ const minSeverity = severityLevels[options.severity || 'warning'] || 2;
458
+ let grammarIssues: GrammarIssue[] = [];
459
+
460
+ for (const file of sections) {
461
+ if (!fs.existsSync(file)) continue;
462
+ const text = fs.readFileSync(file, 'utf-8');
463
+ const issues = checkGrammar(text, { scientific: true });
464
+ const filtered = issues.filter((i: GrammarIssue) => severityLevels[i.severity] >= minSeverity);
465
+ grammarIssues.push(...filtered.map(i => ({ ...i, file })));
466
+ }
467
+
468
+ const grammarSummary = getGrammarSummary(grammarIssues);
469
+ if (grammarSummary.errors > 0) {
470
+ hasErrors = true;
471
+ }
472
+ totalIssues += grammarSummary.total;
473
+
474
+ if (grammarSummary.total > 0) {
475
+ console.log(chalk.yellow(` ⚠ ${grammarSummary.total} grammar issue(s): ${grammarSummary.errors} errors, ${grammarSummary.warnings} warnings`));
476
+ } else {
477
+ console.log(chalk.green(' ✓ No grammar issues'));
478
+ }
479
+ console.log();
480
+
481
+ // 3. Run citation check
482
+ console.log(chalk.cyan.bold('3. Citation check...'));
483
+ const bibFile = config.bibliography || 'references.bib';
484
+ if (fs.existsSync(bibFile)) {
485
+ const existingSections = sections.filter(f => fs.existsSync(f));
486
+
487
+ const result = validateCitations(existingSections, bibFile);
488
+
489
+ if (result.missing.length > 0) {
490
+ console.log(chalk.red(` ✗ ${result.missing.length} missing citation(s): ${result.missing.slice(0, 3).join(', ')}${result.missing.length > 3 ? '...' : ''}`));
491
+ hasErrors = true;
492
+ totalIssues += result.missing.length;
493
+ }
494
+ if (result.unused.length > 0) {
495
+ console.log(chalk.yellow(` ⚠ ${result.unused.length} unused citation(s)`));
496
+ totalIssues += result.unused.length;
497
+ }
498
+ if (result.missing.length === 0 && result.unused.length === 0) {
499
+ console.log(chalk.green(' ✓ All citations valid'));
500
+ }
501
+ } else {
502
+ console.log(chalk.dim(' - No bibliography file found'));
503
+ }
504
+ console.log();
505
+
506
+ // Summary
507
+ console.log(chalk.bold('Summary'));
508
+ if (hasErrors) {
509
+ console.log(chalk.red(` ${totalIssues} issue(s) found. Please fix before submission.`));
510
+ process.exit(1);
511
+ } else if (totalIssues > 0) {
512
+ console.log(chalk.yellow(` ${totalIssues} warning(s). Review before submission.`));
513
+ } else {
514
+ console.log(chalk.green(' ✓ All checks passed! Ready for submission.'));
515
+ }
516
+ });
517
+ }