open-livex-wiki 0.2.1 → 0.2.3

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/commands/coverage.d.ts +1 -0
  2. package/dist/commands/coverage.d.ts.map +1 -1
  3. package/dist/commands/coverage.js +5 -1
  4. package/dist/commands/coverage.js.map +1 -1
  5. package/dist/commands/discover.d.ts +2 -0
  6. package/dist/commands/discover.d.ts.map +1 -1
  7. package/dist/commands/discover.js +7 -0
  8. package/dist/commands/discover.js.map +1 -1
  9. package/dist/commands/ingest-docs/documents.d.ts +25 -0
  10. package/dist/commands/ingest-docs/documents.d.ts.map +1 -0
  11. package/dist/commands/ingest-docs/documents.js +183 -0
  12. package/dist/commands/ingest-docs/documents.js.map +1 -0
  13. package/dist/commands/ingest-docs/manifest.d.ts +41 -0
  14. package/dist/commands/ingest-docs/manifest.d.ts.map +1 -0
  15. package/dist/commands/ingest-docs/manifest.js +143 -0
  16. package/dist/commands/ingest-docs/manifest.js.map +1 -0
  17. package/dist/commands/ingest-docs.d.ts +6 -37
  18. package/dist/commands/ingest-docs.d.ts.map +1 -1
  19. package/dist/commands/ingest-docs.js +81 -312
  20. package/dist/commands/ingest-docs.js.map +1 -1
  21. package/dist/commands/init/skill-templates.d.ts +2 -0
  22. package/dist/commands/init/skill-templates.d.ts.map +1 -0
  23. package/dist/commands/init/skill-templates.js +266 -0
  24. package/dist/commands/init/skill-templates.js.map +1 -0
  25. package/dist/commands/init/templates.d.ts +7 -0
  26. package/dist/commands/init/templates.d.ts.map +1 -0
  27. package/dist/commands/init/templates.js +268 -0
  28. package/dist/commands/init/templates.js.map +1 -0
  29. package/dist/commands/init/workflow-templates.d.ts +2 -0
  30. package/dist/commands/init/workflow-templates.d.ts.map +1 -0
  31. package/dist/commands/init/workflow-templates.js +273 -0
  32. package/dist/commands/init/workflow-templates.js.map +1 -0
  33. package/dist/commands/init.d.ts +1 -5
  34. package/dist/commands/init.d.ts.map +1 -1
  35. package/dist/commands/init.js +2 -791
  36. package/dist/commands/init.js.map +1 -1
  37. package/dist/commands/schema.js +2 -2
  38. package/dist/commands/schema.js.map +1 -1
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +7 -2
  42. package/dist/index.js.map +1 -1
  43. package/dist/templates/starter-bundle.json +3 -3
  44. package/dist/templates/wiki-starter/.agents/skills/wiki-bootstrap/SKILL.md +15 -14
  45. package/dist/templates/wiki-starter/.agents/skills/wiki-consume/SKILL.md +2 -2
  46. package/dist/templates/wiki-starter/AGENTS.md +3 -3
  47. package/package.json +5 -5
@@ -1,4 +1,6 @@
1
1
  import { type CliContext } from "../io.js";
2
+ export { extractDocumentOutline, slugifyKebab } from "./ingest-docs/documents.js";
3
+ export { type IngestManifest, type IngestManifestDocument, type IngestManifestFigure, type IngestManifestSection, parseIngestManifest, } from "./ingest-docs/manifest.js";
2
4
  export interface IngestDocsCommandOptions {
3
5
  wiki?: string;
4
6
  domain?: string;
@@ -6,35 +8,10 @@ export interface IngestDocsCommandOptions {
6
8
  maintainers?: string;
7
9
  confidence?: string;
8
10
  force?: boolean;
11
+ linkRefs?: boolean;
12
+ refScope?: string;
9
13
  json?: boolean;
10
14
  }
11
- export interface IngestManifestFigure {
12
- handle?: string;
13
- assetId: string;
14
- sectionTitle?: string;
15
- pageRange?: [number, number];
16
- scopeNote?: string;
17
- }
18
- export interface IngestManifestSection {
19
- title: string;
20
- pageRange?: [number, number];
21
- summary?: string;
22
- figures?: IngestManifestFigure[];
23
- }
24
- export interface IngestManifestDocument {
25
- file: string;
26
- sceneId?: string;
27
- title?: string;
28
- summary?: string;
29
- aliases?: string[];
30
- pageCount?: number;
31
- sections?: IngestManifestSection[];
32
- }
33
- export interface IngestManifest {
34
- source?: string;
35
- localPath?: string;
36
- documents: IngestManifestDocument[];
37
- }
38
15
  export interface IngestedSceneResult {
39
16
  id: string;
40
17
  relativePath: string;
@@ -56,19 +33,11 @@ export interface IngestDocsResult {
56
33
  sourceRegistered: boolean;
57
34
  domainCreated: boolean;
58
35
  scenes: IngestedSceneResult[];
36
+ linkedEdgeCount: number;
37
+ ambiguousReferenceCodes: string[];
59
38
  warnings: string[];
60
39
  }
61
40
  export declare const DEFAULT_INGEST_CONFIDENCE = 0.85;
62
- /** Parses and structurally validates an ingest manifest / bookmark outline JSON document. */
63
- export declare function parseIngestManifest(raw: unknown): IngestManifest;
64
- /** Converts arbitrary text into a kebab-case identifier (ASCII only), or "" when nothing remains. */
65
- export declare function slugifyKebab(text: string, maxLen?: number): string;
66
- /** Extracts `#` / `##` headings (outside fenced code blocks) from Markdown / plain-text documents. */
67
- export declare function extractDocumentOutline(text: string): {
68
- title?: string;
69
- sections: string[];
70
- firstParagraph?: string;
71
- };
72
41
  /**
73
42
  * `olw ingest-docs <inputPath>` — zero-dependency document corpus ingestion.
74
43
  * Mode 1: JSON manifest / bookmark outline (`*.json`). Mode 2: directory of `.md` / `.txt` documents.
@@ -1 +1 @@
1
- {"version":3,"file":"ingest-docs.d.ts","sourceRoot":"","sources":["../../src/commands/ingest-docs.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAE,KAAK,UAAU,EAAwC,MAAM,UAAU,CAAC;AAWjF,MAAM,WAAW,wBAAwB;IACvC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,oBAAoB;IACnC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CA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,GACd,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAiDvC;AAED,wBAAsB,UAAU,CAC9B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,gBAAgB,CAAC,CAkc3B"}
@@ -1,13 +1,14 @@
1
1
  import fs from "node:fs/promises";
2
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";
3
+ import { AnchorSchema, computeCrossSceneReferenceLinks, extractReferenceCodes, computeFileSha256, DomainFrontmatterSchema, extractDesignatorMentions, isSafeContainedRelativePath, KEBAB_CASE_REGEX, loadWiki, SceneFrontmatterSchema, stringifySafeYaml, toPosixPath, } from "@open-livex-wiki/core";
4
4
  import pc from "picocolors";
5
5
  import { writeErrorLine, writeJson, writeLine } from "../io.js";
6
6
  import { assertTargetWithinRoot, computeWikiRelativeOrAbsPosixPath, readWikiConfigFile, splitCsvList, writeFileAtomic, writeWikiConfigFile, } from "../repo-utils.js";
7
- import { formatPageRangeLabel } from "./discover.js";
7
+ import { buildSceneMarkdown, collectTextDocuments, extractDocumentOutline, isRegularFile, oneLine, slugifyKebab, stripFileExt, titleCaseFromId, } from "./ingest-docs/documents.js";
8
+ import { IngestError, sectionAssets, parseIngestManifest, } from "./ingest-docs/manifest.js";
9
+ export { extractDocumentOutline, slugifyKebab } from "./ingest-docs/documents.js";
10
+ export { parseIngestManifest, } from "./ingest-docs/manifest.js";
8
11
  export const DEFAULT_INGEST_CONFIDENCE = 0.85;
9
- class IngestError extends Error {
10
- }
11
12
  function fail(ctx, json, msg) {
12
13
  if (json) {
13
14
  writeJson(ctx.io, { ok: false, error: msg });
@@ -18,307 +19,6 @@ function fail(ctx, json, msg) {
18
19
  ctx.exitCode = 1;
19
20
  return undefined;
20
21
  }
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
22
  /**
323
23
  * `olw ingest-docs <inputPath>` — zero-dependency document corpus ingestion.
324
24
  * Mode 1: JSON manifest / bookmark outline (`*.json`). Mode 2: directory of `.md` / `.txt` documents.
@@ -343,6 +43,9 @@ export async function runIngestDocsCommand(inputPath, options, ctx) {
343
43
  : pc.cyan(`[${s.status}]`);
344
44
  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
45
  }
46
+ if (result.linkedEdgeCount || result.ambiguousReferenceCodes.length) {
47
+ writeLine(ctx.io, ` Linked ${result.linkedEdgeCount} reference edge(s)${result.ambiguousReferenceCodes.length ? `; ambiguous codes: ${result.ambiguousReferenceCodes.join(", ")}` : ""}`);
48
+ }
346
49
  for (const w of result.warnings) {
347
50
  writeLine(ctx.io, pc.yellow(` WARN: ${w}`));
348
51
  }
@@ -356,6 +59,9 @@ export async function runIngestDocsCommand(inputPath, options, ctx) {
356
59
  }
357
60
  }
358
61
  export async function ingestDocs(inputPath, options) {
62
+ const refScope = options.refScope ?? "auto";
63
+ if (refScope !== "auto" && refScope !== "series-year" && refScope !== "global")
64
+ throw new IngestError("Invalid --ref-scope. Expected auto, series-year, or global.");
359
65
  const domainId = options.domain?.trim() ?? "";
360
66
  if (!KEBAB_CASE_REGEX.test(domainId)) {
361
67
  throw new IngestError(`Invalid or missing --domain "${domainId}". Must be lowercase kebab-case (e.g. "defense-reports").`);
@@ -392,6 +98,7 @@ export async function ingestDocs(inputPath, options) {
392
98
  let mode;
393
99
  let sourceDir;
394
100
  let manifestSource;
101
+ const sourceCodes = new Map();
395
102
  let documents;
396
103
  if (inputStat.isFile() && /\.json$/i.test(resolvedInput)) {
397
104
  mode = "manifest";
@@ -414,6 +121,8 @@ export async function ingestDocs(inputPath, options) {
414
121
  documents = [];
415
122
  for (const file of files) {
416
123
  const text = await fs.readFile(path.join(sourceDir, file), "utf8");
124
+ if (options.linkRefs !== false)
125
+ sourceCodes.set(file, extractReferenceCodes(text));
417
126
  const outline = extractDocumentOutline(text);
418
127
  documents.push({
419
128
  file,
@@ -504,6 +213,14 @@ export async function ingestDocs(inputPath, options) {
504
213
  let sha256;
505
214
  if (await isRegularFile(absFile)) {
506
215
  sha256 = await computeFileSha256(absFile);
216
+ if (mode === "manifest" &&
217
+ options.linkRefs !== false &&
218
+ /\.(?:md|markdown|txt|csv)$/i.test(doc.file) &&
219
+ !sourceCodes.has(doc.file) &&
220
+ (await fs.stat(absFile)).size <= 4_000_000) {
221
+ const text = await fs.readFile(absFile, "utf8");
222
+ sourceCodes.set(doc.file, extractReferenceCodes(text));
223
+ }
507
224
  }
508
225
  else {
509
226
  warnings.push(`Document file "${doc.file}" not found under "${sourceLocalPath}"; sha256 omitted (olw validate --check-anchors will report it)`);
@@ -543,6 +260,8 @@ export async function ingestDocs(inputPath, options) {
543
260
  }
544
261
  const modeLabel = mode === "manifest" ? "JSON bookmark-outline manifest" : "Markdown/text heading scan";
545
262
  const sceneResults = [];
263
+ const pending = new Map();
264
+ const candidates = [];
546
265
  for (const plan of planned) {
547
266
  const { doc, sceneId, sha256 } = plan;
548
267
  const id = `${domainId}/${sceneId}`;
@@ -609,7 +328,6 @@ export async function ingestDocs(inputPath, options) {
609
328
  ...(doc.pageCount ? { pageRange: [1, doc.pageCount] } : {}),
610
329
  },
611
330
  ];
612
- const figureHandles = new Map();
613
331
  for (const section of sections) {
614
332
  anchors.push({
615
333
  source,
@@ -618,12 +336,12 @@ export async function ingestDocs(inputPath, options) {
618
336
  sectionTitle: oneLine(section.title, 200),
619
337
  ...(section.pageRange ? { pageRange: section.pageRange } : {}),
620
338
  });
621
- for (const fig of section.figures ?? []) {
622
- figureHandles.set(fig, fig.handle);
339
+ for (const { kind, asset: fig } of sectionAssets(section)) {
623
340
  anchors.push({
624
341
  source,
625
342
  file: doc.file,
626
- kind: "figure",
343
+ kind,
344
+ ...(fig.caption ? { caption: fig.caption } : {}),
627
345
  assetId: fig.assetId,
628
346
  sectionTitle: oneLine(fig.sectionTitle ?? section.title, 200),
629
347
  ...(fig.handle ? { handle: fig.handle } : {}),
@@ -646,7 +364,7 @@ export async function ingestDocs(inputPath, options) {
646
364
  summary: oneLine(summary, 600),
647
365
  maintainers,
648
366
  confidence,
649
- dependsOn: [],
367
+ dependsOn: existingWiki.scenes.get(id)?.frontmatter.dependsOn ?? [],
650
368
  repositories: [],
651
369
  sources: [sourceRef],
652
370
  anchors,
@@ -658,9 +376,20 @@ export async function ingestDocs(inputPath, options) {
658
376
  source,
659
377
  ...(sha256 ? { sha256 } : {}),
660
378
  modeLabel,
661
- sectionHandles: figureHandles,
379
+ referenceCodes: sourceCodes.get(doc.file),
662
380
  });
663
- await writeFileAtomic(targetPath, ["---", stringifySafeYaml(frontmatter).trimEnd(), "---", "", body].join("\n"), wikiDir);
381
+ if (options.linkRefs !== false) {
382
+ candidates.push({
383
+ id,
384
+ domainId,
385
+ text: [title, summary, body].join("\n"),
386
+ source,
387
+ file: doc.file,
388
+ title,
389
+ existingDependsOn: frontmatter.dependsOn,
390
+ });
391
+ }
392
+ pending.set(id, { targetPath, frontmatter, body });
664
393
  sceneResults.push({
665
394
  id,
666
395
  relativePath,
@@ -673,6 +402,44 @@ export async function ingestDocs(inputPath, options) {
673
402
  status: exists ? "overwritten" : "created",
674
403
  });
675
404
  }
405
+ let linkedEdgeCount = 0;
406
+ let ambiguousReferenceCodes = [];
407
+ if (options.linkRefs !== false) {
408
+ for (const scene of existingWiki.scenes.values()) {
409
+ if (pending.has(scene.id))
410
+ continue;
411
+ const meta = scene.frontmatter;
412
+ const sourceRef = meta.sources?.[0];
413
+ const document = meta.anchors?.find((anchor) => anchor.kind === "document");
414
+ candidates.push({
415
+ id: scene.id,
416
+ domainId: scene.domainId,
417
+ source: sourceRef?.source ?? document?.source,
418
+ file: sourceRef?.path ?? document?.file,
419
+ title: meta.title,
420
+ text: [
421
+ meta.title,
422
+ meta.summary,
423
+ scene.content,
424
+ ...scene.details.map((detail) => detail.content),
425
+ ].join("\n"),
426
+ existingDependsOn: meta.dependsOn,
427
+ });
428
+ }
429
+ const links = computeCrossSceneReferenceLinks(candidates, {
430
+ scopeMode: refScope,
431
+ mutableSceneIds: new Set(pending.keys()),
432
+ });
433
+ linkedEdgeCount = links.edgeCount;
434
+ ambiguousReferenceCodes = links.ambiguousCodes;
435
+ for (const [id, additions] of links.dependsOnByScene) {
436
+ const { frontmatter } = pending.get(id);
437
+ frontmatter.dependsOn = [...new Set([...frontmatter.dependsOn, ...additions])].sort();
438
+ }
439
+ }
440
+ for (const { targetPath, frontmatter, body } of pending.values()) {
441
+ await writeFileAtomic(targetPath, ["---", stringifySafeYaml(frontmatter).trimEnd(), "---", "", body].join("\n"), wikiDir);
442
+ }
676
443
  if (nextConfig) {
677
444
  await writeWikiConfigFile(wikiDir, nextConfig);
678
445
  }
@@ -686,6 +453,8 @@ export async function ingestDocs(inputPath, options) {
686
453
  sourceRegistered,
687
454
  domainCreated,
688
455
  scenes: sceneResults,
456
+ linkedEdgeCount,
457
+ ambiguousReferenceCodes,
689
458
  warnings,
690
459
  };
691
460
  }