open-livex-wiki 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.
@@ -0,0 +1,692 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { AnchorSchema, computeFileSha256, DomainFrontmatterSchema, extractDesignatorMentions, isSafeContainedRelativePath, KEBAB_CASE_REGEX, loadWiki, SceneFrontmatterSchema, stringifySafeYaml, toPosixPath, } from "@open-livex-wiki/core";
4
+ import pc from "picocolors";
5
+ import { writeErrorLine, writeJson, writeLine } from "../io.js";
6
+ import { assertTargetWithinRoot, computeWikiRelativeOrAbsPosixPath, readWikiConfigFile, splitCsvList, writeFileAtomic, writeWikiConfigFile, } from "../repo-utils.js";
7
+ import { formatPageRangeLabel } from "./discover.js";
8
+ export const DEFAULT_INGEST_CONFIDENCE = 0.85;
9
+ class IngestError extends Error {
10
+ }
11
+ function fail(ctx, json, msg) {
12
+ if (json) {
13
+ writeJson(ctx.io, { ok: false, error: msg });
14
+ }
15
+ else {
16
+ writeErrorLine(ctx.io, pc.red(`Error: ${msg}`));
17
+ }
18
+ ctx.exitCode = 1;
19
+ return undefined;
20
+ }
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function optString(obj, key, where) {
25
+ const v = obj[key];
26
+ if (v === undefined || v === null) {
27
+ return undefined;
28
+ }
29
+ if (typeof v !== "string") {
30
+ throw new IngestError(`${where}.${key} must be a string`);
31
+ }
32
+ const trimmed = v.trim();
33
+ return trimmed.length > 0 ? trimmed : undefined;
34
+ }
35
+ function optPageRange(obj, key, where) {
36
+ const v = obj[key];
37
+ if (v === undefined || v === null) {
38
+ return undefined;
39
+ }
40
+ if (!Array.isArray(v) ||
41
+ v.length !== 2 ||
42
+ !v.every((n) => Number.isInteger(n) && n > 0) ||
43
+ v[0] > v[1]) {
44
+ throw new IngestError(`${where}.${key} must be [start, end] positive integers with start <= end`);
45
+ }
46
+ return [v[0], v[1]];
47
+ }
48
+ /** Parses and structurally validates an ingest manifest / bookmark outline JSON document. */
49
+ export function parseIngestManifest(raw) {
50
+ const root = Array.isArray(raw)
51
+ ? { documents: raw }
52
+ : isRecord(raw)
53
+ ? raw
54
+ : {};
55
+ if (!Array.isArray(root.documents)) {
56
+ throw new IngestError('Manifest must be an object with a "documents" array (or a top-level array of documents)');
57
+ }
58
+ const documents = root.documents.map((rawDoc, di) => {
59
+ const where = `documents[${di}]`;
60
+ if (!isRecord(rawDoc)) {
61
+ throw new IngestError(`${where} must be an object`);
62
+ }
63
+ const file = optString(rawDoc, "file", where);
64
+ if (!file) {
65
+ throw new IngestError(`${where}.file is required`);
66
+ }
67
+ const aliasesRaw = rawDoc.aliases;
68
+ if (aliasesRaw !== undefined &&
69
+ (!Array.isArray(aliasesRaw) || !aliasesRaw.every((a) => typeof a === "string"))) {
70
+ throw new IngestError(`${where}.aliases must be an array of strings`);
71
+ }
72
+ const pageCountRaw = rawDoc.pageCount;
73
+ if (pageCountRaw !== undefined &&
74
+ (!Number.isInteger(pageCountRaw) || pageCountRaw < 1)) {
75
+ throw new IngestError(`${where}.pageCount must be a positive integer`);
76
+ }
77
+ const sectionsRaw = rawDoc.sections;
78
+ if (sectionsRaw !== undefined && !Array.isArray(sectionsRaw)) {
79
+ throw new IngestError(`${where}.sections must be an array`);
80
+ }
81
+ const sections = (sectionsRaw ?? []).map((rawSec, si) => {
82
+ const sw = `${where}.sections[${si}]`;
83
+ if (!isRecord(rawSec)) {
84
+ throw new IngestError(`${sw} must be an object`);
85
+ }
86
+ const title = optString(rawSec, "title", sw);
87
+ if (!title) {
88
+ throw new IngestError(`${sw}.title is required`);
89
+ }
90
+ const figuresRaw = rawSec.figures;
91
+ if (figuresRaw !== undefined && !Array.isArray(figuresRaw)) {
92
+ throw new IngestError(`${sw}.figures must be an array`);
93
+ }
94
+ const figures = (figuresRaw ?? []).map((rawFig, fi) => {
95
+ const fw = `${sw}.figures[${fi}]`;
96
+ if (!isRecord(rawFig)) {
97
+ throw new IngestError(`${fw} must be an object`);
98
+ }
99
+ const assetId = optString(rawFig, "assetId", fw);
100
+ if (!assetId) {
101
+ throw new IngestError(`${fw}.assetId is required`);
102
+ }
103
+ return {
104
+ assetId,
105
+ ...(optString(rawFig, "handle", fw) ? { handle: optString(rawFig, "handle", fw) } : {}),
106
+ ...(optString(rawFig, "sectionTitle", fw)
107
+ ? { sectionTitle: optString(rawFig, "sectionTitle", fw) }
108
+ : {}),
109
+ ...(optPageRange(rawFig, "pageRange", fw)
110
+ ? { pageRange: optPageRange(rawFig, "pageRange", fw) }
111
+ : {}),
112
+ ...(optString(rawFig, "scopeNote", fw)
113
+ ? { scopeNote: optString(rawFig, "scopeNote", fw) }
114
+ : {}),
115
+ };
116
+ });
117
+ return {
118
+ title,
119
+ ...(optPageRange(rawSec, "pageRange", sw)
120
+ ? { pageRange: optPageRange(rawSec, "pageRange", sw) }
121
+ : {}),
122
+ ...(optString(rawSec, "summary", sw) ? { summary: optString(rawSec, "summary", sw) } : {}),
123
+ ...(figures.length > 0 ? { figures } : {}),
124
+ };
125
+ });
126
+ return {
127
+ file: toPosixPath(file),
128
+ ...(optString(rawDoc, "sceneId", where)
129
+ ? { sceneId: optString(rawDoc, "sceneId", where) }
130
+ : {}),
131
+ ...(optString(rawDoc, "title", where) ? { title: optString(rawDoc, "title", where) } : {}),
132
+ ...(optString(rawDoc, "summary", where)
133
+ ? { summary: optString(rawDoc, "summary", where) }
134
+ : {}),
135
+ ...(aliasesRaw
136
+ ? { aliases: aliasesRaw.map((a) => a.trim()).filter(Boolean) }
137
+ : {}),
138
+ ...(pageCountRaw !== undefined ? { pageCount: pageCountRaw } : {}),
139
+ ...(sections.length > 0 ? { sections } : {}),
140
+ };
141
+ });
142
+ return {
143
+ ...(optString(root, "source", "manifest")
144
+ ? { source: optString(root, "source", "manifest") }
145
+ : {}),
146
+ ...(optString(root, "localPath", "manifest")
147
+ ? { localPath: optString(root, "localPath", "manifest") }
148
+ : {}),
149
+ documents,
150
+ };
151
+ }
152
+ /** Converts arbitrary text into a kebab-case identifier (ASCII only), or "" when nothing remains. */
153
+ export function slugifyKebab(text, maxLen = 60) {
154
+ const slug = text
155
+ .normalize("NFKD")
156
+ .replace(/[\u0300-\u036f]/g, "")
157
+ .toLowerCase()
158
+ .replace(/[^a-z0-9]+/g, "-")
159
+ .replace(/^-+|-+$/g, "");
160
+ return slug.slice(0, maxLen).replace(/-+$/g, "");
161
+ }
162
+ function oneLine(text, maxLen = 300) {
163
+ const collapsed = text.replace(/\s+/g, " ").trim();
164
+ return collapsed.length > maxLen ? `${collapsed.slice(0, maxLen - 1).trimEnd()}…` : collapsed;
165
+ }
166
+ function stripFileExt(file) {
167
+ return path.posix.basename(file).replace(/\.[^.]+$/, "");
168
+ }
169
+ function titleCaseFromId(id) {
170
+ return id
171
+ .split("-")
172
+ .filter(Boolean)
173
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
174
+ .join(" ");
175
+ }
176
+ async function isRegularFile(filePath) {
177
+ try {
178
+ return (await fs.stat(filePath)).isFile();
179
+ }
180
+ catch {
181
+ return false;
182
+ }
183
+ }
184
+ /** Extracts `#` / `##` headings (outside fenced code blocks) from Markdown / plain-text documents. */
185
+ export function extractDocumentOutline(text) {
186
+ const lines = text.split(/\r?\n/);
187
+ let inFence = false;
188
+ let fenceMarker = "";
189
+ let title;
190
+ const sections = [];
191
+ let firstParagraph;
192
+ for (const line of lines) {
193
+ const fence = /^ {0,3}(`{3,}|~{3,})/.exec(line);
194
+ if (fence?.[1]) {
195
+ if (!inFence) {
196
+ inFence = true;
197
+ fenceMarker = fence[1];
198
+ }
199
+ else if (line.trim().startsWith(fenceMarker)) {
200
+ inFence = false;
201
+ }
202
+ continue;
203
+ }
204
+ if (inFence) {
205
+ continue;
206
+ }
207
+ const heading = /^ {0,3}(#{1,2})\s+(.+?)\s*#*\s*$/.exec(line);
208
+ if (heading?.[1] && heading[2]) {
209
+ const headingText = oneLine(heading[2], 200);
210
+ if (!headingText) {
211
+ continue;
212
+ }
213
+ if (heading[1].length === 1 && title === undefined) {
214
+ title = headingText;
215
+ }
216
+ else {
217
+ sections.push(headingText);
218
+ }
219
+ continue;
220
+ }
221
+ const trimmed = line.trim();
222
+ if (firstParagraph === undefined &&
223
+ trimmed &&
224
+ !/^#{1,6}\s/.test(trimmed) &&
225
+ !/^(?:[-*_]\s*){3,}$/.test(trimmed) &&
226
+ !trimmed.startsWith("|") &&
227
+ !trimmed.startsWith("<")) {
228
+ firstParagraph = oneLine(trimmed.replace(/[*_`>]/g, ""), 240);
229
+ }
230
+ }
231
+ return { ...(title ? { title } : {}), sections, ...(firstParagraph ? { firstParagraph } : {}) };
232
+ }
233
+ async function collectTextDocuments(rootDir, excludeDir) {
234
+ const results = [];
235
+ const excludeKey = path.resolve(excludeDir).toLowerCase();
236
+ async function walk(dir) {
237
+ let entries;
238
+ try {
239
+ entries = await fs.readdir(dir, { withFileTypes: true });
240
+ }
241
+ catch {
242
+ return;
243
+ }
244
+ entries.sort((a, b) => a.name.localeCompare(b.name));
245
+ for (const entry of entries) {
246
+ if (entry.name.startsWith(".") || entry.name === "node_modules") {
247
+ continue;
248
+ }
249
+ const abs = path.join(dir, entry.name);
250
+ if (entry.isDirectory()) {
251
+ // Never ingest the wiki repository itself when it lives inside the corpus directory
252
+ if (path.resolve(abs).toLowerCase() === excludeKey) {
253
+ continue;
254
+ }
255
+ await walk(abs);
256
+ }
257
+ else if (entry.isFile() && /\.(?:md|markdown|txt)$/i.test(entry.name)) {
258
+ results.push(toPosixPath(path.relative(rootDir, abs)));
259
+ }
260
+ }
261
+ }
262
+ await walk(rootDir);
263
+ return results;
264
+ }
265
+ function buildSceneMarkdown(options) {
266
+ const { doc, title, summary, source, sha256, modeLabel } = options;
267
+ const today = new Date().toISOString().slice(0, 10);
268
+ const shaShort = sha256 ? sha256.slice(0, 12) : undefined;
269
+ const baseline = shaShort
270
+ ? `\`${source}:${doc.file}@sha256:${shaShort}\``
271
+ : `\`${source}:${doc.file}\``;
272
+ const lines = [
273
+ `# ${oneLine(title, 200)}`,
274
+ "",
275
+ "## 1. Business Background",
276
+ "",
277
+ oneLine(summary, 600),
278
+ "",
279
+ `- **Corpus Source**: \`${source}\` → \`${doc.file}\`${shaShort ? ` (sha256 \`${shaShort}…\`)` : ""}${doc.pageCount ? ` | ${doc.pageCount} pages` : ""}`,
280
+ `- **Ingestion**: Generated by \`olw ingest-docs\` from a ${modeLabel}; chain entries mirror the document outline and cite deterministic section/figure anchors.`,
281
+ "",
282
+ "## 2. Change History",
283
+ "",
284
+ "| Date | Summary | Source Baseline |",
285
+ "| --- | --- | --- |",
286
+ `| ${today} | Ingested document outline via \`olw ingest-docs\` | ${baseline} |`,
287
+ "",
288
+ "## 3. Chain Details",
289
+ "",
290
+ ];
291
+ const sections = doc.sections ?? [];
292
+ if (sections.length === 0) {
293
+ lines.push(`### Document Overview (${doc.file})`);
294
+ lines.push("");
295
+ lines.push(`- **Location**: \`${doc.file}\`${doc.pageCount ? ` pp.1-${doc.pageCount}` : ""}`);
296
+ lines.push(`- **Summary**: ${oneLine(summary, 600)}`);
297
+ lines.push("");
298
+ }
299
+ else {
300
+ sections.forEach((section, idx) => {
301
+ const pages = formatPageRangeLabel(section.pageRange);
302
+ lines.push(`### Section ${idx + 1}: ${oneLine(section.title, 200)}${pages ? ` (${pages})` : ""}`);
303
+ lines.push("");
304
+ lines.push(`- **Location**: \`${doc.file}\`${pages ? ` ${pages}` : ""}`);
305
+ if (section.summary) {
306
+ lines.push(`- **Summary**: ${oneLine(section.summary, 600)}`);
307
+ }
308
+ for (const fig of section.figures ?? []) {
309
+ const handle = options.sectionHandles.get(fig);
310
+ const figPages = formatPageRangeLabel(fig.pageRange);
311
+ lines.push(`- **Figure**: ${handle ? `[${handle}] ` : ""}\`${fig.assetId}\`${figPages ? ` (${figPages})` : ""}${fig.scopeNote ? ` — scope: ${oneLine(fig.scopeNote, 300)}` : ""}`);
312
+ }
313
+ lines.push("");
314
+ });
315
+ }
316
+ lines.push("## 4. Pending Confirmations");
317
+ lines.push("");
318
+ lines.push("None");
319
+ lines.push("");
320
+ return lines.join("\n");
321
+ }
322
+ /**
323
+ * `olw ingest-docs <inputPath>` — zero-dependency document corpus ingestion.
324
+ * Mode 1: JSON manifest / bookmark outline (`*.json`). Mode 2: directory of `.md` / `.txt` documents.
325
+ */
326
+ export async function runIngestDocsCommand(inputPath, options, ctx) {
327
+ try {
328
+ const result = await ingestDocs(inputPath, options);
329
+ if (options.json) {
330
+ writeJson(ctx.io, result);
331
+ }
332
+ else {
333
+ writeLine(ctx.io, pc.green(`Ingested ${result.scenes.filter((s) => s.status !== "skipped_existing").length}/${result.scenes.length} document(s) into domain "${result.domainId}" (source "${result.source}" -> ${result.sourceLocalPath}, mode=${result.mode})`));
334
+ if (result.sourceRegistered) {
335
+ writeLine(ctx.io, pc.dim(` Registered source "${result.source}" in wiki.config.yaml`));
336
+ }
337
+ if (result.domainCreated) {
338
+ writeLine(ctx.io, pc.dim(` Created domain index for "${result.domainId}"`));
339
+ }
340
+ for (const s of result.scenes) {
341
+ const statusText = s.status === "skipped_existing"
342
+ ? pc.yellow("[skipped: exists]")
343
+ : pc.cyan(`[${s.status}]`);
344
+ writeLine(ctx.io, ` ${statusText} ${pc.bold(s.id)} — ${s.title} ${pc.dim(`(${s.file}${s.sha256 ? ` sha256=${s.sha256.slice(0, 12)}…` : ""}, sections=${s.sectionCount}, figures=${s.figureCount})`)}`);
345
+ }
346
+ for (const w of result.warnings) {
347
+ writeLine(ctx.io, pc.yellow(` WARN: ${w}`));
348
+ }
349
+ writeLine(ctx.io, "");
350
+ writeLine(ctx.io, pc.dim(`Next: olw validate --wiki "${result.wikiDir}" --strict --check-anchors`));
351
+ }
352
+ return result;
353
+ }
354
+ catch (err) {
355
+ return fail(ctx, options.json, err instanceof Error ? err.message : String(err));
356
+ }
357
+ }
358
+ export async function ingestDocs(inputPath, options) {
359
+ const domainId = options.domain?.trim() ?? "";
360
+ if (!KEBAB_CASE_REGEX.test(domainId)) {
361
+ throw new IngestError(`Invalid or missing --domain "${domainId}". Must be lowercase kebab-case (e.g. "defense-reports").`);
362
+ }
363
+ const sourceFlag = options.source?.trim();
364
+ if (sourceFlag !== undefined && !sourceFlag) {
365
+ throw new IngestError("--source must not be empty");
366
+ }
367
+ let confidence = DEFAULT_INGEST_CONFIDENCE;
368
+ if (options.confidence !== undefined) {
369
+ confidence = Number(options.confidence);
370
+ if (Number.isNaN(confidence) || confidence < 0 || confidence > 1) {
371
+ throw new IngestError(`Invalid --confidence "${options.confidence}". Must be between 0 and 1.`);
372
+ }
373
+ }
374
+ const maintainers = splitCsvList(options.maintainers ?? "@wiki-maintainers");
375
+ if (maintainers.length === 0) {
376
+ throw new IngestError("--maintainers must contain at least one handle");
377
+ }
378
+ const wikiDir = path.resolve(options.wiki ?? process.cwd());
379
+ const config = await readWikiConfigFile(wikiDir);
380
+ if ((config.infrastructureDomains ?? []).includes(domainId)) {
381
+ throw new IngestError(`Domain "${domainId}" is an infrastructure domain; ingest-docs writes scene-index/v1 scenes into business domains only.`);
382
+ }
383
+ const resolvedInput = path.resolve(inputPath);
384
+ let inputStat;
385
+ try {
386
+ inputStat = await fs.stat(resolvedInput);
387
+ }
388
+ catch {
389
+ throw new IngestError(`Input path does not exist: ${resolvedInput}`);
390
+ }
391
+ const warnings = [];
392
+ let mode;
393
+ let sourceDir;
394
+ let manifestSource;
395
+ let documents;
396
+ if (inputStat.isFile() && /\.json$/i.test(resolvedInput)) {
397
+ mode = "manifest";
398
+ let parsedJson;
399
+ try {
400
+ parsedJson = JSON.parse((await fs.readFile(resolvedInput, "utf8")).replace(/^\uFEFF/, ""));
401
+ }
402
+ catch (err) {
403
+ throw new IngestError(`Failed to parse manifest JSON "${resolvedInput}": ${err instanceof Error ? err.message : String(err)}`);
404
+ }
405
+ const manifest = parseIngestManifest(parsedJson);
406
+ manifestSource = manifest.source;
407
+ sourceDir = path.resolve(path.dirname(resolvedInput), manifest.localPath ?? ".");
408
+ documents = manifest.documents;
409
+ }
410
+ else if (inputStat.isDirectory()) {
411
+ mode = "directory";
412
+ sourceDir = resolvedInput;
413
+ const files = await collectTextDocuments(sourceDir, wikiDir);
414
+ documents = [];
415
+ for (const file of files) {
416
+ const text = await fs.readFile(path.join(sourceDir, file), "utf8");
417
+ const outline = extractDocumentOutline(text);
418
+ documents.push({
419
+ file,
420
+ title: outline.title ?? stripFileExt(file),
421
+ ...(outline.firstParagraph ? { summary: outline.firstParagraph } : {}),
422
+ ...(outline.sections.length > 0
423
+ ? { sections: outline.sections.map((title) => ({ title })) }
424
+ : {}),
425
+ });
426
+ }
427
+ }
428
+ else {
429
+ throw new IngestError(`Unsupported input "${resolvedInput}": pass a JSON manifest (*.json) or a directory of .md/.txt documents.`);
430
+ }
431
+ if (documents.length === 0) {
432
+ throw new IngestError(`No documents found in "${resolvedInput}".`);
433
+ }
434
+ const source = sourceFlag ?? manifestSource ?? `${domainId}-corpus`;
435
+ const sourceLocalPath = computeWikiRelativeOrAbsPosixPath(wikiDir, sourceDir);
436
+ // Register (or verify) corpus source in wiki.config.yaml
437
+ const existingSource = (config.sources ?? []).find((s) => toPosixPath(s.source.trim()).toLowerCase() === source.toLowerCase());
438
+ let sourceRegistered = false;
439
+ let nextConfig;
440
+ if (!existingSource) {
441
+ nextConfig = {
442
+ ...config,
443
+ sources: [
444
+ ...(config.sources ?? []),
445
+ {
446
+ source,
447
+ localPath: sourceLocalPath,
448
+ description: `Document corpus ingested via olw ingest-docs (${mode})`,
449
+ },
450
+ ],
451
+ };
452
+ sourceRegistered = true;
453
+ }
454
+ else {
455
+ const existingAbs = existingSource.localPath
456
+ ? path.resolve(wikiDir, existingSource.localPath)
457
+ : undefined;
458
+ if (!existingAbs || path.relative(existingAbs, sourceDir) !== "") {
459
+ if (!options.force) {
460
+ throw new IngestError(`Source "${source}" is already registered in wiki.config.yaml with localPath "${existingSource.localPath ?? "(none)"}" which differs from "${sourceLocalPath}". Pass --force to update it or choose another --source.`);
461
+ }
462
+ nextConfig = {
463
+ ...config,
464
+ sources: (config.sources ?? []).map((s) => s === existingSource ? { ...s, localPath: sourceLocalPath } : s),
465
+ };
466
+ warnings.push(`Updated localPath of existing source "${source}" to "${sourceLocalPath}"`);
467
+ }
468
+ }
469
+ // Load existing wiki to avoid alias collisions and sceneId clashes
470
+ const existingWiki = await loadWiki(wikiDir, { strict: false });
471
+ const aliasOwners = new Map();
472
+ for (const scene of existingWiki.scenes.values()) {
473
+ for (const alias of scene.frontmatter.aliases) {
474
+ aliasOwners.set(alias.trim().toLowerCase(), scene.id);
475
+ }
476
+ }
477
+ // Plan scenes (unique sceneIds, sha256, file validation)
478
+ const planned = [];
479
+ const usedSceneIds = new Set();
480
+ for (const [idx, doc] of documents.entries()) {
481
+ if (!isSafeContainedRelativePath(doc.file)) {
482
+ throw new IngestError(`documents[${idx}].file "${doc.file}" must be a relative path contained inside the source directory`);
483
+ }
484
+ let sceneId = doc.sceneId;
485
+ if (sceneId !== undefined && !KEBAB_CASE_REGEX.test(sceneId)) {
486
+ throw new IngestError(`documents[${idx}].sceneId "${sceneId}" must be lowercase kebab-case`);
487
+ }
488
+ if (!sceneId) {
489
+ sceneId =
490
+ slugifyKebab(doc.title ?? "") || slugifyKebab(stripFileExt(doc.file)) || `doc-${idx + 1}`;
491
+ }
492
+ if (usedSceneIds.has(sceneId)) {
493
+ if (doc.sceneId) {
494
+ throw new IngestError(`Duplicate sceneId "${sceneId}" in input`);
495
+ }
496
+ let n = 2;
497
+ while (usedSceneIds.has(`${sceneId}-${n}`)) {
498
+ n += 1;
499
+ }
500
+ sceneId = `${sceneId}-${n}`;
501
+ }
502
+ usedSceneIds.add(sceneId);
503
+ const absFile = path.resolve(sourceDir, doc.file);
504
+ let sha256;
505
+ if (await isRegularFile(absFile)) {
506
+ sha256 = await computeFileSha256(absFile);
507
+ }
508
+ else {
509
+ warnings.push(`Document file "${doc.file}" not found under "${sourceLocalPath}"; sha256 omitted (olw validate --check-anchors will report it)`);
510
+ }
511
+ planned.push({ doc, sceneId, ...(sha256 ? { sha256 } : {}) });
512
+ }
513
+ const domainsDir = config.domainsDir || "domains";
514
+ // Create domain index if missing
515
+ const domainIndexPath = path.resolve(wikiDir, domainsDir, domainId, "index.md");
516
+ assertTargetWithinRoot(wikiDir, domainIndexPath);
517
+ let domainCreated = false;
518
+ if (!(await isRegularFile(domainIndexPath))) {
519
+ const domainTitle = titleCaseFromId(domainId);
520
+ const domainFm = DomainFrontmatterSchema.parse({
521
+ schema: "domain-index/v1",
522
+ domainId,
523
+ title: domainTitle,
524
+ aliases: [],
525
+ summary: `Document-corpus knowledge for ${domainTitle}, ingested from source "${source}".`,
526
+ maintainers,
527
+ });
528
+ const domainBody = [
529
+ "---",
530
+ stringifySafeYaml(domainFm).trimEnd(),
531
+ "---",
532
+ "",
533
+ `# ${domainTitle}`,
534
+ "",
535
+ "## Domain Identity & Boundaries",
536
+ "",
537
+ `- **In Scope**: Documents from corpus source \`${source}\` ingested via \`olw ingest-docs\`, one scene per document with section/figure anchors.`,
538
+ "- **Out of Scope**: Source-code scenes and shared infrastructure (owned by their own domains).",
539
+ "",
540
+ ].join("\n");
541
+ await writeFileAtomic(domainIndexPath, domainBody, wikiDir);
542
+ domainCreated = true;
543
+ }
544
+ const modeLabel = mode === "manifest" ? "JSON bookmark-outline manifest" : "Markdown/text heading scan";
545
+ const sceneResults = [];
546
+ for (const plan of planned) {
547
+ const { doc, sceneId, sha256 } = plan;
548
+ const id = `${domainId}/${sceneId}`;
549
+ const targetPath = path.resolve(wikiDir, domainsDir, domainId, sceneId, "index.md");
550
+ assertTargetWithinRoot(wikiDir, targetPath);
551
+ const relativePath = toPosixPath(path.relative(wikiDir, targetPath));
552
+ const title = doc.title ?? stripFileExt(doc.file);
553
+ const sections = doc.sections ?? [];
554
+ const figureCount = sections.reduce((n, s) => n + (s.figures?.length ?? 0), 0);
555
+ const exists = await isRegularFile(targetPath);
556
+ const existingOwnedId = existingWiki.scenes.has(id) ? id : undefined;
557
+ if (exists && !options.force) {
558
+ warnings.push(`Scene "${id}" already exists at "${relativePath}"; pass --force to overwrite`);
559
+ sceneResults.push({
560
+ id,
561
+ relativePath,
562
+ title,
563
+ file: doc.file,
564
+ ...(sha256 ? { sha256 } : {}),
565
+ sectionCount: sections.length,
566
+ figureCount,
567
+ aliases: existingWiki.scenes.get(id)?.frontmatter.aliases ?? [],
568
+ status: "skipped_existing",
569
+ });
570
+ continue;
571
+ }
572
+ // Aliases: explicit + designator mentions from title / filename / summary (deduped, collision-free)
573
+ const candidateAliases = [
574
+ ...(doc.aliases ?? []),
575
+ ...extractDesignatorMentions([title, stripFileExt(doc.file), doc.summary ?? ""].join(" ")).map((m) => m.raw),
576
+ ];
577
+ const aliases = [];
578
+ const seenAliasKeys = new Set();
579
+ for (const raw of candidateAliases) {
580
+ const alias = oneLine(raw, 120);
581
+ const key = alias.toLowerCase();
582
+ if (!alias || seenAliasKeys.has(key)) {
583
+ continue;
584
+ }
585
+ const owner = aliasOwners.get(key);
586
+ if (owner && owner !== existingOwnedId && owner !== id) {
587
+ warnings.push(`Alias "${alias}" on "${id}" skipped: already owned by "${owner}"`);
588
+ continue;
589
+ }
590
+ seenAliasKeys.add(key);
591
+ aliases.push(alias);
592
+ }
593
+ for (const alias of aliases) {
594
+ aliasOwners.set(alias.toLowerCase(), id);
595
+ }
596
+ const summary = doc.summary ??
597
+ `Outline of "${oneLine(title, 160)}" (${doc.file}${doc.pageCount ? `, ${doc.pageCount} pages` : ""}) from corpus source "${source}".`;
598
+ const sourceRef = {
599
+ source,
600
+ path: doc.file,
601
+ ...(sha256 ? { sha256 } : {}),
602
+ ...(doc.pageCount ? { pageCount: doc.pageCount } : {}),
603
+ };
604
+ const anchors = [
605
+ {
606
+ source,
607
+ file: doc.file,
608
+ kind: "document",
609
+ ...(doc.pageCount ? { pageRange: [1, doc.pageCount] } : {}),
610
+ },
611
+ ];
612
+ const figureHandles = new Map();
613
+ for (const section of sections) {
614
+ anchors.push({
615
+ source,
616
+ file: doc.file,
617
+ kind: "section",
618
+ sectionTitle: oneLine(section.title, 200),
619
+ ...(section.pageRange ? { pageRange: section.pageRange } : {}),
620
+ });
621
+ for (const fig of section.figures ?? []) {
622
+ figureHandles.set(fig, fig.handle);
623
+ anchors.push({
624
+ source,
625
+ file: doc.file,
626
+ kind: "figure",
627
+ assetId: fig.assetId,
628
+ sectionTitle: oneLine(fig.sectionTitle ?? section.title, 200),
629
+ ...(fig.handle ? { handle: fig.handle } : {}),
630
+ ...(fig.pageRange ? { pageRange: fig.pageRange } : {}),
631
+ ...(fig.scopeNote ? { scopeNote: oneLine(fig.scopeNote, 400) } : {}),
632
+ });
633
+ }
634
+ }
635
+ for (const [ai, anchor] of anchors.entries()) {
636
+ const check = AnchorSchema.safeParse(anchor);
637
+ if (!check.success) {
638
+ throw new IngestError(`Invalid anchor #${ai + 1} for "${id}": ${check.error.issues.map((i) => i.message).join("; ")}`);
639
+ }
640
+ }
641
+ const frontmatter = SceneFrontmatterSchema.parse({
642
+ schema: "scene-index/v1",
643
+ sceneId,
644
+ title: oneLine(title, 200),
645
+ aliases,
646
+ summary: oneLine(summary, 600),
647
+ maintainers,
648
+ confidence,
649
+ dependsOn: [],
650
+ repositories: [],
651
+ sources: [sourceRef],
652
+ anchors,
653
+ });
654
+ const body = buildSceneMarkdown({
655
+ doc,
656
+ title,
657
+ summary,
658
+ source,
659
+ ...(sha256 ? { sha256 } : {}),
660
+ modeLabel,
661
+ sectionHandles: figureHandles,
662
+ });
663
+ await writeFileAtomic(targetPath, ["---", stringifySafeYaml(frontmatter).trimEnd(), "---", "", body].join("\n"), wikiDir);
664
+ sceneResults.push({
665
+ id,
666
+ relativePath,
667
+ title: frontmatter.title,
668
+ file: doc.file,
669
+ ...(sha256 ? { sha256 } : {}),
670
+ sectionCount: sections.length,
671
+ figureCount,
672
+ aliases,
673
+ status: exists ? "overwritten" : "created",
674
+ });
675
+ }
676
+ if (nextConfig) {
677
+ await writeWikiConfigFile(wikiDir, nextConfig);
678
+ }
679
+ return {
680
+ ok: true,
681
+ mode,
682
+ wikiDir: toPosixPath(wikiDir),
683
+ domainId,
684
+ source,
685
+ sourceLocalPath,
686
+ sourceRegistered,
687
+ domainCreated,
688
+ scenes: sceneResults,
689
+ warnings,
690
+ };
691
+ }
692
+ //# sourceMappingURL=ingest-docs.js.map