@mfdaves/okf-mcp 0.3.2-rc.1

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.
package/src/cli.js ADDED
@@ -0,0 +1,427 @@
1
+ "use strict";
2
+
3
+ const {
4
+ attachProject,
5
+ buildIndex,
6
+ buildProjectIndexAsync,
7
+ loadProjectBundles,
8
+ validateIndex,
9
+ } = require("./indexer");
10
+ const { exportGraph, findPaths, getNeighbors, graphSummary } = require("./graph");
11
+ const { searchConcepts } = require("./search");
12
+ const { conceptSummary } = require("./indexer");
13
+ const { findProjectConfig, loadProjectConfig } = require("./project");
14
+ const { generateProject } = require("./plugins");
15
+ const { runStdioServer } = require("./mcp-server");
16
+ const { fetchRemoteBundles } = require("./remote");
17
+ const { runHttpServer } = require("./http-server");
18
+ const packageMetadata = require("../package.json");
19
+
20
+ const COMMANDS = new Set(["mcp", "validate", "graph", "search", "concept", "neighbors", "paths", "generate", "serve"]);
21
+
22
+ class UsageError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "UsageError";
26
+ this.code = "OKF_USAGE_ERROR";
27
+ this.exitCode = 2;
28
+ }
29
+ }
30
+
31
+ function usageError(message) {
32
+ return new UsageError(message);
33
+ }
34
+
35
+ function exitCodeForError(error) {
36
+ return error && error.exitCode === 2 ? 2 : 1;
37
+ }
38
+
39
+ function parseArgs(argv) {
40
+ const bundles = [];
41
+ const remoteBundles = [];
42
+ const positional = [];
43
+ let project = null;
44
+ let inspect = false;
45
+ let help = false;
46
+ let host = "127.0.0.1";
47
+ let port = 8765;
48
+ let writeToken = "";
49
+ let proposalRoot = "";
50
+ let version = false;
51
+ let authoring = false;
52
+ let allowRemoteTool = false;
53
+ for (let index = 0; index < argv.length; index += 1) {
54
+ const arg = argv[index];
55
+ if (arg === "--bundle" || arg === "-b") {
56
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
57
+ throw usageError(`${arg} requires a value.`);
58
+ }
59
+ bundles.push(argv[index + 1]);
60
+ index += 1;
61
+ continue;
62
+ }
63
+ if (arg.startsWith("--bundle=")) {
64
+ const value = arg.slice("--bundle=".length);
65
+ if (!value) {
66
+ throw usageError("--bundle requires a value.");
67
+ }
68
+ bundles.push(value);
69
+ continue;
70
+ }
71
+ if (arg === "--remote-bundle") {
72
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
73
+ throw usageError(`${arg} requires a value.`);
74
+ }
75
+ remoteBundles.push(argv[index + 1]);
76
+ index += 1;
77
+ continue;
78
+ }
79
+ if (arg.startsWith("--remote-bundle=")) {
80
+ const value = arg.slice("--remote-bundle=".length);
81
+ if (!value) {
82
+ throw usageError("--remote-bundle requires a value.");
83
+ }
84
+ remoteBundles.push(value);
85
+ continue;
86
+ }
87
+ if (arg === "--project" || arg === "-p") {
88
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
89
+ throw usageError(`${arg} requires a value.`);
90
+ }
91
+ project = argv[index + 1];
92
+ index += 1;
93
+ continue;
94
+ }
95
+ if (arg.startsWith("--project=")) {
96
+ project = arg.slice("--project=".length);
97
+ if (!project) {
98
+ throw usageError("--project requires a value.");
99
+ }
100
+ continue;
101
+ }
102
+ if (arg === "--inspect") {
103
+ inspect = true;
104
+ continue;
105
+ }
106
+ if (arg === "--authoring") {
107
+ authoring = true;
108
+ continue;
109
+ }
110
+ if (arg === "--allow-remote-tool") {
111
+ allowRemoteTool = true;
112
+ continue;
113
+ }
114
+ if (arg === "--host") {
115
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
116
+ throw usageError(`${arg} requires a value.`);
117
+ }
118
+ host = argv[index + 1];
119
+ index += 1;
120
+ continue;
121
+ }
122
+ if (arg.startsWith("--host=")) {
123
+ host = arg.slice("--host=".length);
124
+ continue;
125
+ }
126
+ if (arg === "--port") {
127
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
128
+ throw usageError(`${arg} requires a value.`);
129
+ }
130
+ port = Number(argv[index + 1]);
131
+ index += 1;
132
+ continue;
133
+ }
134
+ if (arg.startsWith("--port=")) {
135
+ port = Number(arg.slice("--port=".length));
136
+ continue;
137
+ }
138
+ if (arg === "--write-token") {
139
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
140
+ throw usageError(`${arg} requires a value.`);
141
+ }
142
+ writeToken = argv[index + 1];
143
+ index += 1;
144
+ continue;
145
+ }
146
+ if (arg.startsWith("--write-token=")) {
147
+ writeToken = arg.slice("--write-token=".length);
148
+ continue;
149
+ }
150
+ if (arg === "--proposal-root") {
151
+ if (!argv[index + 1] || String(argv[index + 1]).startsWith("-")) {
152
+ throw usageError(`${arg} requires a value.`);
153
+ }
154
+ proposalRoot = argv[index + 1];
155
+ index += 1;
156
+ continue;
157
+ }
158
+ if (arg.startsWith("--proposal-root=")) {
159
+ proposalRoot = arg.slice("--proposal-root=".length);
160
+ continue;
161
+ }
162
+ if (arg === "--help" || arg === "-h") {
163
+ help = true;
164
+ continue;
165
+ }
166
+ if (arg === "--version" || arg === "-v") {
167
+ version = true;
168
+ continue;
169
+ }
170
+ if (arg === "--") {
171
+ positional.push(...argv.slice(index + 1));
172
+ break;
173
+ }
174
+ if (arg && arg.startsWith("-")) {
175
+ throw usageError(`Unknown option: ${arg}`);
176
+ }
177
+ if (arg && !arg.startsWith("-")) {
178
+ positional.push(arg);
179
+ }
180
+ }
181
+ return {
182
+ bundles,
183
+ remoteBundles,
184
+ positional,
185
+ project,
186
+ inspect,
187
+ help,
188
+ version,
189
+ authoring,
190
+ allowRemoteTool,
191
+ host,
192
+ port,
193
+ writeToken,
194
+ proposalRoot,
195
+ };
196
+ }
197
+
198
+ function usage() {
199
+ return [
200
+ "okf-mcp / okf",
201
+ "",
202
+ "Usage:",
203
+ " okf-mcp --bundle <path-or-id=path> [--bundle <path>] [--inspect]",
204
+ " okf-mcp --remote-bundle <id=github-tree-url> [--inspect]",
205
+ " okf-mcp --project <okf.project.yaml> <command>",
206
+ " okf-mcp [--project <okf.project.yaml>] [--authoring] [--allow-remote-tool] mcp",
207
+ " okf-mcp --project <okf.project.yaml> serve [--host 127.0.0.1] [--port 8765]",
208
+ " okf-mcp <command> --bundle <path-or-id=path>",
209
+ "",
210
+ "Commands:",
211
+ " mcp Start the stdio MCP server.",
212
+ " validate Validate project or bundles.",
213
+ " graph [json|dot|mermaid] Export graph.",
214
+ " search <query> Search concepts.",
215
+ " concept <uri> Print one concept.",
216
+ " neighbors <uri> Print inbound/outbound neighbors.",
217
+ " paths <from> <to> Find directed paths.",
218
+ " generate Run configured generator plugins.",
219
+ " serve Start the HTTP OKF API server.",
220
+ "",
221
+ "Options:",
222
+ " --authoring Enable MCP proposal authoring tools.",
223
+ " --allow-remote-tool Enable runtime remote-bundle loading over MCP.",
224
+ " --version, -v Print the package version.",
225
+ " --help, -h Print this help.",
226
+ " --debug Include stack traces in error output.",
227
+ "",
228
+ "When no project or bundle source is passed, the nearest okf.project.yaml",
229
+ "or okf.project.json is discovered from the current directory.",
230
+ "",
231
+ "Examples:",
232
+ " node bin/okf-mcp.js --bundle ./okf/bundles/app --inspect",
233
+ " node bin/okf-mcp.js --bundle app=./okf/bundles/app",
234
+ " node bin/okf-mcp.js --remote-bundle docs=https://github.com/org/repo/tree/main/okf/bundles/docs --inspect",
235
+ " node bin/okf-mcp.js --project okf.project.yaml validate",
236
+ "",
237
+ ].join("\n");
238
+ }
239
+
240
+ function resolveLegacyBundles(args) {
241
+ if (args.bundles.length) {
242
+ return args.bundles;
243
+ }
244
+ if (!args.positional.length) {
245
+ return [];
246
+ }
247
+ const first = args.positional[0];
248
+ return COMMANDS.has(first) ? [] : args.positional;
249
+ }
250
+
251
+ function parseRemoteBundleArg(value, index) {
252
+ const text = String(value || "");
253
+ const eq = text.indexOf("=");
254
+ if (eq <= 0) {
255
+ throw usageError("--remote-bundle value must use id=https://github.com/... format.");
256
+ }
257
+ return {
258
+ id: text.slice(0, eq),
259
+ provider: "github",
260
+ url: text.slice(eq + 1),
261
+ };
262
+ }
263
+
264
+ function discoverProject(args, startDir) {
265
+ if (!args.project && !args.bundles.length && !args.remoteBundles.length && !resolveLegacyBundles(args).length) {
266
+ args.project = findProjectConfig(startDir);
267
+ }
268
+ return args;
269
+ }
270
+
271
+ function stdioServerOptions(args) {
272
+ const options = {
273
+ remoteBundles: args.remoteBundles.map(parseRemoteBundleArg),
274
+ allowAuthoring: Boolean(args.authoring),
275
+ allowRuntimeRemoteLoad: Boolean(args.allowRemoteTool),
276
+ };
277
+ if (args.project) {
278
+ options.projectPath = args.project;
279
+ }
280
+ return options;
281
+ }
282
+
283
+ async function loadIndex(args) {
284
+ const remoteConfigs = args.remoteBundles.map(parseRemoteBundleArg);
285
+ if (args.project) {
286
+ if (!remoteConfigs.length) {
287
+ return buildProjectIndexAsync(args.project);
288
+ }
289
+ const loaded = await loadProjectBundles(args.project);
290
+ const remoteBundles = await fetchRemoteBundles(remoteConfigs);
291
+ const index = buildIndex(loaded.bundles.concat(remoteBundles), { relationTypes: loaded.project.relationTypes });
292
+ return attachProject(index, loaded.project);
293
+ }
294
+ const bundles = resolveLegacyBundles(args);
295
+ const fetchedRemoteBundles = await fetchRemoteBundles(remoteConfigs);
296
+ if (!bundles.length && !fetchedRemoteBundles.length) {
297
+ throw usageError("At least one --bundle root or --project config is required.");
298
+ }
299
+ return buildIndex(bundles.concat(fetchedRemoteBundles));
300
+ }
301
+
302
+ function printJson(value) {
303
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
304
+ }
305
+
306
+ async function main(argv, runtime) {
307
+ const args = parseArgs(argv || []);
308
+ if (args.help) {
309
+ process.stdout.write(usage());
310
+ return;
311
+ }
312
+ if (args.version) {
313
+ process.stdout.write(`${packageMetadata.version}\n`);
314
+ return;
315
+ }
316
+ discoverProject(args, (runtime && runtime.cwd) || process.cwd());
317
+ if (args.inspect) {
318
+ printJson(graphSummary(await loadIndex(args)));
319
+ return;
320
+ }
321
+ const command = args.positional[0] || "mcp";
322
+ if (!COMMANDS.has(command)) {
323
+ throw usageError(`Unknown OKF command: ${command}`);
324
+ }
325
+ if (command === "mcp") {
326
+ const bundles = resolveLegacyBundles(args);
327
+ if (args.project) {
328
+ const server = await ((runtime && runtime.runStdioServer) || runStdioServer)(
329
+ [],
330
+ process.stdin,
331
+ process.stdout,
332
+ stdioServerOptions(args),
333
+ );
334
+ if (server && server.closed) {
335
+ await server.closed;
336
+ }
337
+ return;
338
+ }
339
+ if (!bundles.length && !args.remoteBundles.length) {
340
+ throw usageError("At least one --bundle root or --project config is required.");
341
+ }
342
+ const server = await ((runtime && runtime.runStdioServer) || runStdioServer)(
343
+ bundles,
344
+ process.stdin,
345
+ process.stdout,
346
+ stdioServerOptions(args),
347
+ );
348
+ if (server && server.closed) {
349
+ await server.closed;
350
+ }
351
+ return;
352
+ }
353
+ if (command === "serve") {
354
+ if (!args.project) {
355
+ throw usageError("serve requires --project.");
356
+ }
357
+ const result = await runHttpServer({
358
+ projectPath: args.project,
359
+ host: args.host,
360
+ port: args.port,
361
+ writeToken: args.writeToken || process.env.OKF_WRITE_TOKEN || "",
362
+ proposalRoot: args.proposalRoot || "",
363
+ });
364
+ process.stderr.write(`OKF HTTP server listening on ${result.url}\n`);
365
+ return;
366
+ }
367
+ if (command === "generate") {
368
+ if (!args.project) {
369
+ throw usageError("generate requires --project.");
370
+ }
371
+ const project = loadProjectConfig(args.project);
372
+ printJson(generateProject(project));
373
+ return;
374
+ }
375
+ const index = await loadIndex(args);
376
+ if (command === "validate") {
377
+ const result = validateIndex(index);
378
+ printJson(result);
379
+ process.exitCode = result.validForProject ? 0 : 1;
380
+ return;
381
+ }
382
+ if (command === "graph") {
383
+ process.stdout.write(exportGraph(index, { format: args.positional[1] || "json", includeExternal: true }) + "\n");
384
+ return;
385
+ }
386
+ if (command === "search") {
387
+ printJson(searchConcepts(index, { query: args.positional.slice(1).join(" ") }));
388
+ return;
389
+ }
390
+ if (command === "concept") {
391
+ const uri = args.positional[1];
392
+ if (!uri) {
393
+ throw usageError("concept requires a URI.");
394
+ }
395
+ const doc = index.byUri.get(uri);
396
+ if (!doc) {
397
+ throw new Error(`Unknown OKF concept URI: ${uri || "<missing>"}`);
398
+ }
399
+ printJson(Object.assign(conceptSummary(doc), { frontmatter: doc.frontmatter, body: doc.body, links: doc.links }));
400
+ return;
401
+ }
402
+ if (command === "neighbors") {
403
+ if (!args.positional[1]) {
404
+ throw usageError("neighbors requires a URI.");
405
+ }
406
+ printJson(getNeighbors(index, args.positional[1]));
407
+ return;
408
+ }
409
+ if (command === "paths") {
410
+ if (!args.positional[1] || !args.positional[2]) {
411
+ throw usageError("paths requires <from> and <to> URIs.");
412
+ }
413
+ printJson(findPaths(index, args.positional[1], args.positional[2]));
414
+ return;
415
+ }
416
+ throw usageError(`Unknown OKF command: ${command}`);
417
+ }
418
+
419
+ module.exports = {
420
+ UsageError,
421
+ discoverProject,
422
+ exitCodeForError,
423
+ main,
424
+ parseArgs,
425
+ stdioServerOptions,
426
+ usage,
427
+ };
package/src/graph.js ADDED
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+
3
+ const { applyFilters } = require("./search");
4
+ const { conceptSummary } = require("./indexer");
5
+
6
+ function nodeFor(doc) {
7
+ return {
8
+ id: doc.uri,
9
+ bundle: doc.bundle,
10
+ path: doc.path,
11
+ pathUri: doc.pathUri,
12
+ type: doc.type,
13
+ title: doc.title,
14
+ tags: doc.tags,
15
+ aliases: doc.aliases,
16
+ description: doc.description,
17
+ };
18
+ }
19
+
20
+ function externalNodeFor(uri) {
21
+ return {
22
+ id: uri,
23
+ bundle: null,
24
+ path: uri,
25
+ pathUri: uri,
26
+ type: "External Reference",
27
+ title: uri,
28
+ tags: ["external"],
29
+ aliases: [],
30
+ description: "",
31
+ external: true,
32
+ };
33
+ }
34
+
35
+ function boundedInteger(value, fallback, min, max) {
36
+ const parsed = Number(value);
37
+ if (!Number.isFinite(parsed)) {
38
+ return fallback;
39
+ }
40
+ return Math.max(min, Math.min(Math.floor(parsed), max));
41
+ }
42
+
43
+ function docsByFilter(index, options) {
44
+ const includeReserved = Boolean(options && options.includeReserved);
45
+ const docs = includeReserved ? index.documents : index.concepts;
46
+ if (!options || (!options.bundle && !options.type && !options.types && !options.tag && !options.tagsAny && !options.tagsAll && !options.pathPrefix)) {
47
+ return docs;
48
+ }
49
+ const conceptUris = new Set(applyFilters(index, options).map((doc) => doc.uri));
50
+ return docs.filter((doc) => conceptUris.has(doc.uri) || (includeReserved && doc.reserved));
51
+ }
52
+
53
+ function trimGraph(nodes, edges, options) {
54
+ const maxNodes = boundedInteger(options && options.maxNodes, 100, 1, 1000);
55
+ const maxEdges = boundedInteger(options && options.maxEdges, 300, 1, 5000);
56
+ const warnings = [];
57
+ let trimmedNodes = nodes;
58
+ let trimmedEdges = edges;
59
+ if (nodes.length > maxNodes) {
60
+ const allowed = new Set(nodes.slice(0, maxNodes).map((node) => node.id));
61
+ trimmedNodes = nodes.slice(0, maxNodes);
62
+ trimmedEdges = edges.filter((edge) => allowed.has(edge.source) && allowed.has(edge.target));
63
+ warnings.push(`Graph truncated to ${maxNodes} nodes; use narrower filters for full results.`);
64
+ }
65
+ if (trimmedEdges.length > maxEdges) {
66
+ trimmedEdges = trimmedEdges.slice(0, maxEdges);
67
+ warnings.push(`Graph truncated to ${maxEdges} edges; use narrower filters for full results.`);
68
+ }
69
+ return {
70
+ nodes: trimmedNodes,
71
+ edges: trimmedEdges,
72
+ warnings,
73
+ };
74
+ }
75
+
76
+ function canonicalUri(index, uri) {
77
+ const doc = uri ? index.byUri.get(uri) : null;
78
+ return doc ? doc.uri : uri;
79
+ }
80
+
81
+ function getGraph(index, options) {
82
+ const docs = docsByFilter(index, options || {});
83
+ const uris = new Set(docs.map((doc) => doc.uri));
84
+ const nodes = docs.map(nodeFor).sort((a, b) => a.id.localeCompare(b.id));
85
+ const includeExternal = Boolean(options && options.includeExternal);
86
+ const externalUris = new Set();
87
+ const edges = index.edges.filter((edge) => {
88
+ if (edge.broken || !uris.has(edge.source)) {
89
+ return false;
90
+ }
91
+ if (uris.has(edge.target)) {
92
+ return true;
93
+ }
94
+ if (includeExternal && edge.external) {
95
+ externalUris.add(edge.target);
96
+ return true;
97
+ }
98
+ return false;
99
+ });
100
+ externalUris.forEach((uri) => nodes.push(externalNodeFor(uri)));
101
+ return trimGraph(nodes, edges, options || {});
102
+ }
103
+
104
+ function getNeighbors(index, uri) {
105
+ const canonical = canonicalUri(index, uri);
106
+ const inbound = [];
107
+ const outbound = [];
108
+ index.edges.forEach((edge) => {
109
+ if (edge.source === canonical && index.byUri.has(edge.target)) {
110
+ outbound.push({ edge, node: nodeFor(index.byUri.get(edge.target)) });
111
+ } else if (edge.source === canonical && edge.external) {
112
+ outbound.push({ edge, node: externalNodeFor(edge.target) });
113
+ }
114
+ if (edge.target === canonical && index.byUri.has(edge.source)) {
115
+ inbound.push({ edge, node: nodeFor(index.byUri.get(edge.source)) });
116
+ }
117
+ });
118
+ return { uri: canonical, inbound, outbound };
119
+ }
120
+
121
+ function getSubgraph(index, options) {
122
+ const requestedSeeds = Array.isArray(options && options.seeds) ? options.seeds : [options && options.uri].filter(Boolean);
123
+ const seeds = Array.from(new Set(requestedSeeds.map((uri) => canonicalUri(index, uri))));
124
+ const depth = boundedInteger(options && options.depth, 1, 0, 10);
125
+ const maxNodes = boundedInteger(options && options.maxNodes, 50, 1, 1000);
126
+ const allowedUris = new Set((options && options.includeReserved ? index.documents : index.concepts).map((doc) => doc.uri));
127
+ const seen = new Set();
128
+ let frontier = seeds.filter((uri) => allowedUris.has(uri));
129
+ frontier.forEach((uri) => seen.add(uri));
130
+ for (let level = 0; level < depth && frontier.length && seen.size < maxNodes; level += 1) {
131
+ const next = [];
132
+ index.edges.filter((edge) => !edge.broken).forEach((edge) => {
133
+ if (frontier.includes(edge.source) && allowedUris.has(edge.target) && !seen.has(edge.target)) {
134
+ seen.add(edge.target);
135
+ next.push(edge.target);
136
+ }
137
+ if (frontier.includes(edge.target) && allowedUris.has(edge.source) && !seen.has(edge.source)) {
138
+ seen.add(edge.source);
139
+ next.push(edge.source);
140
+ }
141
+ });
142
+ frontier = next.slice(0, Math.max(0, maxNodes - seen.size));
143
+ }
144
+ const nodes = Array.from(seen).map((uri) => index.byUri.get(uri)).filter(Boolean).map(nodeFor);
145
+ const uris = new Set(nodes.map((node) => node.id));
146
+ const edges = index.edges.filter((edge) => !edge.broken && uris.has(edge.source) && uris.has(edge.target));
147
+ return trimGraph(nodes, edges, Object.assign({}, options, { maxNodes }));
148
+ }
149
+
150
+ function findPaths(index, source, target, maxPaths) {
151
+ const canonicalSource = canonicalUri(index, source);
152
+ const canonicalTarget = canonicalUri(index, target);
153
+ const limit = boundedInteger(maxPaths, 3, 1, 50);
154
+ const adjacency = new Map();
155
+ index.edges.filter((edge) => !edge.broken).forEach((edge) => {
156
+ if (!adjacency.has(edge.source)) {
157
+ adjacency.set(edge.source, []);
158
+ }
159
+ adjacency.get(edge.source).push(edge.target);
160
+ });
161
+ const queue = [[canonicalSource]];
162
+ const paths = [];
163
+ const bestDepth = new Map([[canonicalSource, 0]]);
164
+ while (queue.length && paths.length < limit) {
165
+ const path = queue.shift();
166
+ const last = path[path.length - 1];
167
+ if (last === canonicalTarget) {
168
+ paths.push(path);
169
+ continue;
170
+ }
171
+ for (const next of adjacency.get(last) || []) {
172
+ if (path.includes(next)) {
173
+ continue;
174
+ }
175
+ const nextDepth = path.length;
176
+ if (bestDepth.has(next) && bestDepth.get(next) < nextDepth) {
177
+ continue;
178
+ }
179
+ bestDepth.set(next, nextDepth);
180
+ queue.push(path.concat(next));
181
+ }
182
+ }
183
+ return { source: canonicalSource, target: canonicalTarget, paths };
184
+ }
185
+
186
+ function graphSummary(index) {
187
+ const byType = {};
188
+ const byTag = {};
189
+ const byBundle = {};
190
+ const byRelationType = {};
191
+ index.concepts.forEach((doc) => {
192
+ byType[doc.type] = (byType[doc.type] || 0) + 1;
193
+ byBundle[doc.bundle] = (byBundle[doc.bundle] || 0) + 1;
194
+ doc.tags.forEach((tag) => {
195
+ byTag[tag] = (byTag[tag] || 0) + 1;
196
+ });
197
+ });
198
+ const inbound = new Map();
199
+ const outbound = new Map();
200
+ index.edges.filter((edge) => !edge.broken).forEach((edge) => {
201
+ outbound.set(edge.source, (outbound.get(edge.source) || 0) + 1);
202
+ inbound.set(edge.target, (inbound.get(edge.target) || 0) + 1);
203
+ if (edge.kind === "relation") {
204
+ byRelationType[edge.relationType] = (byRelationType[edge.relationType] || 0) + 1;
205
+ }
206
+ });
207
+ const orphanConcepts = index.concepts
208
+ .filter((doc) => !inbound.get(doc.uri) && !outbound.get(doc.uri))
209
+ .map((doc) => doc.uri);
210
+ const topLinkedConcepts = index.concepts
211
+ .map((doc) => ({ uri: doc.uri, links: (inbound.get(doc.uri) || 0) + (outbound.get(doc.uri) || 0) }))
212
+ .filter((entry) => entry.links > 0)
213
+ .sort((a, b) => b.links - a.links || a.uri.localeCompare(b.uri))
214
+ .slice(0, 10);
215
+ return {
216
+ bundles: index.bundles.length,
217
+ documents: index.documents.length,
218
+ concepts: index.concepts.length,
219
+ reserved: index.reserved.length,
220
+ edges: index.edges.length,
221
+ brokenLinks: index.edges.filter((edge) => edge.kind === "markdown_link" && edge.broken).length,
222
+ brokenRelations: index.edges.filter((edge) => edge.kind === "relation" && edge.broken).length,
223
+ relations: index.edges.filter((edge) => edge.kind === "relation").length,
224
+ externalReferences: index.externalReferences ? index.externalReferences.length : 0,
225
+ byBundle,
226
+ byType,
227
+ byTag,
228
+ byRelationType,
229
+ orphanConcepts,
230
+ topLinkedConcepts,
231
+ warnings: index.warnings,
232
+ errors: index.errors,
233
+ };
234
+ }
235
+
236
+ function exportGraph(index, options) {
237
+ const graph = getGraph(index, options || {});
238
+ const format = String((options && options.format) || "json").toLowerCase();
239
+ if (format === "json") {
240
+ return JSON.stringify(graph, null, 2);
241
+ }
242
+ if (format === "dot") {
243
+ const dot = (value) => String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\\n");
244
+ const lines = ["digraph OKF {"];
245
+ graph.nodes.forEach((node) => {
246
+ lines.push(` "${dot(node.id)}" [label="${dot(node.title)}"];`);
247
+ });
248
+ graph.edges.forEach((edge) => {
249
+ lines.push(` "${dot(edge.source)}" -> "${dot(edge.target)}" [label="${dot(edge.text || edge.relationType || edge.kind)}"];`);
250
+ });
251
+ lines.push("}");
252
+ return lines.join("\n");
253
+ }
254
+ if (format === "mermaid") {
255
+ const mermaidLabel = (value) => String(value || "").replace(/"/g, "#quot;").replace(/\]/g, "#93;").replace(/\r?\n/g, " ");
256
+ const ids = new Map();
257
+ graph.nodes.forEach((node, index) => ids.set(node.id, `N${index + 1}`));
258
+ const lines = ["graph TD"];
259
+ graph.nodes.forEach((node) => {
260
+ lines.push(` ${ids.get(node.id)}["${mermaidLabel(node.title)}"]`);
261
+ });
262
+ graph.edges.forEach((edge) => {
263
+ lines.push(` ${ids.get(edge.source)} --> ${ids.get(edge.target)}`);
264
+ });
265
+ return lines.join("\n");
266
+ }
267
+ throw new Error(`Unsupported graph export format: ${format}`);
268
+ }
269
+
270
+ module.exports = {
271
+ exportGraph,
272
+ findPaths,
273
+ getGraph,
274
+ getNeighbors,
275
+ getSubgraph,
276
+ graphSummary,
277
+ nodeFor,
278
+ };