docrev 0.9.18 → 0.10.1

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 (134) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -149
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -406
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/build.d.ts +8 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +62 -6
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/context.d.ts +1 -1
  15. package/dist/lib/commands/context.d.ts.map +1 -1
  16. package/dist/lib/commands/context.js +1 -1
  17. package/dist/lib/commands/context.js.map +1 -1
  18. package/dist/lib/commands/sections.js +7 -7
  19. package/dist/lib/commands/sections.js.map +1 -1
  20. package/dist/lib/commands/sync.d.ts.map +1 -1
  21. package/dist/lib/commands/sync.js +15 -14
  22. package/dist/lib/commands/sync.js.map +1 -1
  23. package/dist/lib/commands/utilities.js +164 -164
  24. package/dist/lib/commands/verify-anchors.js +6 -6
  25. package/dist/lib/commands/verify-anchors.js.map +1 -1
  26. package/dist/lib/commands/word-tools.js +8 -8
  27. package/dist/lib/grammar.js +3 -3
  28. package/dist/lib/macro-filter.lua +201 -0
  29. package/dist/lib/macros.d.ts +102 -0
  30. package/dist/lib/macros.d.ts.map +1 -0
  31. package/dist/lib/macros.js +218 -0
  32. package/dist/lib/macros.js.map +1 -0
  33. package/dist/lib/pdf-comments.js +44 -44
  34. package/dist/lib/plugins.js +57 -57
  35. package/dist/lib/pptx-color-filter.lua +37 -0
  36. package/dist/lib/pptx-themes.js +115 -115
  37. package/dist/lib/schema.d.ts.map +1 -1
  38. package/dist/lib/schema.js +34 -0
  39. package/dist/lib/schema.js.map +1 -1
  40. package/dist/lib/sections.d.ts +35 -0
  41. package/dist/lib/sections.d.ts.map +1 -1
  42. package/dist/lib/sections.js +81 -0
  43. package/dist/lib/sections.js.map +1 -1
  44. package/dist/lib/spelling.js +2 -2
  45. package/dist/lib/templates.js +387 -387
  46. package/dist/lib/themes.js +51 -51
  47. package/eslint.config.js +27 -27
  48. package/lib/anchor-match.ts +276 -276
  49. package/lib/annotations.ts +644 -644
  50. package/lib/build.ts +1766 -1694
  51. package/lib/citations.ts +160 -160
  52. package/lib/commands/build.ts +855 -855
  53. package/lib/commands/citations.ts +515 -515
  54. package/lib/commands/comments.ts +1050 -1050
  55. package/lib/commands/context.ts +176 -174
  56. package/lib/commands/core.ts +309 -309
  57. package/lib/commands/doi.ts +435 -435
  58. package/lib/commands/file-ops.ts +372 -372
  59. package/lib/commands/history.ts +320 -320
  60. package/lib/commands/index.ts +87 -87
  61. package/lib/commands/init.ts +259 -259
  62. package/lib/commands/merge-resolve.ts +378 -378
  63. package/lib/commands/preview.ts +178 -178
  64. package/lib/commands/project-info.ts +244 -244
  65. package/lib/commands/quality.ts +517 -517
  66. package/lib/commands/response.ts +454 -454
  67. package/lib/commands/section-boundaries.ts +82 -82
  68. package/lib/commands/sections.ts +451 -451
  69. package/lib/commands/sync.ts +709 -706
  70. package/lib/commands/text-ops.ts +449 -449
  71. package/lib/commands/utilities.ts +448 -448
  72. package/lib/commands/verify-anchors.ts +272 -272
  73. package/lib/commands/word-tools.ts +340 -340
  74. package/lib/comment-realign.ts +517 -517
  75. package/lib/config.ts +84 -84
  76. package/lib/crossref.ts +781 -781
  77. package/lib/csl.ts +191 -191
  78. package/lib/dependencies.ts +98 -98
  79. package/lib/diff-engine.ts +465 -465
  80. package/lib/doi-cache.ts +115 -115
  81. package/lib/doi.ts +897 -897
  82. package/lib/equations.ts +506 -506
  83. package/lib/errors.ts +346 -346
  84. package/lib/format.ts +541 -541
  85. package/lib/git.ts +326 -326
  86. package/lib/grammar.ts +303 -303
  87. package/lib/image-registry.ts +180 -180
  88. package/lib/import.ts +911 -911
  89. package/lib/journals.ts +543 -543
  90. package/lib/macro-filter.lua +201 -0
  91. package/lib/macros.ts +273 -0
  92. package/lib/merge.ts +633 -633
  93. package/lib/orcid.ts +144 -144
  94. package/lib/pdf-comments.ts +263 -263
  95. package/lib/pdf-import.ts +524 -524
  96. package/lib/plugins.ts +362 -362
  97. package/lib/postprocess.ts +188 -188
  98. package/lib/pptx-color-filter.lua +37 -37
  99. package/lib/pptx-template.ts +469 -469
  100. package/lib/pptx-themes.ts +483 -483
  101. package/lib/protect-restore.ts +520 -520
  102. package/lib/rate-limiter.ts +94 -94
  103. package/lib/response.ts +197 -197
  104. package/lib/restore-references.ts +240 -240
  105. package/lib/review.ts +327 -327
  106. package/lib/schema.ts +488 -454
  107. package/lib/scientific-words.ts +73 -73
  108. package/lib/sections.ts +425 -335
  109. package/lib/slides.ts +756 -756
  110. package/lib/spelling.ts +334 -334
  111. package/lib/templates.ts +526 -526
  112. package/lib/themes.ts +742 -742
  113. package/lib/trackchanges.ts +247 -247
  114. package/lib/tui.ts +450 -450
  115. package/lib/types.ts +550 -550
  116. package/lib/undo.ts +250 -250
  117. package/lib/utils.ts +69 -69
  118. package/lib/variables.ts +179 -179
  119. package/lib/word-extraction.ts +806 -806
  120. package/lib/word.ts +643 -643
  121. package/lib/wordcomments.ts +840 -840
  122. package/package.json +137 -137
  123. package/scripts/postbuild.js +47 -28
  124. package/skill/REFERENCE.md +539 -539
  125. package/skill/SKILL.md +295 -295
  126. package/tsconfig.json +26 -26
  127. package/types/index.d.ts +525 -525
  128. package/issues.md +0 -180
  129. package/site/assets/extra.css +0 -208
  130. package/site/commands.html +0 -926
  131. package/site/configuration.html +0 -469
  132. package/site/index.html +0 -288
  133. package/site/troubleshooting.html +0 -461
  134. package/site/workflow.html +0 -518
@@ -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
+ }