@mfdaves/okf-mcp 0.3.3 → 0.5.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 (40) hide show
  1. package/.agents/skills/okf-v02-migration/SKILL.md +37 -0
  2. package/.agents/skills/okf-v02-migration/agents/openai.yaml +6 -0
  3. package/.agents/skills/okf-v02-migration/references/field-mapping.md +26 -0
  4. package/README.md +192 -78
  5. package/okf/bundles/okf-mcp/distribution/reference-bundle.md +2 -2
  6. package/okf/bundles/okf-mcp/index.md +7 -0
  7. package/okf/bundles/okf-mcp/interfaces/http-authoring-api.md +2 -2
  8. package/okf/bundles/okf-mcp/interfaces/mcp-tools.md +8 -4
  9. package/okf/bundles/okf-mcp/overview/okf-mcp.md +2 -2
  10. package/okf/bundles/okf-mcp/policies/authoring-safety.md +5 -3
  11. package/okf/bundles/okf-mcp/runtime/file-concept-store.md +7 -5
  12. package/okf/bundles/okf-mcp/runtime/indexer.md +6 -4
  13. package/okf/bundles/okf-mcp/runtime/mcp-server.md +6 -6
  14. package/okf/bundles/okf-mcp/specs/attested-computation.md +24 -0
  15. package/okf/bundles/okf-mcp/specs/concept-format.md +5 -3
  16. package/okf/bundles/okf-mcp/specs/git-sources.md +23 -0
  17. package/okf/bundles/okf-mcp/workflows/v02-migration.md +24 -0
  18. package/package.json +9 -3
  19. package/server.json +5 -5
  20. package/src/assets.js +469 -0
  21. package/src/authoring.js +492 -20
  22. package/src/cli.js +467 -37
  23. package/src/computation.js +366 -0
  24. package/src/git-source.js +551 -0
  25. package/src/graph.js +71 -18
  26. package/src/http-server.js +8 -1
  27. package/src/index.js +5 -0
  28. package/src/indexer.js +428 -24
  29. package/src/markdown.js +129 -0
  30. package/src/mcp-server.js +447 -313
  31. package/src/migration.js +687 -0
  32. package/src/parser.js +135 -54
  33. package/src/plugins.js +30 -50
  34. package/src/project.js +74 -17
  35. package/src/remote.js +232 -17
  36. package/src/search.js +69 -6
  37. package/src/store.js +421 -25
  38. package/src/v02.js +545 -0
  39. package/src/validation.js +13 -2
  40. package/src/mcp-protocol.js +0 -283
package/src/parser.js CHANGED
@@ -3,16 +3,29 @@
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
5
  const yaml = require("js-yaml");
6
+ const { normalizeV02Signals } = require("./v02");
7
+ const { markdownStructure, nodeText } = require("./markdown");
6
8
 
7
9
  function normalizeSlashes(value) {
8
10
  return String(value || "").replace(/\\/g, "/");
9
11
  }
10
12
 
11
13
  function isReservedPath(relativePath) {
12
- const base = path.basename(relativePath).toLowerCase();
14
+ const base = path.basename(relativePath);
13
15
  return base === "index.md" || base === "log.md";
14
16
  }
15
17
 
18
+ function validOkfConceptUri(value) {
19
+ if (typeof value !== "string" || value.trim() !== value) {
20
+ return false;
21
+ }
22
+ const match = value.match(/^okf:\/\/([^/\s?#]+)\/([^\s?#]+)$/);
23
+ return Boolean(
24
+ match
25
+ && match[2].split("/").every((segment) => segment && segment !== "." && segment !== ".."),
26
+ );
27
+ }
28
+
16
29
  function parseFrontmatterYaml(source) {
17
30
  let parsed;
18
31
  try {
@@ -57,27 +70,61 @@ function splitFrontmatter(text) {
57
70
  }
58
71
 
59
72
  function extractTitle(body, fallback) {
60
- const match = String(body || "").match(/^#\s+(.+)$/m);
61
- return match ? match[1].trim() : fallback;
73
+ const heading = markdownStructure(body).headings.find((entry) => entry.level === 1);
74
+ return heading ? heading.text || fallback : fallback;
75
+ }
76
+
77
+ function isExternalMarkdownTarget(target) {
78
+ return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(target) || target.startsWith("//");
62
79
  }
63
80
 
64
81
  function extractMarkdownLinks(body) {
65
82
  const out = [];
66
- const regex = /!?\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
67
- let match;
68
- while ((match = regex.exec(String(body || "")))) {
69
- const target = match[2].trim();
70
- if (!target || target.startsWith("http://") || target.startsWith("https://") || target.startsWith("mailto:") || target.startsWith("#")) {
83
+ const tree = markdownStructure(body).tree;
84
+ const walker = tree.walker();
85
+ let event;
86
+ while ((event = walker.next())) {
87
+ const node = event.node;
88
+ if (!event.entering || node.type !== "link") {
89
+ continue;
90
+ }
91
+ const target = String(node.destination || "").trim();
92
+ if (!target || isExternalMarkdownTarget(target) || target.startsWith("#")) {
71
93
  continue;
72
94
  }
73
95
  out.push({
74
- text: match[1],
96
+ text: nodeText(node),
75
97
  href: target,
76
98
  });
77
99
  }
78
100
  return out;
79
101
  }
80
102
 
103
+ function topLevelBlocks(tree) {
104
+ const blocks = [];
105
+ let current = tree && tree.firstChild;
106
+ while (current) {
107
+ blocks.push(current);
108
+ current = current.next;
109
+ }
110
+ return blocks;
111
+ }
112
+
113
+ function hasLocalLink(node) {
114
+ const walker = node.walker();
115
+ let event;
116
+ while ((event = walker.next())) {
117
+ if (event.entering
118
+ && event.node.type === "link"
119
+ && event.node.destination
120
+ && !isExternalMarkdownTarget(event.node.destination)
121
+ && !String(event.node.destination).startsWith("#")) {
122
+ return true;
123
+ }
124
+ }
125
+ return false;
126
+ }
127
+
81
128
  function safeRelativePath(root, absolutePath) {
82
129
  const resolvedRoot = path.resolve(root);
83
130
  const resolvedPath = path.resolve(absolutePath);
@@ -99,24 +146,6 @@ function conformanceDiagnostic(bundle, relativePath, code, message) {
99
146
  };
100
147
  }
101
148
 
102
- function markdownLines(body) {
103
- const lines = String(body || "").split(/\r?\n/);
104
- let fence = null;
105
- return lines.map((text, index) => {
106
- const marker = text.match(/^\s*(```+|~~~+)/);
107
- const hidden = Boolean(fence);
108
- if (marker) {
109
- if (!fence) {
110
- fence = marker[1][0];
111
- } else if (marker[1][0] === fence) {
112
- fence = null;
113
- }
114
- return { index, text, hidden: true };
115
- }
116
- return { index, text, hidden };
117
- });
118
- }
119
-
120
149
  function validIsoDate(value) {
121
150
  const match = String(value || "").match(/^(\d{4})-(\d{2})-(\d{2})$/);
122
151
  if (!match) {
@@ -169,8 +198,9 @@ function validateReservedIndex(bundle, relativePath, split) {
169
198
  }
170
199
  }
171
200
  }
172
- const visible = markdownLines(split.body).filter((line) => !line.hidden);
173
- if (!visible.some((line) => /^#{1,6}[ \t]+\S/.test(line.text))) {
201
+ const structure = markdownStructure(split.body);
202
+ const blocks = topLevelBlocks(structure.tree);
203
+ if (!structure.headings.length) {
174
204
  diagnostics.push(conformanceDiagnostic(
175
205
  bundle,
176
206
  relativePath,
@@ -178,7 +208,20 @@ function validateReservedIndex(bundle, relativePath, split) {
178
208
  "Reserved index.md must contain at least one Markdown heading.",
179
209
  ));
180
210
  }
181
- if (!extractMarkdownLinks(split.body).length) {
211
+ if (blocks.length && blocks[0].type !== "heading") {
212
+ diagnostics.push(conformanceDiagnostic(
213
+ bundle,
214
+ relativePath,
215
+ "reserved_index_heading_order",
216
+ "Reserved index.md content must begin with a heading.",
217
+ ));
218
+ }
219
+ const groupedLink = blocks.some((block, index) => (
220
+ block.type === "list"
221
+ && blocks.slice(0, index).some((entry) => entry.type === "heading")
222
+ && hasLocalLink(block)
223
+ ));
224
+ if (!groupedLink) {
182
225
  diagnostics.push(conformanceDiagnostic(
183
226
  bundle,
184
227
  relativePath,
@@ -199,11 +242,9 @@ function validateReservedLog(bundle, relativePath, split) {
199
242
  "Reserved log.md must not declare YAML frontmatter.",
200
243
  ));
201
244
  }
202
- const visible = markdownLines(split.body).filter((line) => !line.hidden);
203
- const headings = visible.map((line) => {
204
- const match = line.text.match(/^(#{1,6})[ \t]+(.+?)[ \t]*$/);
205
- return match ? { index: line.index, level: match[1].length, text: match[2].trim() } : null;
206
- }).filter(Boolean);
245
+ const structure = markdownStructure(split.body);
246
+ const blocks = topLevelBlocks(structure.tree);
247
+ const headings = structure.headings;
207
248
  const h1 = headings.filter((heading) => heading.level === 1);
208
249
  if (!h1.length) {
209
250
  diagnostics.push(conformanceDiagnostic(
@@ -212,7 +253,7 @@ function validateReservedLog(bundle, relativePath, split) {
212
253
  "reserved_log_missing_h1",
213
254
  "Reserved log.md must start with an H1 title.",
214
255
  ));
215
- } else if (headings[0] !== h1[0]) {
256
+ } else if (!blocks.length || blocks[0] !== h1[0].node) {
216
257
  diagnostics.push(conformanceDiagnostic(
217
258
  bundle,
218
259
  relativePath,
@@ -220,6 +261,14 @@ function validateReservedLog(bundle, relativePath, split) {
220
261
  "The H1 title in reserved log.md must precede its dated sections.",
221
262
  ));
222
263
  }
264
+ if (h1.length > 1) {
265
+ diagnostics.push(conformanceDiagnostic(
266
+ bundle,
267
+ relativePath,
268
+ "reserved_log_multiple_h1",
269
+ "Reserved log.md must contain exactly one H1 title.",
270
+ ));
271
+ }
223
272
 
224
273
  const h2 = headings.filter((heading) => heading.level === 2);
225
274
  const sections = [];
@@ -264,12 +313,12 @@ function validateReservedLog(bundle, relativePath, split) {
264
313
  }
265
314
  }
266
315
  sections.forEach((section) => {
267
- const nextH2 = h2.find((heading) => heading.index > section.index);
268
- const end = nextH2 ? nextH2.index : Number.POSITIVE_INFINITY;
269
- const hasListItem = visible.some((line) => (
270
- line.index > section.index
271
- && line.index < end
272
- && /^\s*(?:[-+*]|\d+[.)])\s+\S/.test(line.text)
316
+ const nextHeading = headings.find((heading) => (
317
+ heading.startLine > section.startLine && heading.level <= section.level
318
+ ));
319
+ const end = nextHeading ? nextHeading.startLine : Number.POSITIVE_INFINITY;
320
+ const hasListItem = structure.items.some((item) => (
321
+ item.startLine > section.startLine && item.startLine < end
273
322
  ));
274
323
  if (!hasListItem) {
275
324
  diagnostics.push(conformanceDiagnostic(
@@ -284,7 +333,7 @@ function validateReservedLog(bundle, relativePath, split) {
284
333
  }
285
334
 
286
335
  function validateReservedDocument(bundle, relativePath, split) {
287
- const base = path.basename(relativePath).toLowerCase();
336
+ const base = path.basename(relativePath);
288
337
  if (base === "index.md") {
289
338
  return validateReservedIndex(bundle, relativePath, split);
290
339
  }
@@ -294,7 +343,7 @@ function validateReservedDocument(bundle, relativePath, split) {
294
343
  return [];
295
344
  }
296
345
 
297
- function parseMarkdownText(bundle, relativePath, text, sourcePath) {
346
+ function parseMarkdownText(bundle, relativePath, text, sourcePath, options) {
298
347
  const reserved = isReservedPath(relativePath);
299
348
  const split = splitFrontmatter(text);
300
349
  const frontmatter = split.frontmatter || {};
@@ -302,20 +351,39 @@ function parseMarkdownText(bundle, relativePath, text, sourcePath) {
302
351
  if (!reserved && !split.frontmatter) {
303
352
  warnings.push({ code: "missing_frontmatter", path: relativePath, message: "Concept file has no YAML frontmatter." });
304
353
  }
305
- if (!reserved && (!frontmatter.type || String(frontmatter.type).trim() === "")) {
306
- warnings.push({ code: "missing_type", path: relativePath, message: "Concept file has no non-empty type field." });
354
+ const validType = typeof frontmatter.type === "string" && frontmatter.type.trim() !== "";
355
+ if (!reserved && !validType) {
356
+ warnings.push({ code: "missing_type", path: relativePath, message: "Concept file type must be a non-empty string." });
307
357
  }
308
- if (!reserved && frontmatter.id && !String(frontmatter.id).startsWith("okf://")) {
309
- warnings.push({ code: "invalid_id", path: relativePath, message: "Concept id must start with okf://." });
358
+ const hasCustomId = Object.prototype.hasOwnProperty.call(frontmatter, "id");
359
+ const customIdValid = hasCustomId && validOkfConceptUri(frontmatter.id);
360
+ if (!reserved && hasCustomId && !customIdValid) {
361
+ warnings.push({
362
+ code: "invalid_id",
363
+ path: relativePath,
364
+ message: "Concept id must match okf://<bundle>/<concept-id> with non-empty safe path segments.",
365
+ });
310
366
  }
311
367
  const conformanceDiagnostics = reserved
312
368
  ? validateReservedDocument(bundle, relativePath, split)
313
369
  : warnings
314
370
  .filter((warning) => warning.code === "missing_frontmatter" || warning.code === "missing_type")
315
371
  .map((warning) => conformanceDiagnostic(bundle, relativePath, warning.code, warning.message));
316
- const title = frontmatter.title || extractTitle(split.body, path.basename(relativePath, ".md"));
372
+ const title = frontmatter.title || extractTitle(split.body, path.basename(relativePath).replace(/\.md$/i, ""));
317
373
  const pathUri = `okf://${bundle.id}/${relativePath}`;
318
- const uri = frontmatter.id && String(frontmatter.id).startsWith("okf://") ? String(frontmatter.id) : pathUri;
374
+ const conceptId = reserved
375
+ ? relativePath
376
+ : normalizeSlashes(relativePath).replace(/\.md$/i, "");
377
+ const uri = `okf://${bundle.id}/${conceptId}`;
378
+ const customId = customIdValid ? frontmatter.id : null;
379
+ const signals = normalizeV02Signals({ frontmatter, body: split.body }, {
380
+ asOf: options && options.asOf,
381
+ });
382
+ const v02Diagnostics = signals.diagnostics.map((entry) => Object.assign({
383
+ bundle: bundle.id,
384
+ path: relativePath,
385
+ }, entry));
386
+ warnings.push.apply(warnings, v02Diagnostics);
319
387
  return {
320
388
  bundle: bundle.id,
321
389
  bundleRoot: bundle.root,
@@ -323,36 +391,49 @@ function parseMarkdownText(bundle, relativePath, text, sourcePath) {
323
391
  absolutePath: sourcePath || relativePath,
324
392
  uri,
325
393
  pathUri,
394
+ conceptId,
395
+ customId,
396
+ uriAliases: Array.from(new Set([pathUri, customId].filter((alias) => alias && alias !== uri))),
326
397
  reserved,
327
398
  kind: reserved ? "reserved" : "concept",
328
399
  frontmatter,
329
400
  rawFrontmatter: split.rawFrontmatter,
330
401
  body: split.body,
331
402
  text,
332
- type: frontmatter.type || null,
403
+ type: validType ? frontmatter.type : null,
333
404
  title,
334
405
  description: frontmatter.description || "",
335
406
  tags: Array.isArray(frontmatter.tags) ? frontmatter.tags.map(String) : [],
336
407
  aliases: Array.isArray(frontmatter.aliases) ? frontmatter.aliases.map(String) : [],
337
408
  relations: Array.isArray(frontmatter.relations) ? frontmatter.relations : [],
409
+ signals,
410
+ v02Diagnostics,
338
411
  links: extractMarkdownLinks(split.body),
339
412
  warnings,
340
413
  diagnostics: conformanceDiagnostics,
341
414
  conformanceDiagnostics,
342
- valid: reserved || Boolean(frontmatter.type && String(frontmatter.type).trim() !== ""),
415
+ valid: reserved || validType,
343
416
  };
344
417
  }
345
418
 
346
- function parseMarkdownFile(bundle, absolutePath) {
419
+ function parseMarkdownFile(bundle, absolutePath, options) {
347
420
  const relativePath = safeRelativePath(bundle.root, absolutePath);
348
421
  if (relativePath === null) {
349
422
  throw new Error(`Path is outside bundle root: ${absolutePath}`);
350
423
  }
351
- return parseMarkdownText(bundle, relativePath, fs.readFileSync(absolutePath, "utf8"), absolutePath);
424
+ const bytes = fs.readFileSync(absolutePath);
425
+ let text;
426
+ try {
427
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
428
+ } catch {
429
+ throw new Error("Concept document is not valid UTF-8.");
430
+ }
431
+ return parseMarkdownText(bundle, relativePath, text, absolutePath, options);
352
432
  }
353
433
 
354
434
  module.exports = {
355
435
  extractMarkdownLinks,
436
+ extractTitle,
356
437
  isReservedPath,
357
438
  normalizeSlashes,
358
439
  parseFrontmatterYaml,
package/src/plugins.js CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
- const { isInsidePath } = require("./project");
5
+ const { safeProjectPath } = require("./project");
6
+ const { renderFrontmatter } = require("./authoring");
6
7
 
7
8
  function ensureDir(dirPath) {
8
9
  fs.mkdirSync(dirPath, { recursive: true });
@@ -16,43 +17,17 @@ function slug(value) {
16
17
  return String(value || "concept").replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "concept";
17
18
  }
18
19
 
19
- function yamlScalar(value) {
20
- if (value === null) {
21
- return "null";
22
- }
23
- if (typeof value === "boolean" || typeof value === "number") {
24
- return String(value);
25
- }
26
- return JSON.stringify(String(value || ""));
27
- }
28
-
29
- function yamlValue(lines, key, value) {
30
- if (Array.isArray(value)) {
31
- lines.push(`${key}:`);
32
- value.forEach((entry) => {
33
- if (entry && typeof entry === "object") {
34
- const entries = Object.entries(entry);
35
- const first = entries.shift();
36
- lines.push(` - ${first[0]}: ${yamlScalar(first[1])}`);
37
- entries.forEach(([childKey, childValue]) => {
38
- lines.push(` ${childKey}: ${yamlScalar(childValue)}`);
39
- });
40
- } else {
41
- lines.push(` - ${yamlScalar(entry)}`);
42
- }
43
- });
44
- return;
45
- }
46
- lines.push(`${key}: ${yamlScalar(value)}`);
47
- }
48
-
49
20
  function conceptMarkdown(frontmatter, bodyLines) {
50
- const lines = ["---"];
51
- Object.keys(frontmatter).forEach((key) => yamlValue(lines, key, frontmatter[key]));
52
- lines.push("---", "");
21
+ const lines = ["---", renderFrontmatter(frontmatter), "---", ""];
53
22
  return lines.concat(bodyLines || []).join("\n") + "\n";
54
23
  }
55
24
 
25
+ function generatedMetadata(plugin) {
26
+ return {
27
+ by: `process:okf-mcp/${plugin.name || plugin.type || "generator"}`,
28
+ };
29
+ }
30
+
56
31
  function walkFiles(root, extensions) {
57
32
  const out = [];
58
33
  if (!fs.existsSync(root)) {
@@ -75,28 +50,22 @@ function outputRoot(project, plugin) {
75
50
  if (!plugin.output) {
76
51
  throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} is missing output.`);
77
52
  }
78
- if (path.isAbsolute(String(plugin.output))) {
79
- throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} output must be relative to the project root.`);
80
- }
81
- const resolved = path.resolve(project.root, plugin.output);
82
- if (!isInsidePath(project.root, resolved)) {
83
- throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} output resolves outside the project root.`);
84
- }
85
- return resolved;
53
+ return safeProjectPath(
54
+ project.root,
55
+ plugin.output,
56
+ `Plugin ${plugin.name || plugin.type || "<unnamed>"} output`,
57
+ );
86
58
  }
87
59
 
88
60
  function sourceRoot(project, plugin) {
89
61
  if (!plugin.root) {
90
62
  throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} is missing root.`);
91
63
  }
92
- if (path.isAbsolute(String(plugin.root))) {
93
- throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} root must be relative to the project root.`);
94
- }
95
- const resolved = path.resolve(project.root, plugin.root);
96
- if (!isInsidePath(project.root, resolved)) {
97
- throw new Error(`Plugin ${plugin.name || plugin.type || "<unnamed>"} root resolves outside the project root.`);
98
- }
99
- return resolved;
64
+ return safeProjectPath(
65
+ project.root,
66
+ plugin.root,
67
+ `Plugin ${plugin.name || plugin.type || "<unnamed>"} root`,
68
+ );
100
69
  }
101
70
 
102
71
  function writeGeneratedFiles(root, files) {
@@ -124,6 +93,10 @@ function generateFilesystemConcepts(project, plugin) {
124
93
  type: plugin.conceptType || "Repository File",
125
94
  title,
126
95
  description: `Repository file ${relative}.`,
96
+ resource: `repo://${relative}`,
97
+ sources: [{ resource: `repo://${relative}`, title }],
98
+ generated: generatedMetadata(plugin),
99
+ // Compatibility extension retained for existing generated catalogs.
127
100
  source: `repo://${relative}`,
128
101
  tags: Array.isArray(plugin.tags) ? plugin.tags : ["generated", "file"],
129
102
  }, [
@@ -160,6 +133,10 @@ function generateJsonSpecConcepts(project, plugin) {
160
133
  type: plugin.conceptType || "JSON Spec",
161
134
  title: key,
162
135
  description: json.description || `Generated concept for JSON spec ${key}.`,
136
+ resource: `repo://${relative}`,
137
+ sources: [{ resource: `repo://${relative}`, title: key }],
138
+ generated: generatedMetadata(plugin),
139
+ // Compatibility extension retained for existing generated catalogs.
163
140
  source: `repo://${relative}`,
164
141
  tags: Array.isArray(plugin.tags) ? plugin.tags : ["generated", "spec"],
165
142
  relations,
@@ -179,6 +156,9 @@ function generateJsonSpecConcepts(project, plugin) {
179
156
  }
180
157
 
181
158
  function generateProject(project) {
159
+ if (Array.isArray(project && project.errors) && project.errors.length) {
160
+ throw new Error("Cannot run generator plugins while the project configuration is invalid.");
161
+ }
182
162
  const results = [];
183
163
  project.plugins.forEach((plugin) => {
184
164
  const type = plugin.type || plugin.name;
package/src/project.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
- const { parseFrontmatterYaml } = require("./parser");
5
+ const { parseFrontmatterYaml, splitFrontmatter } = require("./parser");
6
6
 
7
7
  const DEFAULT_RELATION_TYPES = [
8
8
  "depends_on",
@@ -27,27 +27,54 @@ function isInsidePath(root, target) {
27
27
  return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
28
28
  }
29
29
 
30
- function resolveProjectPath(projectRoot, value, field, errors) {
30
+ function safeProjectPath(projectRoot, value, field) {
31
+ const label = field || "project path";
31
32
  if (!value || path.isAbsolute(String(value))) {
32
- errors.push({
33
- code: "invalid_project_path",
34
- field,
35
- path: value || "",
36
- message: `${field} must be a relative path inside the project root.`,
37
- });
38
- return null;
33
+ const error = new Error(`${label} must be a relative path inside the project root.`);
34
+ error.code = "invalid_project_path";
35
+ throw error;
39
36
  }
40
- const resolved = path.resolve(projectRoot, value);
41
- if (!isInsidePath(projectRoot, resolved)) {
37
+ const realRoot = fs.realpathSync(projectRoot);
38
+ const resolved = path.resolve(realRoot, String(value));
39
+ if (!isInsidePath(realRoot, resolved)) {
40
+ const error = new Error(`${label} resolves outside the project root.`);
41
+ error.code = "project_path_outside_root";
42
+ throw error;
43
+ }
44
+ const relative = path.relative(realRoot, resolved);
45
+ let current = realRoot;
46
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
47
+ current = path.join(current, segment);
48
+ let stat;
49
+ try {
50
+ stat = fs.lstatSync(current);
51
+ } catch (error) {
52
+ if (error && error.code === "ENOENT") {
53
+ break;
54
+ }
55
+ throw error;
56
+ }
57
+ if (stat.isSymbolicLink()) {
58
+ const error = new Error(`${label} cannot traverse a symbolic link inside the project root.`);
59
+ error.code = "project_path_symlink";
60
+ throw error;
61
+ }
62
+ }
63
+ return resolved;
64
+ }
65
+
66
+ function resolveProjectPath(projectRoot, value, field, errors) {
67
+ try {
68
+ return safeProjectPath(projectRoot, value, field);
69
+ } catch (error) {
42
70
  errors.push({
43
- code: "project_path_outside_root",
71
+ code: error.code || "invalid_project_path",
44
72
  field,
45
- path: value,
46
- message: `${field} resolves outside the project root.`,
73
+ path: value || "",
74
+ message: error.message,
47
75
  });
48
76
  return null;
49
77
  }
50
- return resolved;
51
78
  }
52
79
 
53
80
  function findProjectConfig(startDir) {
@@ -69,6 +96,29 @@ function findProjectConfig(startDir) {
69
96
  }
70
97
  }
71
98
 
99
+ function findOkfRoot(startDir) {
100
+ let current = path.resolve(startDir || process.cwd());
101
+ while (true) {
102
+ const indexPath = path.join(current, "index.md");
103
+ if (fs.existsSync(indexPath) && fs.statSync(indexPath).isFile()) {
104
+ try {
105
+ const split = splitFrontmatter(fs.readFileSync(indexPath, "utf8"));
106
+ if (split.frontmatter
107
+ && Object.prototype.hasOwnProperty.call(split.frontmatter, "okf_version")) {
108
+ return current;
109
+ }
110
+ } catch {
111
+ // Discovery is best effort; validation reports malformed root indexes.
112
+ }
113
+ }
114
+ const parent = path.dirname(current);
115
+ if (parent === current) {
116
+ return null;
117
+ }
118
+ current = parent;
119
+ }
120
+ }
121
+
72
122
  function readConfigFile(configPath) {
73
123
  const absolutePath = path.resolve(configPath);
74
124
  const text = fs.readFileSync(absolutePath, "utf8");
@@ -189,12 +239,13 @@ function normalizeRemoteBundles(config, errors) {
189
239
  }
190
240
 
191
241
  function loadProjectConfig(configPath) {
192
- const resolvedPath = configPath
242
+ const requestedPath = configPath
193
243
  ? path.resolve(configPath)
194
244
  : findProjectConfig(process.cwd());
195
- if (!resolvedPath) {
245
+ if (!requestedPath) {
196
246
  throw new Error("No okf.project.yaml or okf.project.json found. Pass --project or --bundle.");
197
247
  }
248
+ const resolvedPath = fs.realpathSync(requestedPath);
198
249
  const rawConfig = readConfigFile(resolvedPath);
199
250
  const errors = [];
200
251
  if (!rawConfig || typeof rawConfig !== "object" || Array.isArray(rawConfig)) {
@@ -202,6 +253,9 @@ function loadProjectConfig(configPath) {
202
253
  }
203
254
  const config = (!rawConfig || typeof rawConfig !== "object" || Array.isArray(rawConfig)) ? {} : rawConfig;
204
255
  validateRelationTypes(config, errors);
256
+ if (config.strictLinks !== undefined && typeof config.strictLinks !== "boolean") {
257
+ errors.push({ code: "invalid_strict_links", field: "strictLinks", message: "strictLinks must be a boolean." });
258
+ }
205
259
  const relationTypes = new Set(DEFAULT_RELATION_TYPES.concat(Array.isArray(config.relationTypes) ? config.relationTypes.map(String) : []));
206
260
  const bundles = normalizeBundles(config, resolvedPath, errors);
207
261
  const remoteBundles = normalizeRemoteBundles(config, errors);
@@ -221,6 +275,7 @@ function loadProjectConfig(configPath) {
221
275
  remoteBundles,
222
276
  relationTypes: Array.from(relationTypes),
223
277
  plugins: Array.isArray(config.plugins) ? config.plugins : [],
278
+ strictLinks: Boolean(config.strictLinks),
224
279
  errors,
225
280
  raw: config,
226
281
  };
@@ -228,8 +283,10 @@ function loadProjectConfig(configPath) {
228
283
 
229
284
  module.exports = {
230
285
  DEFAULT_RELATION_TYPES,
286
+ findOkfRoot,
231
287
  findProjectConfig,
232
288
  isInsidePath,
233
289
  loadProjectConfig,
234
290
  resolveProjectPath,
291
+ safeProjectPath,
235
292
  };