docrev 0.10.1 → 0.10.2

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 (119) 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 +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +47 -17
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/sync.d.ts.map +1 -1
  16. package/dist/lib/commands/sync.js +78 -100
  17. package/dist/lib/commands/sync.js.map +1 -1
  18. package/dist/lib/commands/utilities.js +164 -164
  19. package/dist/lib/commands/word-tools.js +8 -8
  20. package/dist/lib/grammar.js +3 -3
  21. package/dist/lib/macro-filter.lua +201 -201
  22. package/dist/lib/pdf-comments.js +44 -44
  23. package/dist/lib/plugins.js +57 -57
  24. package/dist/lib/pptx-color-filter.lua +37 -37
  25. package/dist/lib/pptx-themes.js +115 -115
  26. package/dist/lib/sections.d.ts.map +1 -1
  27. package/dist/lib/sections.js +5 -2
  28. package/dist/lib/sections.js.map +1 -1
  29. package/dist/lib/spelling.js +2 -2
  30. package/dist/lib/templates.js +387 -387
  31. package/dist/lib/themes.js +51 -51
  32. package/eslint.config.js +27 -27
  33. package/issues.md +180 -0
  34. package/lib/anchor-match.ts +308 -276
  35. package/lib/annotations.ts +644 -644
  36. package/lib/build.ts +1766 -1766
  37. package/lib/citations.ts +160 -160
  38. package/lib/commands/build.ts +855 -855
  39. package/lib/commands/citations.ts +515 -515
  40. package/lib/commands/comments.ts +1050 -1050
  41. package/lib/commands/context.ts +176 -176
  42. package/lib/commands/core.ts +309 -309
  43. package/lib/commands/doi.ts +435 -435
  44. package/lib/commands/file-ops.ts +372 -372
  45. package/lib/commands/history.ts +320 -320
  46. package/lib/commands/index.ts +87 -87
  47. package/lib/commands/init.ts +259 -259
  48. package/lib/commands/merge-resolve.ts +378 -378
  49. package/lib/commands/preview.ts +178 -178
  50. package/lib/commands/project-info.ts +244 -244
  51. package/lib/commands/quality.ts +517 -517
  52. package/lib/commands/response.ts +454 -454
  53. package/lib/commands/section-boundaries.ts +82 -82
  54. package/lib/commands/sections.ts +451 -451
  55. package/lib/commands/sync.ts +676 -709
  56. package/lib/commands/text-ops.ts +449 -449
  57. package/lib/commands/utilities.ts +448 -448
  58. package/lib/commands/verify-anchors.ts +272 -272
  59. package/lib/commands/word-tools.ts +340 -340
  60. package/lib/comment-realign.ts +517 -517
  61. package/lib/config.ts +84 -84
  62. package/lib/crossref.ts +781 -781
  63. package/lib/csl.ts +191 -191
  64. package/lib/dependencies.ts +98 -98
  65. package/lib/diff-engine.ts +465 -465
  66. package/lib/doi-cache.ts +115 -115
  67. package/lib/doi.ts +897 -897
  68. package/lib/equations.ts +506 -506
  69. package/lib/errors.ts +346 -346
  70. package/lib/format.ts +541 -541
  71. package/lib/git.ts +326 -326
  72. package/lib/grammar.ts +303 -303
  73. package/lib/image-registry.ts +180 -180
  74. package/lib/import.ts +911 -911
  75. package/lib/journals.ts +543 -543
  76. package/lib/macro-filter.lua +201 -201
  77. package/lib/macros.ts +273 -273
  78. package/lib/merge.ts +633 -633
  79. package/lib/orcid.ts +144 -144
  80. package/lib/pdf-comments.ts +263 -263
  81. package/lib/pdf-import.ts +524 -524
  82. package/lib/plugins.ts +362 -362
  83. package/lib/postprocess.ts +188 -188
  84. package/lib/pptx-color-filter.lua +37 -37
  85. package/lib/pptx-template.ts +469 -469
  86. package/lib/pptx-themes.ts +483 -483
  87. package/lib/protect-restore.ts +520 -520
  88. package/lib/rate-limiter.ts +94 -94
  89. package/lib/response.ts +197 -197
  90. package/lib/restore-references.ts +240 -240
  91. package/lib/review.ts +327 -327
  92. package/lib/schema.ts +488 -488
  93. package/lib/scientific-words.ts +73 -73
  94. package/lib/sections.ts +428 -425
  95. package/lib/slides.ts +756 -756
  96. package/lib/spelling.ts +334 -334
  97. package/lib/templates.ts +526 -526
  98. package/lib/themes.ts +742 -742
  99. package/lib/trackchanges.ts +247 -247
  100. package/lib/tui.ts +450 -450
  101. package/lib/types.ts +550 -550
  102. package/lib/undo.ts +250 -250
  103. package/lib/utils.ts +69 -69
  104. package/lib/variables.ts +179 -179
  105. package/lib/word-extraction.ts +806 -806
  106. package/lib/word.ts +643 -643
  107. package/lib/wordcomments.ts +840 -840
  108. package/package.json +137 -137
  109. package/scripts/postbuild.js +47 -47
  110. package/site/assets/extra.css +208 -0
  111. package/site/commands.html +926 -0
  112. package/site/configuration.html +469 -0
  113. package/site/index.html +288 -0
  114. package/site/troubleshooting.html +461 -0
  115. package/site/workflow.html +518 -0
  116. package/skill/REFERENCE.md +539 -539
  117. package/skill/SKILL.md +295 -295
  118. package/tsconfig.json +26 -26
  119. package/types/index.d.ts +525 -525
package/lib/sections.ts CHANGED
@@ -1,425 +1,428 @@
1
- /**
2
- * Section handling - map between section .md files and combined documents
3
- */
4
-
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
- import YAML from 'yaml';
8
- import type { SectionConfig, SectionsConfig, ExtractedSection } from './types.js';
9
-
10
- /**
11
- * Default section order (common academic paper structure)
12
- */
13
- const DEFAULT_ORDER = [
14
- 'abstract',
15
- 'introduction',
16
- 'background',
17
- 'literature',
18
- 'theory',
19
- 'methods',
20
- 'materials',
21
- 'data',
22
- 'results',
23
- 'analysis',
24
- 'discussion',
25
- 'conclusion',
26
- 'references',
27
- 'appendix',
28
- 'supplementary',
29
- ];
30
-
31
- /**
32
- * Extract header from a markdown file
33
- */
34
- export function extractHeader(filePath: string): string | null {
35
- if (!fs.existsSync(filePath)) return null;
36
-
37
- const content = fs.readFileSync(filePath, 'utf-8');
38
- const lines = content.split('\n');
39
-
40
- for (const line of lines) {
41
- const match = line.match(/^#\s+(.+)$/);
42
- if (match && match[1]) {
43
- return match[1].trim();
44
- }
45
- }
46
-
47
- return null;
48
- }
49
-
50
- /**
51
- * Extract the first markdown heading of ANY level (`#`–`######`) from a file.
52
- *
53
- * Unlike {@link extractHeader} (which is H1-only by contract), this is used to
54
- * derive a section's header from files that lead with a subsection — e.g.
55
- * `02_objectives.md` starting with `## 1.2 Objectives`. Using the real first
56
- * heading lets the derived header match the corresponding docx heading.
57
- */
58
- export function extractFirstHeading(filePath: string): string | null {
59
- if (!fs.existsSync(filePath)) return null;
60
-
61
- const content = fs.readFileSync(filePath, 'utf-8');
62
- for (const line of content.split('\n')) {
63
- const match = line.match(/^#{1,6}\s+(.+)$/);
64
- if (match && match[1]) {
65
- return match[1].trim();
66
- }
67
- }
68
-
69
- return null;
70
- }
71
-
72
- /**
73
- * Generate sections.yaml from existing .md files
74
- */
75
- export function generateConfig(
76
- directory: string,
77
- excludePatterns: string[] = ['paper.md', 'README.md', 'CLAUDE.md']
78
- ): SectionsConfig {
79
- const files = fs.readdirSync(directory).filter((f) => {
80
- if (!f.endsWith('.md')) return false;
81
- if (excludePatterns.some((p) => f.toLowerCase().includes(p.toLowerCase()))) return false;
82
- return true;
83
- });
84
-
85
- const sections: Record<string, SectionConfig> = {};
86
-
87
- for (const file of files) {
88
- const filePath = path.join(directory, file);
89
- const header = extractHeader(filePath);
90
- const baseName = path.basename(file, '.md').toLowerCase();
91
-
92
- // Determine order based on common patterns
93
- let order = DEFAULT_ORDER.findIndex((s) => baseName.includes(s));
94
- if (order === -1) order = 999;
95
-
96
- sections[file] = {
97
- header: header || titleCase(baseName),
98
- aliases: [],
99
- order: order,
100
- };
101
- }
102
-
103
- // Sort by order
104
- const sorted = Object.entries(sections)
105
- .sort((a, b) => (a[1].order ?? 999) - (b[1].order ?? 999))
106
- .reduce((acc, [k, v]) => {
107
- acc[k] = v;
108
- return acc;
109
- }, {} as Record<string, SectionConfig>);
110
-
111
- return {
112
- version: 1,
113
- description: 'Section configuration for rev import/split',
114
- sections: sorted,
115
- };
116
- }
117
-
118
- /**
119
- * Convert string to title case
120
- */
121
- function titleCase(str: string): string {
122
- return str
123
- .split(/[-_\s]+/)
124
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
125
- .join(' ');
126
- }
127
-
128
- /**
129
- * Load sections config from yaml file
130
- */
131
- export function loadConfig(configPath: string): SectionsConfig {
132
- const content = fs.readFileSync(configPath, 'utf-8');
133
- const config = YAML.parse(content);
134
-
135
- // Normalize: convert string values to full config objects
136
- const normalized: SectionsConfig = {
137
- version: config.version || 1,
138
- description: config.description,
139
- sections: {},
140
- };
141
-
142
- for (const [file, value] of Object.entries(config.sections || {})) {
143
- if (typeof value === 'string') {
144
- normalized.sections[file] = {
145
- header: value,
146
- aliases: [],
147
- };
148
- } else {
149
- const typedValue = value as SectionConfig;
150
- normalized.sections[file] = {
151
- header: typedValue.header,
152
- aliases: typedValue.aliases || [],
153
- order: typedValue.order,
154
- };
155
- }
156
- }
157
-
158
- return normalized;
159
- }
160
-
161
- /**
162
- * Save sections config to yaml file
163
- */
164
- export function saveConfig(configPath: string, config: SectionsConfig): void {
165
- const yamlStr = YAML.stringify(config, { indent: 2, lineWidth: 100 });
166
- fs.writeFileSync(configPath, yamlStr, 'utf-8');
167
- }
168
-
169
- /**
170
- * Derive a SectionsConfig from the `sections:` list in rev.yaml.
171
- *
172
- * Each listed file's header is its first markdown H1 (falling back to a
173
- * title-cased file name); order follows the list order in rev.yaml. This is
174
- * the same section list that `build` consumes, so a project that only has a
175
- * `rev.yaml` needs no separate `sections.yaml`.
176
- *
177
- * Returns null when rev.yaml is absent, unparseable, or has no `sections` list.
178
- */
179
- export function deriveSectionsFromRev(directory: string): SectionsConfig | null {
180
- const revPath = path.join(directory, 'rev.yaml');
181
- if (!fs.existsSync(revPath)) return null;
182
-
183
- let parsed: { sections?: unknown };
184
- try {
185
- parsed = YAML.parse(fs.readFileSync(revPath, 'utf-8')) || {};
186
- } catch {
187
- return null;
188
- }
189
-
190
- const list = parsed.sections;
191
- if (!Array.isArray(list) || list.length === 0) return null;
192
-
193
- const sections: Record<string, SectionConfig> = {};
194
- list.forEach((entry, index) => {
195
- if (typeof entry !== 'string') return;
196
- const header = extractFirstHeading(path.join(directory, entry)) || titleCase(path.basename(entry, '.md'));
197
- sections[entry] = { header, aliases: [], order: index };
198
- });
199
-
200
- if (Object.keys(sections).length === 0) return null;
201
-
202
- return {
203
- version: 1,
204
- description: 'Derived from rev.yaml sections list',
205
- sections,
206
- };
207
- }
208
-
209
- /**
210
- * Resolve the effective sections config for a project directory.
211
- *
212
- * Precedence (single source of truth, with optional override):
213
- * 1. An explicit sections config file (default `sections.yaml`) when it
214
- * exists — lets users override headers/aliases/order.
215
- * 2. Otherwise the `sections:` list in `rev.yaml`, via {@link deriveSectionsFromRev}.
216
- *
217
- * Returns null only when neither source yields any sections; callers turn that
218
- * into a user-facing error.
219
- */
220
- export function resolveSectionsConfig(
221
- directory: string,
222
- configFileName = 'sections.yaml'
223
- ): { config: SectionsConfig; source: string } | null {
224
- const explicitPath = path.resolve(directory, configFileName);
225
- if (fs.existsSync(explicitPath)) {
226
- return { config: loadConfig(explicitPath), source: explicitPath };
227
- }
228
-
229
- const derived = deriveSectionsFromRev(directory);
230
- if (derived) {
231
- return { config: derived, source: path.resolve(directory, 'rev.yaml') };
232
- }
233
-
234
- return null;
235
- }
236
-
237
- /**
238
- * Match a heading to a section file
239
- */
240
- export function matchHeading(
241
- heading: string,
242
- sections: Record<string, SectionConfig>
243
- ): { file: string; config: SectionConfig } | null {
244
- // Strip markdown header prefix (# or ##, etc.) before matching
245
- const normalizedHeading = heading.replace(/^#{1,6}\s+/, '').toLowerCase().trim();
246
-
247
- for (const [file, config] of Object.entries(sections)) {
248
- // Check primary header
249
- if (config.header.toLowerCase().trim() === normalizedHeading) {
250
- return { file, config };
251
- }
252
-
253
- // Check aliases
254
- if (config.aliases) {
255
- for (const alias of config.aliases) {
256
- if (alias.toLowerCase().trim() === normalizedHeading) {
257
- return { file, config };
258
- }
259
- }
260
- }
261
-
262
- // Fuzzy match: check if heading contains the key words
263
- const headerWords = config.header.toLowerCase().split(/\s+/);
264
- const headingWords = normalizedHeading.split(/\s+/);
265
- const matchCount = headerWords.filter((w) => headingWords.includes(w)).length;
266
- if (matchCount >= headerWords.length * 0.7) {
267
- return { file, config };
268
- }
269
- }
270
-
271
- return null;
272
- }
273
-
274
- /**
275
- * Extract sections from Word document text
276
- */
277
- export function extractSectionsFromText(
278
- text: string,
279
- sections: Record<string, SectionConfig>
280
- ): ExtractedSection[] {
281
- const result: ExtractedSection[] = [];
282
-
283
- // Process line by line to detect markdown headers
284
- const lines = text.split('\n');
285
- let currentSection: { file: string; header: string } | null = null;
286
- let currentContent: string[] = [];
287
-
288
- for (let i = 0; i < lines.length; i++) {
289
- const line = lines[i];
290
- if (!line) continue;
291
- const trimmed = line.trim();
292
-
293
- // Explicitly check for markdown headers (# Header)
294
- const headerMatch = trimmed.match(/^(#{1,6})\s+(.+)$/);
295
-
296
- let matchedSection: { file: string; config: SectionConfig } | null = null;
297
- if (headerMatch) {
298
- // This is a markdown header - try to match it to a section
299
- matchedSection = matchHeading(trimmed, sections);
300
- } else if (trimmed.length > 0 && trimmed.length < 100 && !trimmed.includes('.')) {
301
- // Fallback: check if short text without periods matches a section (for plain text headings)
302
- matchedSection = matchHeading(trimmed, sections);
303
- }
304
-
305
- if (matchedSection) {
306
- // Save previous section
307
- if (currentSection) {
308
- // Include header in content for proper diffing
309
- const fullContent = currentSection.header + '\n\n' + currentContent.join('\n').trim();
310
- result.push({
311
- file: currentSection.file,
312
- header: currentSection.header,
313
- content: fullContent.trim(),
314
- matched: true,
315
- });
316
- }
317
-
318
- currentSection = {
319
- file: matchedSection.file,
320
- header: trimmed,
321
- };
322
- currentContent = [];
323
- } else {
324
- currentContent.push(line);
325
- }
326
- }
327
-
328
- // Save last section
329
- if (currentSection) {
330
- // Include header in content for proper diffing
331
- const fullContent = currentSection.header + '\n\n' + currentContent.join('\n').trim();
332
- result.push({
333
- file: currentSection.file,
334
- header: currentSection.header,
335
- content: fullContent.trim(),
336
- matched: true,
337
- });
338
- }
339
-
340
- return result;
341
- }
342
-
343
- /**
344
- * Parse annotated paper.md and split back to section files
345
- */
346
- export function splitAnnotatedPaper(
347
- paperContent: string,
348
- sections: Record<string, SectionConfig>
349
- ): Map<string, string> {
350
- const result = new Map<string, string>();
351
-
352
- // Look for section markers: <!-- @section:filename.md -->
353
- const markerPattern = /<!--\s*@section:(\S+\.md)\s*-->/g;
354
- const markers = [...paperContent.matchAll(markerPattern)];
355
-
356
- if (markers.length > 0) {
357
- // Use markers
358
- for (let i = 0; i < markers.length; i++) {
359
- const marker = markers[i];
360
- if (!marker || !marker[1]) continue;
361
- const file = marker[1];
362
- const start = (marker.index || 0) + marker[0].length;
363
- const end = markers[i + 1]?.index || paperContent.length;
364
-
365
- let content = paperContent.slice(start, end).trim();
366
-
367
- // Remove trailing marker if present
368
- content = content.replace(/<!--\s*@section:\S+\.md\s*-->$/, '').trim();
369
-
370
- result.set(file, content);
371
- }
372
- } else {
373
- // Fall back to header detection
374
- const lines = paperContent.split('\n');
375
- let currentFile: string | null = null;
376
- let currentContent: string[] = [];
377
-
378
- for (const line of lines) {
379
- const headerMatch = line.match(/^#\s+(.+)$/);
380
-
381
- if (headerMatch && headerMatch[1]) {
382
- // Save previous section
383
- if (currentFile) {
384
- result.set(currentFile, currentContent.join('\n').trim());
385
- }
386
-
387
- // Find matching section file
388
- const heading = headerMatch[1].trim();
389
- const match = matchHeading(heading, sections);
390
-
391
- if (match) {
392
- currentFile = match.file;
393
- currentContent = [line];
394
- } else {
395
- // Unknown section - keep accumulating to previous
396
- currentContent.push(line);
397
- }
398
- } else {
399
- currentContent.push(line);
400
- }
401
- }
402
-
403
- // Save last section
404
- if (currentFile) {
405
- result.set(currentFile, currentContent.join('\n').trim());
406
- }
407
- }
408
-
409
- return result;
410
- }
411
-
412
- /**
413
- * Get ordered list of section files from config
414
- */
415
- export function getOrderedSections(config: SectionsConfig): string[] {
416
- const entries = Object.entries(config.sections || {});
417
-
418
- return entries
419
- .sort((a, b) => {
420
- const orderA = a[1].order ?? 999;
421
- const orderB = b[1].order ?? 999;
422
- return orderA - orderB;
423
- })
424
- .map(([file]) => file);
425
- }
1
+ /**
2
+ * Section handling - map between section .md files and combined documents
3
+ */
4
+
5
+ import * as fs from 'fs';
6
+ import * as path from 'path';
7
+ import YAML from 'yaml';
8
+ import type { SectionConfig, SectionsConfig, ExtractedSection } from './types.js';
9
+
10
+ /**
11
+ * Default section order (common academic paper structure)
12
+ */
13
+ const DEFAULT_ORDER = [
14
+ 'abstract',
15
+ 'introduction',
16
+ 'background',
17
+ 'literature',
18
+ 'theory',
19
+ 'methods',
20
+ 'materials',
21
+ 'data',
22
+ 'results',
23
+ 'analysis',
24
+ 'discussion',
25
+ 'conclusion',
26
+ 'references',
27
+ 'appendix',
28
+ 'supplementary',
29
+ ];
30
+
31
+ /**
32
+ * Extract header from a markdown file
33
+ */
34
+ export function extractHeader(filePath: string): string | null {
35
+ if (!fs.existsSync(filePath)) return null;
36
+
37
+ const content = fs.readFileSync(filePath, 'utf-8');
38
+ const lines = content.split('\n');
39
+
40
+ for (const line of lines) {
41
+ const match = line.match(/^#\s+(.+)$/);
42
+ if (match && match[1]) {
43
+ return match[1].trim();
44
+ }
45
+ }
46
+
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * Extract the first markdown heading of ANY level (`#`–`######`) from a file.
52
+ *
53
+ * Unlike {@link extractHeader} (which is H1-only by contract), this is used to
54
+ * derive a section's header from files that lead with a subsection — e.g.
55
+ * `02_objectives.md` starting with `## 1.2 Objectives`. Using the real first
56
+ * heading lets the derived header match the corresponding docx heading.
57
+ */
58
+ export function extractFirstHeading(filePath: string): string | null {
59
+ if (!fs.existsSync(filePath)) return null;
60
+
61
+ const content = fs.readFileSync(filePath, 'utf-8');
62
+ for (const line of content.split('\n')) {
63
+ const match = line.match(/^#{1,6}\s+(.+)$/);
64
+ if (match && match[1]) {
65
+ return match[1].trim();
66
+ }
67
+ }
68
+
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Generate sections.yaml from existing .md files
74
+ */
75
+ export function generateConfig(
76
+ directory: string,
77
+ excludePatterns: string[] = ['paper.md', 'README.md', 'CLAUDE.md']
78
+ ): SectionsConfig {
79
+ const files = fs.readdirSync(directory).filter((f) => {
80
+ if (!f.endsWith('.md')) return false;
81
+ if (excludePatterns.some((p) => f.toLowerCase().includes(p.toLowerCase()))) return false;
82
+ return true;
83
+ });
84
+
85
+ const sections: Record<string, SectionConfig> = {};
86
+
87
+ for (const file of files) {
88
+ const filePath = path.join(directory, file);
89
+ // Use the first heading at any level: a section file may be headed by a
90
+ // subsection (## 1.2 Objectives). H1-only extraction left such files with a
91
+ // filename-derived header that never matched the reviewed document.
92
+ const header = extractFirstHeading(filePath);
93
+ const baseName = path.basename(file, '.md').toLowerCase();
94
+
95
+ // Determine order based on common patterns
96
+ let order = DEFAULT_ORDER.findIndex((s) => baseName.includes(s));
97
+ if (order === -1) order = 999;
98
+
99
+ sections[file] = {
100
+ header: header || titleCase(baseName),
101
+ aliases: [],
102
+ order: order,
103
+ };
104
+ }
105
+
106
+ // Sort by order
107
+ const sorted = Object.entries(sections)
108
+ .sort((a, b) => (a[1].order ?? 999) - (b[1].order ?? 999))
109
+ .reduce((acc, [k, v]) => {
110
+ acc[k] = v;
111
+ return acc;
112
+ }, {} as Record<string, SectionConfig>);
113
+
114
+ return {
115
+ version: 1,
116
+ description: 'Section configuration for rev import/split',
117
+ sections: sorted,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Convert string to title case
123
+ */
124
+ function titleCase(str: string): string {
125
+ return str
126
+ .split(/[-_\s]+/)
127
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
128
+ .join(' ');
129
+ }
130
+
131
+ /**
132
+ * Load sections config from yaml file
133
+ */
134
+ export function loadConfig(configPath: string): SectionsConfig {
135
+ const content = fs.readFileSync(configPath, 'utf-8');
136
+ const config = YAML.parse(content);
137
+
138
+ // Normalize: convert string values to full config objects
139
+ const normalized: SectionsConfig = {
140
+ version: config.version || 1,
141
+ description: config.description,
142
+ sections: {},
143
+ };
144
+
145
+ for (const [file, value] of Object.entries(config.sections || {})) {
146
+ if (typeof value === 'string') {
147
+ normalized.sections[file] = {
148
+ header: value,
149
+ aliases: [],
150
+ };
151
+ } else {
152
+ const typedValue = value as SectionConfig;
153
+ normalized.sections[file] = {
154
+ header: typedValue.header,
155
+ aliases: typedValue.aliases || [],
156
+ order: typedValue.order,
157
+ };
158
+ }
159
+ }
160
+
161
+ return normalized;
162
+ }
163
+
164
+ /**
165
+ * Save sections config to yaml file
166
+ */
167
+ export function saveConfig(configPath: string, config: SectionsConfig): void {
168
+ const yamlStr = YAML.stringify(config, { indent: 2, lineWidth: 100 });
169
+ fs.writeFileSync(configPath, yamlStr, 'utf-8');
170
+ }
171
+
172
+ /**
173
+ * Derive a SectionsConfig from the `sections:` list in rev.yaml.
174
+ *
175
+ * Each listed file's header is its first markdown H1 (falling back to a
176
+ * title-cased file name); order follows the list order in rev.yaml. This is
177
+ * the same section list that `build` consumes, so a project that only has a
178
+ * `rev.yaml` needs no separate `sections.yaml`.
179
+ *
180
+ * Returns null when rev.yaml is absent, unparseable, or has no `sections` list.
181
+ */
182
+ export function deriveSectionsFromRev(directory: string): SectionsConfig | null {
183
+ const revPath = path.join(directory, 'rev.yaml');
184
+ if (!fs.existsSync(revPath)) return null;
185
+
186
+ let parsed: { sections?: unknown };
187
+ try {
188
+ parsed = YAML.parse(fs.readFileSync(revPath, 'utf-8')) || {};
189
+ } catch {
190
+ return null;
191
+ }
192
+
193
+ const list = parsed.sections;
194
+ if (!Array.isArray(list) || list.length === 0) return null;
195
+
196
+ const sections: Record<string, SectionConfig> = {};
197
+ list.forEach((entry, index) => {
198
+ if (typeof entry !== 'string') return;
199
+ const header = extractFirstHeading(path.join(directory, entry)) || titleCase(path.basename(entry, '.md'));
200
+ sections[entry] = { header, aliases: [], order: index };
201
+ });
202
+
203
+ if (Object.keys(sections).length === 0) return null;
204
+
205
+ return {
206
+ version: 1,
207
+ description: 'Derived from rev.yaml sections list',
208
+ sections,
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Resolve the effective sections config for a project directory.
214
+ *
215
+ * Precedence (single source of truth, with optional override):
216
+ * 1. An explicit sections config file (default `sections.yaml`) when it
217
+ * exists lets users override headers/aliases/order.
218
+ * 2. Otherwise the `sections:` list in `rev.yaml`, via {@link deriveSectionsFromRev}.
219
+ *
220
+ * Returns null only when neither source yields any sections; callers turn that
221
+ * into a user-facing error.
222
+ */
223
+ export function resolveSectionsConfig(
224
+ directory: string,
225
+ configFileName = 'sections.yaml'
226
+ ): { config: SectionsConfig; source: string } | null {
227
+ const explicitPath = path.resolve(directory, configFileName);
228
+ if (fs.existsSync(explicitPath)) {
229
+ return { config: loadConfig(explicitPath), source: explicitPath };
230
+ }
231
+
232
+ const derived = deriveSectionsFromRev(directory);
233
+ if (derived) {
234
+ return { config: derived, source: path.resolve(directory, 'rev.yaml') };
235
+ }
236
+
237
+ return null;
238
+ }
239
+
240
+ /**
241
+ * Match a heading to a section file
242
+ */
243
+ export function matchHeading(
244
+ heading: string,
245
+ sections: Record<string, SectionConfig>
246
+ ): { file: string; config: SectionConfig } | null {
247
+ // Strip markdown header prefix (# or ##, etc.) before matching
248
+ const normalizedHeading = heading.replace(/^#{1,6}\s+/, '').toLowerCase().trim();
249
+
250
+ for (const [file, config] of Object.entries(sections)) {
251
+ // Check primary header
252
+ if (config.header.toLowerCase().trim() === normalizedHeading) {
253
+ return { file, config };
254
+ }
255
+
256
+ // Check aliases
257
+ if (config.aliases) {
258
+ for (const alias of config.aliases) {
259
+ if (alias.toLowerCase().trim() === normalizedHeading) {
260
+ return { file, config };
261
+ }
262
+ }
263
+ }
264
+
265
+ // Fuzzy match: check if heading contains the key words
266
+ const headerWords = config.header.toLowerCase().split(/\s+/);
267
+ const headingWords = normalizedHeading.split(/\s+/);
268
+ const matchCount = headerWords.filter((w) => headingWords.includes(w)).length;
269
+ if (matchCount >= headerWords.length * 0.7) {
270
+ return { file, config };
271
+ }
272
+ }
273
+
274
+ return null;
275
+ }
276
+
277
+ /**
278
+ * Extract sections from Word document text
279
+ */
280
+ export function extractSectionsFromText(
281
+ text: string,
282
+ sections: Record<string, SectionConfig>
283
+ ): ExtractedSection[] {
284
+ const result: ExtractedSection[] = [];
285
+
286
+ // Process line by line to detect markdown headers
287
+ const lines = text.split('\n');
288
+ let currentSection: { file: string; header: string } | null = null;
289
+ let currentContent: string[] = [];
290
+
291
+ for (let i = 0; i < lines.length; i++) {
292
+ const line = lines[i];
293
+ if (!line) continue;
294
+ const trimmed = line.trim();
295
+
296
+ // Explicitly check for markdown headers (# Header)
297
+ const headerMatch = trimmed.match(/^(#{1,6})\s+(.+)$/);
298
+
299
+ let matchedSection: { file: string; config: SectionConfig } | null = null;
300
+ if (headerMatch) {
301
+ // This is a markdown header - try to match it to a section
302
+ matchedSection = matchHeading(trimmed, sections);
303
+ } else if (trimmed.length > 0 && trimmed.length < 100 && !trimmed.includes('.')) {
304
+ // Fallback: check if short text without periods matches a section (for plain text headings)
305
+ matchedSection = matchHeading(trimmed, sections);
306
+ }
307
+
308
+ if (matchedSection) {
309
+ // Save previous section
310
+ if (currentSection) {
311
+ // Include header in content for proper diffing
312
+ const fullContent = currentSection.header + '\n\n' + currentContent.join('\n').trim();
313
+ result.push({
314
+ file: currentSection.file,
315
+ header: currentSection.header,
316
+ content: fullContent.trim(),
317
+ matched: true,
318
+ });
319
+ }
320
+
321
+ currentSection = {
322
+ file: matchedSection.file,
323
+ header: trimmed,
324
+ };
325
+ currentContent = [];
326
+ } else {
327
+ currentContent.push(line);
328
+ }
329
+ }
330
+
331
+ // Save last section
332
+ if (currentSection) {
333
+ // Include header in content for proper diffing
334
+ const fullContent = currentSection.header + '\n\n' + currentContent.join('\n').trim();
335
+ result.push({
336
+ file: currentSection.file,
337
+ header: currentSection.header,
338
+ content: fullContent.trim(),
339
+ matched: true,
340
+ });
341
+ }
342
+
343
+ return result;
344
+ }
345
+
346
+ /**
347
+ * Parse annotated paper.md and split back to section files
348
+ */
349
+ export function splitAnnotatedPaper(
350
+ paperContent: string,
351
+ sections: Record<string, SectionConfig>
352
+ ): Map<string, string> {
353
+ const result = new Map<string, string>();
354
+
355
+ // Look for section markers: <!-- @section:filename.md -->
356
+ const markerPattern = /<!--\s*@section:(\S+\.md)\s*-->/g;
357
+ const markers = [...paperContent.matchAll(markerPattern)];
358
+
359
+ if (markers.length > 0) {
360
+ // Use markers
361
+ for (let i = 0; i < markers.length; i++) {
362
+ const marker = markers[i];
363
+ if (!marker || !marker[1]) continue;
364
+ const file = marker[1];
365
+ const start = (marker.index || 0) + marker[0].length;
366
+ const end = markers[i + 1]?.index || paperContent.length;
367
+
368
+ let content = paperContent.slice(start, end).trim();
369
+
370
+ // Remove trailing marker if present
371
+ content = content.replace(/<!--\s*@section:\S+\.md\s*-->$/, '').trim();
372
+
373
+ result.set(file, content);
374
+ }
375
+ } else {
376
+ // Fall back to header detection
377
+ const lines = paperContent.split('\n');
378
+ let currentFile: string | null = null;
379
+ let currentContent: string[] = [];
380
+
381
+ for (const line of lines) {
382
+ const headerMatch = line.match(/^#{1,6}\s+(.+)$/);
383
+
384
+ if (headerMatch && headerMatch[1]) {
385
+ // Save previous section
386
+ if (currentFile) {
387
+ result.set(currentFile, currentContent.join('\n').trim());
388
+ }
389
+
390
+ // Find matching section file
391
+ const heading = headerMatch[1].trim();
392
+ const match = matchHeading(heading, sections);
393
+
394
+ if (match) {
395
+ currentFile = match.file;
396
+ currentContent = [line];
397
+ } else {
398
+ // Unknown section - keep accumulating to previous
399
+ currentContent.push(line);
400
+ }
401
+ } else {
402
+ currentContent.push(line);
403
+ }
404
+ }
405
+
406
+ // Save last section
407
+ if (currentFile) {
408
+ result.set(currentFile, currentContent.join('\n').trim());
409
+ }
410
+ }
411
+
412
+ return result;
413
+ }
414
+
415
+ /**
416
+ * Get ordered list of section files from config
417
+ */
418
+ export function getOrderedSections(config: SectionsConfig): string[] {
419
+ const entries = Object.entries(config.sections || {});
420
+
421
+ return entries
422
+ .sort((a, b) => {
423
+ const orderA = a[1].order ?? 999;
424
+ const orderB = b[1].order ?? 999;
425
+ return orderA - orderB;
426
+ })
427
+ .map(([file]) => file);
428
+ }