@open-livex-wiki/core 0.1.0 → 0.2.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 (47) hide show
  1. package/dist/browser.d.ts +3 -3
  2. package/dist/browser.d.ts.map +1 -1
  3. package/dist/browser.js +2 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/coverage.d.ts +8 -0
  6. package/dist/coverage.d.ts.map +1 -0
  7. package/dist/coverage.js +425 -0
  8. package/dist/coverage.js.map +1 -0
  9. package/dist/diff-impact.d.ts.map +1 -1
  10. package/dist/diff-impact.js +109 -45
  11. package/dist/diff-impact.js.map +1 -1
  12. package/dist/discover.d.ts +35 -3
  13. package/dist/discover.d.ts.map +1 -1
  14. package/dist/discover.js +1800 -293
  15. package/dist/discover.js.map +1 -1
  16. package/dist/frontmatter.d.ts.map +1 -1
  17. package/dist/frontmatter.js +96 -6
  18. package/dist/frontmatter.js.map +1 -1
  19. package/dist/gate.d.ts.map +1 -1
  20. package/dist/gate.js +2 -0
  21. package/dist/gate.js.map +1 -1
  22. package/dist/graph.d.ts.map +1 -1
  23. package/dist/graph.js +3 -0
  24. package/dist/graph.js.map +1 -1
  25. package/dist/index.d.ts +6 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +5 -4
  28. package/dist/index.js.map +1 -1
  29. package/dist/loader.d.ts +2 -1
  30. package/dist/loader.d.ts.map +1 -1
  31. package/dist/loader.js +427 -178
  32. package/dist/loader.js.map +1 -1
  33. package/dist/schemas.d.ts +79 -3
  34. package/dist/schemas.d.ts.map +1 -1
  35. package/dist/schemas.js +49 -4
  36. package/dist/schemas.js.map +1 -1
  37. package/dist/types.d.ts +71 -3
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/utils.d.ts +11 -0
  40. package/dist/utils.d.ts.map +1 -1
  41. package/dist/utils.js +35 -2
  42. package/dist/utils.js.map +1 -1
  43. package/dist/validator.d.ts +32 -1
  44. package/dist/validator.d.ts.map +1 -1
  45. package/dist/validator.js +346 -26
  46. package/dist/validator.js.map +1 -1
  47. package/package.json +1 -1
package/dist/loader.js CHANGED
@@ -2,7 +2,8 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { parseFrontmatterMarkdown, parseSafeYaml, } from "./frontmatter.js";
4
4
  import { DomainFrontmatterSchema, InfrastructureFrontmatterSchema, SceneFrontmatterSchema, WikiConfigSchema, } from "./schemas.js";
5
- import { extractMarkdownHeadings, extractPendingConfirmations, extractSceneChains, isSafeContainedRelativePath, toPosixPath, } from "./utils.js";
5
+ import { extractMarkdownHeadings, isSafeContainedRelativePath, parseSceneMarkdownStructure, toPosixPath, } from "./utils.js";
6
+ const LOAD_WIKI_CONCURRENCY = 64;
6
7
  export function isPathStrictlyInsideRoot(rootPath, candidatePath) {
7
8
  const normRoot = process.platform === "win32" ? path.resolve(rootPath).toLowerCase() : path.resolve(rootPath);
8
9
  const normCandidate = process.platform === "win32"
@@ -29,8 +30,37 @@ async function pathExists(p) {
29
30
  return false;
30
31
  }
31
32
  }
33
+ async function mapWithConcurrency(items, concurrency, mapper) {
34
+ const total = items.length;
35
+ if (total === 0) {
36
+ return [];
37
+ }
38
+ const results = new Array(total);
39
+ const workerCount = Math.max(1, Math.min(concurrency, total));
40
+ let nextIndex = 0;
41
+ let aborted = false;
42
+ async function runWorker() {
43
+ while (!aborted) {
44
+ const idx = nextIndex;
45
+ if (idx >= total) {
46
+ return;
47
+ }
48
+ nextIndex += 1;
49
+ try {
50
+ results[idx] = await mapper(items[idx], idx);
51
+ }
52
+ catch (err) {
53
+ aborted = true;
54
+ throw err;
55
+ }
56
+ }
57
+ }
58
+ await Promise.all(Array.from({ length: workerCount }, () => runWorker()));
59
+ return results;
60
+ }
32
61
  /**
33
- * Loads and parses a LiveX Wiki repository from `rootDir`.
62
+ * Loads and parses a LiveX Wiki repository from `rootDir` with bounded parallel I/O (`concurrency = 32`)
63
+ * and deterministic lexicographical ordering across all maps, arrays, and diagnostics.
34
64
  */
35
65
  export async function loadWiki(rootDir, options = {}) {
36
66
  const resolvedRoot = path.resolve(rootDir);
@@ -178,170 +208,296 @@ export async function loadWiki(rootDir, options = {}) {
178
208
  const sortedDomainDirs = domainEntries
179
209
  .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && !entry.name.startsWith("."))
180
210
  .sort((a, b) => a.name.localeCompare(b.name));
181
- for (const domainDirEntry of sortedDomainDirs) {
211
+ // Phase 1: Scan domain directories concurrently, reusing Dirents and checking realpath only on symlinks/junctions
212
+ const scannedDomains = await mapWithConcurrency(sortedDomainDirs, LOAD_WIKI_CONCURRENCY, async (domainDirEntry) => {
182
213
  const folderDomainId = domainDirEntry.name;
183
214
  const domainDirPath = path.join(domainsRoot, folderDomainId);
184
215
  const domainIndexPath = path.join(domainDirPath, "index.md");
185
216
  const domainRelPath = toPosixPath(path.relative(resolvedRoot, domainIndexPath));
186
- if (!(await isRealpathStrictlyInside(rootRealPath, domainDirPath))) {
187
- const msg = `Domain directory "${toPosixPath(path.relative(resolvedRoot, domainDirPath))}" escapes wiki root via symlink or junction`;
188
- if (options.strict) {
189
- throw new Error(msg);
217
+ const dirErrors = [];
218
+ if (domainDirEntry.isSymbolicLink()) {
219
+ if (!(await isRealpathStrictlyInside(rootRealPath, domainDirPath))) {
220
+ const msg = `Domain directory "${toPosixPath(path.relative(resolvedRoot, domainDirPath))}" escapes wiki root via symlink or junction`;
221
+ if (options.strict) {
222
+ throw new Error(msg);
223
+ }
224
+ dirErrors.push({
225
+ relativePath: toPosixPath(path.relative(resolvedRoot, domainDirPath)),
226
+ filePath: domainDirPath,
227
+ entityId: folderDomainId,
228
+ code: "UNSAFE_SYMLINK_ESCAPE",
229
+ message: msg,
230
+ });
231
+ return {
232
+ folderDomainId,
233
+ domainDirPath,
234
+ domainIndexPath,
235
+ domainRelPath,
236
+ skipped: true,
237
+ dirErrors,
238
+ sortedSceneDirs: [],
239
+ };
240
+ }
241
+ try {
242
+ const domainStat = await fs.stat(domainDirPath);
243
+ if (!domainStat.isDirectory()) {
244
+ return {
245
+ folderDomainId,
246
+ domainDirPath,
247
+ domainIndexPath,
248
+ domainRelPath,
249
+ skipped: true,
250
+ dirErrors,
251
+ sortedSceneDirs: [],
252
+ };
253
+ }
254
+ }
255
+ catch {
256
+ return {
257
+ folderDomainId,
258
+ domainDirPath,
259
+ domainIndexPath,
260
+ domainRelPath,
261
+ skipped: true,
262
+ dirErrors,
263
+ sortedSceneDirs: [],
264
+ };
190
265
  }
191
- parseErrors.push({
192
- relativePath: toPosixPath(path.relative(resolvedRoot, domainDirPath)),
193
- filePath: domainDirPath,
194
- entityId: folderDomainId,
195
- code: "UNSAFE_SYMLINK_ESCAPE",
196
- message: msg,
197
- });
198
- continue;
199
266
  }
267
+ let subEntries;
200
268
  try {
201
- const domainStat = await fs.stat(domainDirPath);
202
- if (!domainStat.isDirectory()) {
203
- continue;
204
- }
269
+ subEntries = await fs.readdir(domainDirPath, { withFileTypes: true });
205
270
  }
206
271
  catch {
207
- continue;
272
+ return {
273
+ folderDomainId,
274
+ domainDirPath,
275
+ domainIndexPath,
276
+ domainRelPath,
277
+ skipped: true,
278
+ dirErrors,
279
+ sortedSceneDirs: [],
280
+ };
208
281
  }
209
- const domainSceneIds = [];
210
- // Load scenes under <domainsDir>/<domainId>/<sceneId>/
211
- const subEntries = await fs.readdir(domainDirPath, { withFileTypes: true });
282
+ const domainIndexEntry = subEntries.find((e) => e.name === "index.md");
212
283
  const sortedSceneDirs = subEntries
213
284
  .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && !entry.name.startsWith("."))
214
285
  .sort((a, b) => a.name.localeCompare(b.name));
215
- for (const sceneDirEntry of sortedSceneDirs) {
216
- const folderSceneId = sceneDirEntry.name;
217
- const sceneDirPath = path.join(domainDirPath, folderSceneId);
218
- const sceneIndexPath = path.join(sceneDirPath, "index.md");
219
- const sceneRelPath = toPosixPath(path.relative(resolvedRoot, sceneIndexPath));
220
- const canonicalSceneId = `${folderDomainId}/${folderSceneId}`;
286
+ return {
287
+ folderDomainId,
288
+ domainDirPath,
289
+ domainIndexPath,
290
+ domainRelPath,
291
+ skipped: false,
292
+ dirErrors,
293
+ domainIndexEntry,
294
+ sortedSceneDirs,
295
+ };
296
+ });
297
+ // Phase 2: Flatten all scene tasks across all domains so bounded concurrency=32 stays saturated even for 1 mega-domain
298
+ const sceneTasks = [];
299
+ for (let dIdx = 0; dIdx < scannedDomains.length; dIdx++) {
300
+ const dom = scannedDomains[dIdx];
301
+ if (dom.skipped) {
302
+ continue;
303
+ }
304
+ for (const sceneDirEntry of dom.sortedSceneDirs) {
305
+ sceneTasks.push({
306
+ domainIndex: dIdx,
307
+ folderDomainId: dom.folderDomainId,
308
+ domainDirPath: dom.domainDirPath,
309
+ sceneDirEntry,
310
+ });
311
+ }
312
+ }
313
+ const loadedSceneResults = await mapWithConcurrency(sceneTasks, LOAD_WIKI_CONCURRENCY, async (task) => {
314
+ const { domainIndex, folderDomainId, domainDirPath, sceneDirEntry } = task;
315
+ const folderSceneId = sceneDirEntry.name;
316
+ const sceneDirPath = path.join(domainDirPath, folderSceneId);
317
+ const sceneIndexPath = path.join(sceneDirPath, "index.md");
318
+ const sceneRelPath = toPosixPath(path.relative(resolvedRoot, sceneIndexPath));
319
+ const canonicalSceneId = `${folderDomainId}/${folderSceneId}`;
320
+ const errors = [];
321
+ if (sceneDirEntry.isSymbolicLink()) {
221
322
  if (!(await isRealpathStrictlyInside(rootRealPath, sceneDirPath))) {
222
323
  const msg = `Scene directory "${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}" escapes wiki root via symlink or junction`;
223
324
  if (options.strict) {
224
325
  throw new Error(msg);
225
326
  }
226
- parseErrors.push({
327
+ errors.push({
227
328
  relativePath: toPosixPath(path.relative(resolvedRoot, sceneDirPath)),
228
329
  filePath: sceneDirPath,
229
330
  entityId: canonicalSceneId,
230
331
  code: "UNSAFE_SYMLINK_ESCAPE",
231
332
  message: msg,
232
333
  });
233
- continue;
334
+ return { domainIndex, canonicalSceneId, errors };
234
335
  }
235
336
  try {
236
337
  const sceneStat = await fs.stat(sceneDirPath);
237
338
  if (!sceneStat.isDirectory()) {
238
- continue;
339
+ return { domainIndex, canonicalSceneId, errors };
239
340
  }
240
341
  }
241
342
  catch {
242
- continue;
343
+ return { domainIndex, canonicalSceneId, errors };
243
344
  }
244
- if (!(await pathExists(sceneIndexPath))) {
245
- const msg = `Missing index.md in scene directory ${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}`;
246
- if (options.strict) {
247
- throw new Error(msg);
248
- }
249
- parseErrors.push({
250
- relativePath: sceneRelPath,
251
- filePath: sceneIndexPath,
252
- entityId: canonicalSceneId,
253
- code: "MISSING_SCENE_INDEX",
254
- message: msg,
255
- });
256
- continue;
345
+ }
346
+ let sceneFiles;
347
+ try {
348
+ sceneFiles = await fs.readdir(sceneDirPath, { withFileTypes: true });
349
+ }
350
+ catch {
351
+ return { domainIndex, canonicalSceneId, errors };
352
+ }
353
+ const indexEntry = sceneFiles.find((f) => f.name === "index.md");
354
+ if (!indexEntry) {
355
+ const msg = `Missing index.md in scene directory ${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}`;
356
+ if (options.strict) {
357
+ throw new Error(msg);
257
358
  }
359
+ errors.push({
360
+ relativePath: sceneRelPath,
361
+ filePath: sceneIndexPath,
362
+ entityId: canonicalSceneId,
363
+ code: "MISSING_SCENE_INDEX",
364
+ message: msg,
365
+ });
366
+ return { domainIndex, canonicalSceneId, errors };
367
+ }
368
+ if (indexEntry.isSymbolicLink()) {
258
369
  if (!(await isRealpathStrictlyInside(rootRealPath, sceneIndexPath))) {
259
370
  const msg = `Scene index "${sceneRelPath}" escapes wiki root via symlink or junction`;
260
371
  if (options.strict) {
261
372
  throw new Error(msg);
262
373
  }
263
- parseErrors.push({
374
+ errors.push({
264
375
  relativePath: sceneRelPath,
265
376
  filePath: sceneIndexPath,
266
377
  entityId: canonicalSceneId,
267
378
  code: "UNSAFE_SYMLINK_ESCAPE",
268
379
  message: msg,
269
380
  });
270
- continue;
381
+ return { domainIndex, canonicalSceneId, errors };
271
382
  }
272
- const rawScene = await fs.readFile(sceneIndexPath, "utf8");
273
- let parsedMatter;
274
383
  try {
275
- parsedMatter = parseFrontmatterMarkdown(rawScene);
276
- }
277
- catch (err) {
278
- const detail = err instanceof Error ? err.message : String(err);
279
- if (options.strict) {
280
- throw new Error(`Failed to parse frontmatter in ${sceneRelPath}: ${detail}`);
384
+ if (!(await fs.stat(sceneIndexPath)).isFile()) {
385
+ const msg = `Missing index.md in scene directory ${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}`;
386
+ if (options.strict) {
387
+ throw new Error(msg);
388
+ }
389
+ errors.push({
390
+ relativePath: sceneRelPath,
391
+ filePath: sceneIndexPath,
392
+ entityId: canonicalSceneId,
393
+ code: "MISSING_SCENE_INDEX",
394
+ message: msg,
395
+ });
396
+ return { domainIndex, canonicalSceneId, errors };
281
397
  }
282
- parseErrors.push({
283
- relativePath: sceneRelPath,
284
- filePath: sceneIndexPath,
285
- entityId: canonicalSceneId,
286
- code: "FRONTMATTER_PARSE_ERROR",
287
- message: `Failed to parse frontmatter in ${sceneRelPath}: ${detail}`,
288
- });
289
- continue;
290
398
  }
291
- const rawSchema = parsedMatter.data?.schema;
292
- const isInfraSchema = rawSchema === "infrastructure-index/v1";
293
- const validation = isInfraSchema
294
- ? InfrastructureFrontmatterSchema.safeParse(parsedMatter.data)
295
- : SceneFrontmatterSchema.safeParse(parsedMatter.data);
296
- if (!validation.success) {
297
- const msg = validation.error.issues
298
- .map((iss) => `${iss.path.join(".") || "frontmatter"}: ${iss.message}`)
299
- .join("; ");
399
+ catch {
400
+ const msg = `Missing index.md in scene directory ${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}`;
300
401
  if (options.strict) {
301
- throw new Error(`Invalid frontmatter in ${sceneRelPath}: ${msg}`);
402
+ throw new Error(msg);
302
403
  }
303
- parseErrors.push({
404
+ errors.push({
304
405
  relativePath: sceneRelPath,
305
406
  filePath: sceneIndexPath,
306
407
  entityId: canonicalSceneId,
307
- field: validation.error.issues[0]?.path.join("."),
308
- code: "INVALID_SCENE_FRONTMATTER",
408
+ code: "MISSING_SCENE_INDEX",
309
409
  message: msg,
310
410
  });
311
- continue;
411
+ return { domainIndex, canonicalSceneId, errors };
312
412
  }
313
- if (validation.data.sceneId !== folderSceneId) {
314
- const msg = `Frontmatter sceneId "${validation.data.sceneId}" does not match folder name "${folderSceneId}"`;
315
- if (options.strict) {
316
- throw new Error(`${sceneRelPath}: ${msg}`);
317
- }
318
- parseErrors.push({
319
- relativePath: sceneRelPath,
320
- filePath: sceneIndexPath,
321
- entityId: canonicalSceneId,
322
- field: "sceneId",
323
- code: "FOLDER_ID_MISMATCH",
324
- message: msg,
325
- });
413
+ }
414
+ else if (!indexEntry.isFile()) {
415
+ const msg = `Missing index.md in scene directory ${toPosixPath(path.relative(resolvedRoot, sceneDirPath))}`;
416
+ if (options.strict) {
417
+ throw new Error(msg);
418
+ }
419
+ errors.push({
420
+ relativePath: sceneRelPath,
421
+ filePath: sceneIndexPath,
422
+ entityId: canonicalSceneId,
423
+ code: "MISSING_SCENE_INDEX",
424
+ message: msg,
425
+ });
426
+ return { domainIndex, canonicalSceneId, errors };
427
+ }
428
+ const rawScene = await fs.readFile(sceneIndexPath, "utf8");
429
+ let parsedMatter;
430
+ try {
431
+ parsedMatter = parseFrontmatterMarkdown(rawScene);
432
+ }
433
+ catch (err) {
434
+ const detail = err instanceof Error ? err.message : String(err);
435
+ if (options.strict) {
436
+ throw new Error(`Failed to parse frontmatter in ${sceneRelPath}: ${detail}`);
326
437
  }
327
- // Load optional sibling detail docs (*.md excluding index.md)
328
- const sceneFiles = await fs.readdir(sceneDirPath, { withFileTypes: true });
329
- const detailEntries = sceneFiles
330
- .filter((f) => (f.isFile() || f.isSymbolicLink()) &&
331
- f.name.endsWith(".md") &&
332
- f.name !== "index.md" &&
333
- !f.name.startsWith("."))
334
- .sort((a, b) => a.name.localeCompare(b.name));
335
- const details = [];
336
- for (const detailFile of detailEntries) {
337
- const detailPath = path.join(sceneDirPath, detailFile.name);
338
- const detailRelPath = toPosixPath(path.relative(resolvedRoot, detailPath));
438
+ errors.push({
439
+ relativePath: sceneRelPath,
440
+ filePath: sceneIndexPath,
441
+ entityId: canonicalSceneId,
442
+ code: "FRONTMATTER_PARSE_ERROR",
443
+ message: `Failed to parse frontmatter in ${sceneRelPath}: ${detail}`,
444
+ });
445
+ return { domainIndex, canonicalSceneId, errors };
446
+ }
447
+ const rawSchema = parsedMatter.data?.schema;
448
+ const isInfraSchema = rawSchema === "infrastructure-index/v1";
449
+ const validation = isInfraSchema
450
+ ? InfrastructureFrontmatterSchema.safeParse(parsedMatter.data)
451
+ : SceneFrontmatterSchema.safeParse(parsedMatter.data);
452
+ if (!validation.success) {
453
+ const msg = validation.error.issues
454
+ .map((iss) => `${iss.path.join(".") || "frontmatter"}: ${iss.message}`)
455
+ .join("; ");
456
+ if (options.strict) {
457
+ throw new Error(`Invalid frontmatter in ${sceneRelPath}: ${msg}`);
458
+ }
459
+ errors.push({
460
+ relativePath: sceneRelPath,
461
+ filePath: sceneIndexPath,
462
+ entityId: canonicalSceneId,
463
+ field: validation.error.issues[0]?.path.join("."),
464
+ code: "INVALID_SCENE_FRONTMATTER",
465
+ message: msg,
466
+ });
467
+ return { domainIndex, canonicalSceneId, errors };
468
+ }
469
+ if (validation.data.sceneId !== folderSceneId) {
470
+ const msg = `Frontmatter sceneId "${validation.data.sceneId}" does not match folder name "${folderSceneId}"`;
471
+ if (options.strict) {
472
+ throw new Error(`${sceneRelPath}: ${msg}`);
473
+ }
474
+ errors.push({
475
+ relativePath: sceneRelPath,
476
+ filePath: sceneIndexPath,
477
+ entityId: canonicalSceneId,
478
+ field: "sceneId",
479
+ code: "FOLDER_ID_MISMATCH",
480
+ message: msg,
481
+ });
482
+ }
483
+ // Load optional sibling detail docs (*.md excluding index.md) reusing `sceneFiles` Dirents
484
+ const detailEntries = sceneFiles
485
+ .filter((f) => (f.isFile() || f.isSymbolicLink()) &&
486
+ f.name.endsWith(".md") &&
487
+ f.name !== "index.md" &&
488
+ !f.name.startsWith("."))
489
+ .sort((a, b) => a.name.localeCompare(b.name));
490
+ const details = [];
491
+ for (const detailFile of detailEntries) {
492
+ const detailPath = path.join(sceneDirPath, detailFile.name);
493
+ const detailRelPath = toPosixPath(path.relative(resolvedRoot, detailPath));
494
+ if (detailFile.isSymbolicLink()) {
339
495
  if (!(await isRealpathStrictlyInside(rootRealPath, detailPath))) {
340
496
  const msg = `Detail document "${detailRelPath}" escapes wiki root via symlink or junction`;
341
497
  if (options.strict) {
342
498
  throw new Error(msg);
343
499
  }
344
- parseErrors.push({
500
+ errors.push({
345
501
  relativePath: detailRelPath,
346
502
  filePath: detailPath,
347
503
  entityId: canonicalSceneId,
@@ -359,89 +515,140 @@ export async function loadWiki(rootDir, options = {}) {
359
515
  catch {
360
516
  continue;
361
517
  }
362
- const detailRaw = await fs.readFile(detailPath, "utf8");
363
- let detailMatter;
364
- try {
365
- detailMatter = parseFrontmatterMarkdown(detailRaw);
366
- }
367
- catch (err) {
368
- const detail = err instanceof Error ? err.message : String(err);
369
- if (options.strict) {
370
- throw new Error(`Failed to parse frontmatter in ${detailRelPath}: ${detail}`);
371
- }
372
- parseErrors.push({
373
- relativePath: detailRelPath,
374
- filePath: detailPath,
375
- entityId: canonicalSceneId,
376
- code: "DETAIL_FRONTMATTER_PARSE_ERROR",
377
- message: `Failed to parse frontmatter in ${detailRelPath}: ${detail}`,
378
- });
379
- continue;
518
+ }
519
+ const detailRaw = await fs.readFile(detailPath, "utf8");
520
+ let detailMatter;
521
+ try {
522
+ detailMatter = parseFrontmatterMarkdown(detailRaw);
523
+ }
524
+ catch (err) {
525
+ const detail = err instanceof Error ? err.message : String(err);
526
+ if (options.strict) {
527
+ throw new Error(`Failed to parse frontmatter in ${detailRelPath}: ${detail}`);
380
528
  }
381
- const detailHeadings = extractMarkdownHeadings(detailMatter.content);
382
- const nameStem = detailFile.name.slice(0, -3);
383
- const fmTitle = typeof detailMatter.data?.title === "string" && detailMatter.data.title.trim().length > 0
384
- ? detailMatter.data.title.trim()
385
- : undefined;
386
- details.push({
387
- name: nameStem,
388
- title: fmTitle ?? detailHeadings[0]?.text ?? nameStem,
529
+ errors.push({
389
530
  relativePath: detailRelPath,
390
531
  filePath: detailPath,
391
- frontmatter: detailMatter.data ?? {},
392
- content: detailMatter.content,
393
- raw: detailRaw,
532
+ entityId: canonicalSceneId,
533
+ code: "DETAIL_FRONTMATTER_PARSE_ERROR",
534
+ message: `Failed to parse frontmatter in ${detailRelPath}: ${detail}`,
394
535
  });
536
+ continue;
395
537
  }
396
- const headings = extractMarkdownHeadings(parsedMatter.content).map((h) => h.text);
397
- const chains = extractSceneChains(parsedMatter.content);
398
- const pending = extractPendingConfirmations(parsedMatter.content);
399
- const sceneDoc = {
400
- id: canonicalSceneId,
401
- domainId: folderDomainId,
402
- sceneId: folderSceneId,
403
- kind: isInfraSchema ? "infrastructure" : "scene",
404
- relativePath: sceneRelPath,
405
- filePath: sceneIndexPath,
406
- frontmatter: validation.data,
407
- content: parsedMatter.content,
408
- raw: rawScene,
409
- headings,
410
- chains,
411
- pendingItems: pending.items,
412
- hasPendingConfirmations: pending.hasActiveItems,
413
- details,
414
- };
415
- scenes.set(canonicalSceneId, sceneDoc);
416
- domainSceneIds.push(canonicalSceneId);
538
+ const detailHeadings = extractMarkdownHeadings(detailMatter.content);
539
+ const nameStem = detailFile.name.slice(0, -3);
540
+ const fmTitle = typeof detailMatter.data?.title === "string" && detailMatter.data.title.trim().length > 0
541
+ ? detailMatter.data.title.trim()
542
+ : undefined;
543
+ details.push({
544
+ name: nameStem,
545
+ title: fmTitle ?? detailHeadings[0]?.text ?? nameStem,
546
+ relativePath: detailRelPath,
547
+ filePath: detailPath,
548
+ frontmatter: detailMatter.data ?? {},
549
+ content: detailMatter.content,
550
+ raw: detailRaw,
551
+ });
417
552
  }
418
- if (!(await pathExists(domainIndexPath))) {
553
+ const { headings, chains, pending } = parseSceneMarkdownStructure(parsedMatter.content);
554
+ const sceneDoc = {
555
+ id: canonicalSceneId,
556
+ domainId: folderDomainId,
557
+ sceneId: folderSceneId,
558
+ kind: isInfraSchema ? "infrastructure" : "scene",
559
+ relativePath: sceneRelPath,
560
+ filePath: sceneIndexPath,
561
+ frontmatter: validation.data,
562
+ content: parsedMatter.content,
563
+ raw: rawScene,
564
+ headings,
565
+ chains,
566
+ pendingItems: pending.items,
567
+ hasPendingConfirmations: pending.hasActiveItems,
568
+ details,
569
+ };
570
+ return { domainIndex, canonicalSceneId, sceneDoc, errors };
571
+ });
572
+ // Phase 3: Parse domain index.md files concurrently
573
+ const loadedDomainIndexResults = await mapWithConcurrency(scannedDomains, LOAD_WIKI_CONCURRENCY, async (dom) => {
574
+ if (dom.skipped) {
575
+ return { errors: [] };
576
+ }
577
+ const { folderDomainId, domainDirPath, domainIndexPath, domainRelPath, domainIndexEntry } = dom;
578
+ const errors = [];
579
+ if (!domainIndexEntry) {
419
580
  const msg = `Missing index.md in domain directory ${toPosixPath(path.relative(resolvedRoot, domainDirPath))}`;
420
581
  if (options.strict) {
421
582
  throw new Error(msg);
422
583
  }
423
- parseErrors.push({
584
+ errors.push({
424
585
  relativePath: domainRelPath,
425
586
  filePath: domainIndexPath,
426
587
  entityId: folderDomainId,
427
588
  code: "MISSING_DOMAIN_INDEX",
428
589
  message: msg,
429
590
  });
430
- continue;
591
+ return { errors };
431
592
  }
432
- if (!(await isRealpathStrictlyInside(rootRealPath, domainIndexPath))) {
433
- const msg = `Domain index "${domainRelPath}" escapes wiki root via symlink or junction`;
593
+ if (domainIndexEntry.isSymbolicLink()) {
594
+ if (!(await isRealpathStrictlyInside(rootRealPath, domainIndexPath))) {
595
+ const msg = `Domain index "${domainRelPath}" escapes wiki root via symlink or junction`;
596
+ if (options.strict) {
597
+ throw new Error(msg);
598
+ }
599
+ errors.push({
600
+ relativePath: domainRelPath,
601
+ filePath: domainIndexPath,
602
+ entityId: folderDomainId,
603
+ code: "UNSAFE_SYMLINK_ESCAPE",
604
+ message: msg,
605
+ });
606
+ return { errors };
607
+ }
608
+ try {
609
+ if (!(await fs.stat(domainIndexPath)).isFile()) {
610
+ const msg = `Missing index.md in domain directory ${toPosixPath(path.relative(resolvedRoot, domainDirPath))}`;
611
+ if (options.strict) {
612
+ throw new Error(msg);
613
+ }
614
+ errors.push({
615
+ relativePath: domainRelPath,
616
+ filePath: domainIndexPath,
617
+ entityId: folderDomainId,
618
+ code: "MISSING_DOMAIN_INDEX",
619
+ message: msg,
620
+ });
621
+ return { errors };
622
+ }
623
+ }
624
+ catch {
625
+ const msg = `Missing index.md in domain directory ${toPosixPath(path.relative(resolvedRoot, domainDirPath))}`;
626
+ if (options.strict) {
627
+ throw new Error(msg);
628
+ }
629
+ errors.push({
630
+ relativePath: domainRelPath,
631
+ filePath: domainIndexPath,
632
+ entityId: folderDomainId,
633
+ code: "MISSING_DOMAIN_INDEX",
634
+ message: msg,
635
+ });
636
+ return { errors };
637
+ }
638
+ }
639
+ else if (!domainIndexEntry.isFile()) {
640
+ const msg = `Missing index.md in domain directory ${toPosixPath(path.relative(resolvedRoot, domainDirPath))}`;
434
641
  if (options.strict) {
435
642
  throw new Error(msg);
436
643
  }
437
- parseErrors.push({
644
+ errors.push({
438
645
  relativePath: domainRelPath,
439
646
  filePath: domainIndexPath,
440
647
  entityId: folderDomainId,
441
- code: "UNSAFE_SYMLINK_ESCAPE",
648
+ code: "MISSING_DOMAIN_INDEX",
442
649
  message: msg,
443
650
  });
444
- continue;
651
+ return { errors };
445
652
  }
446
653
  const rawDomain = await fs.readFile(domainIndexPath, "utf8");
447
654
  let domainMatter;
@@ -453,14 +660,14 @@ export async function loadWiki(rootDir, options = {}) {
453
660
  if (options.strict) {
454
661
  throw new Error(`Failed to parse frontmatter in ${domainRelPath}: ${detail}`);
455
662
  }
456
- parseErrors.push({
663
+ errors.push({
457
664
  relativePath: domainRelPath,
458
665
  filePath: domainIndexPath,
459
666
  entityId: folderDomainId,
460
667
  code: "FRONTMATTER_PARSE_ERROR",
461
668
  message: `Failed to parse frontmatter in ${domainRelPath}: ${detail}`,
462
669
  });
463
- continue;
670
+ return { errors };
464
671
  }
465
672
  const domainValidation = DomainFrontmatterSchema.safeParse(domainMatter.data);
466
673
  if (!domainValidation.success) {
@@ -470,7 +677,7 @@ export async function loadWiki(rootDir, options = {}) {
470
677
  if (options.strict) {
471
678
  throw new Error(`Invalid frontmatter in ${domainRelPath}: ${msg}`);
472
679
  }
473
- parseErrors.push({
680
+ errors.push({
474
681
  relativePath: domainRelPath,
475
682
  filePath: domainIndexPath,
476
683
  entityId: folderDomainId,
@@ -478,14 +685,14 @@ export async function loadWiki(rootDir, options = {}) {
478
685
  code: "INVALID_DOMAIN_FRONTMATTER",
479
686
  message: msg,
480
687
  });
481
- continue;
688
+ return { errors };
482
689
  }
483
690
  if (domainValidation.data.domainId !== folderDomainId) {
484
691
  const msg = `Frontmatter domainId "${domainValidation.data.domainId}" does not match folder name "${folderDomainId}"`;
485
692
  if (options.strict) {
486
693
  throw new Error(`${domainRelPath}: ${msg}`);
487
694
  }
488
- parseErrors.push({
695
+ errors.push({
489
696
  relativePath: domainRelPath,
490
697
  filePath: domainIndexPath,
491
698
  entityId: folderDomainId,
@@ -494,17 +701,59 @@ export async function loadWiki(rootDir, options = {}) {
494
701
  message: msg,
495
702
  });
496
703
  }
497
- domains.set(folderDomainId, {
498
- domainId: folderDomainId,
499
- relativePath: domainRelPath,
500
- filePath: domainIndexPath,
501
- frontmatter: domainValidation.data,
502
- content: domainMatter.content,
503
- raw: rawDomain,
504
- headings: extractMarkdownHeadings(domainMatter.content).map((h) => h.text),
505
- isInfrastructureDomain: infraSet.has(folderDomainId) || infraSet.has(domainValidation.data.domainId),
506
- sceneIds: domainSceneIds,
507
- });
704
+ return {
705
+ domainDoc: {
706
+ domainId: folderDomainId,
707
+ relativePath: domainRelPath,
708
+ filePath: domainIndexPath,
709
+ frontmatter: domainValidation.data,
710
+ content: domainMatter.content,
711
+ raw: rawDomain,
712
+ headings: extractMarkdownHeadings(domainMatter.content).map((h) => h.text),
713
+ isInfrastructureDomain: infraSet.has(folderDomainId) || infraSet.has(domainValidation.data.domainId),
714
+ },
715
+ errors,
716
+ };
717
+ });
718
+ // Phase 4: Reassemble scenes, domains, and parseErrors in 100% deterministic lexicographical order
719
+ const scenesByDomainIdx = new Map();
720
+ for (const res of loadedSceneResults) {
721
+ const bucket = scenesByDomainIdx.get(res.domainIndex);
722
+ if (bucket) {
723
+ bucket.push(res);
724
+ }
725
+ else {
726
+ scenesByDomainIdx.set(res.domainIndex, [res]);
727
+ }
728
+ }
729
+ for (let dIdx = 0; dIdx < scannedDomains.length; dIdx++) {
730
+ const dom = scannedDomains[dIdx];
731
+ if (dom.dirErrors.length > 0) {
732
+ parseErrors.push(...dom.dirErrors);
733
+ }
734
+ if (dom.skipped) {
735
+ continue;
736
+ }
737
+ const domainSceneIds = [];
738
+ for (const sceneRes of scenesByDomainIdx.get(dIdx) ?? []) {
739
+ if (sceneRes.errors.length > 0) {
740
+ parseErrors.push(...sceneRes.errors);
741
+ }
742
+ if (sceneRes.sceneDoc) {
743
+ scenes.set(sceneRes.canonicalSceneId, sceneRes.sceneDoc);
744
+ domainSceneIds.push(sceneRes.canonicalSceneId);
745
+ }
746
+ }
747
+ const domIndexRes = loadedDomainIndexResults[dIdx];
748
+ if (domIndexRes.errors.length > 0) {
749
+ parseErrors.push(...domIndexRes.errors);
750
+ }
751
+ if (domIndexRes.domainDoc) {
752
+ domains.set(dom.folderDomainId, {
753
+ ...domIndexRes.domainDoc,
754
+ sceneIds: domainSceneIds,
755
+ });
756
+ }
508
757
  }
509
758
  const sortedLoadedScenes = Array.from(scenes.values()).sort((a, b) => a.id.localeCompare(b.id));
510
759
  for (const scene of sortedLoadedScenes) {