docrev 0.10.1 → 0.11.0

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