@daogee/mdgraph 1.0.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 (121) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README-ZH.md +203 -0
  4. package/README.md +203 -0
  5. package/agent-pack/README.md +26 -0
  6. package/agent-pack/host-examples.md +71 -0
  7. package/agent-pack/mcp-config.example.json +14 -0
  8. package/agent-pack/mdgraph-agent-instructions.md +21 -0
  9. package/agent-pack/prompts/relationship-trace.md +12 -0
  10. package/agent-pack/prompts/status-doctor.md +13 -0
  11. package/agent-pack/prompts/task-start-context.md +15 -0
  12. package/dist/analysis/doctor-scope.d.ts +8 -0
  13. package/dist/analysis/doctor-scope.js +109 -0
  14. package/dist/analysis/doctor.d.ts +148 -0
  15. package/dist/analysis/doctor.js +919 -0
  16. package/dist/analysis/status-freshness.d.ts +13 -0
  17. package/dist/analysis/status-freshness.js +55 -0
  18. package/dist/benchmark/benchmark.d.ts +118 -0
  19. package/dist/benchmark/benchmark.js +357 -0
  20. package/dist/bin/mdgraph.d.ts +2 -0
  21. package/dist/bin/mdgraph.js +877 -0
  22. package/dist/bundle/bundle.d.ts +66 -0
  23. package/dist/bundle/bundle.js +320 -0
  24. package/dist/config/limits.d.ts +24 -0
  25. package/dist/config/limits.js +24 -0
  26. package/dist/config/load-config.d.ts +14 -0
  27. package/dist/config/load-config.js +177 -0
  28. package/dist/db/connection.d.ts +15 -0
  29. package/dist/db/connection.js +145 -0
  30. package/dist/db/repositories.d.ts +159 -0
  31. package/dist/db/repositories.js +929 -0
  32. package/dist/db/schema.sql +110 -0
  33. package/dist/db/sqlite-adapter.d.ts +18 -0
  34. package/dist/db/sqlite-adapter.js +60 -0
  35. package/dist/diff/graph-diff.d.ts +41 -0
  36. package/dist/diff/graph-diff.js +334 -0
  37. package/dist/evaluation/retrieval-eval.d.ts +115 -0
  38. package/dist/evaluation/retrieval-eval.js +399 -0
  39. package/dist/export/diagram.d.ts +11 -0
  40. package/dist/export/diagram.js +41 -0
  41. package/dist/export/graphjson.d.ts +89 -0
  42. package/dist/export/graphjson.js +299 -0
  43. package/dist/export/markdown-index.d.ts +21 -0
  44. package/dist/export/markdown-index.js +89 -0
  45. package/dist/export/source-bridge.d.ts +22 -0
  46. package/dist/export/source-bridge.js +83 -0
  47. package/dist/extraction/entity-extractor.d.ts +12 -0
  48. package/dist/extraction/entity-extractor.js +153 -0
  49. package/dist/extraction/graph-builder.d.ts +2 -0
  50. package/dist/extraction/graph-builder.js +168 -0
  51. package/dist/index.d.ts +28 -0
  52. package/dist/index.js +28 -0
  53. package/dist/indexer.d.ts +19 -0
  54. package/dist/indexer.js +100 -0
  55. package/dist/mcp/debug.d.ts +7 -0
  56. package/dist/mcp/debug.js +41 -0
  57. package/dist/mcp/server-instructions.d.ts +2 -0
  58. package/dist/mcp/server-instructions.js +40 -0
  59. package/dist/mcp/server.d.ts +28 -0
  60. package/dist/mcp/server.js +232 -0
  61. package/dist/mcp/tools.d.ts +31 -0
  62. package/dist/mcp/tools.js +506 -0
  63. package/dist/mcp/transport.d.ts +50 -0
  64. package/dist/mcp/transport.js +88 -0
  65. package/dist/parser/frontmatter.d.ts +10 -0
  66. package/dist/parser/frontmatter.js +191 -0
  67. package/dist/parser/links.d.ts +6 -0
  68. package/dist/parser/links.js +9 -0
  69. package/dist/parser/markdown-parser.d.ts +2 -0
  70. package/dist/parser/markdown-parser.js +267 -0
  71. package/dist/query/context-builder.d.ts +85 -0
  72. package/dist/query/context-builder.js +413 -0
  73. package/dist/query/search.d.ts +32 -0
  74. package/dist/query/search.js +237 -0
  75. package/dist/query/trace.d.ts +10 -0
  76. package/dist/query/trace.js +55 -0
  77. package/dist/reporting/report.d.ts +49 -0
  78. package/dist/reporting/report.js +143 -0
  79. package/dist/resolution/link-resolver.d.ts +17 -0
  80. package/dist/resolution/link-resolver.js +113 -0
  81. package/dist/scanner/file-scanner.d.ts +4 -0
  82. package/dist/scanner/file-scanner.js +144 -0
  83. package/dist/semantic/local-embedding.d.ts +4 -0
  84. package/dist/semantic/local-embedding.js +30 -0
  85. package/dist/semantic/status.d.ts +19 -0
  86. package/dist/semantic/status.js +70 -0
  87. package/dist/semantic/vector-codec.d.ts +3 -0
  88. package/dist/semantic/vector-codec.js +35 -0
  89. package/dist/types.d.ts +198 -0
  90. package/dist/types.js +15 -0
  91. package/dist/utils/bounded-json.d.ts +9 -0
  92. package/dist/utils/bounded-json.js +57 -0
  93. package/dist/utils/content-risk.d.ts +5 -0
  94. package/dist/utils/content-risk.js +20 -0
  95. package/dist/utils/fts.d.ts +3 -0
  96. package/dist/utils/fts.js +52 -0
  97. package/dist/utils/id.d.ts +2 -0
  98. package/dist/utils/id.js +8 -0
  99. package/dist/utils/path-safety.d.ts +4 -0
  100. package/dist/utils/path-safety.js +25 -0
  101. package/dist/utils/text.d.ts +7 -0
  102. package/dist/utils/text.js +36 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +11 -0
  105. package/dist/watcher/file-watcher.d.ts +11 -0
  106. package/dist/watcher/file-watcher.js +127 -0
  107. package/docs/EN/Agent_Integration.md +129 -0
  108. package/docs/EN/Architecture.md +135 -0
  109. package/docs/EN/Evaluation_Questions.md +68 -0
  110. package/docs/EN/Output_Contracts.md +274 -0
  111. package/docs/EN/Public_Contracts.md +88 -0
  112. package/docs/EN/Public_Contracts_1.0.md +234 -0
  113. package/docs/EN/Release_Checklist.md +82 -0
  114. package/docs/ZH/Agent_Integration.md +105 -0
  115. package/docs/ZH/Architecture.md +124 -0
  116. package/docs/ZH/Evaluation_Questions.md +66 -0
  117. package/docs/ZH/Output_Contracts.md +269 -0
  118. package/docs/ZH/Public_Contracts.md +81 -0
  119. package/docs/ZH/Public_Contracts_1.0.md +202 -0
  120. package/docs/ZH/Release_Checklist.md +83 -0
  121. package/package.json +94 -0
@@ -0,0 +1,299 @@
1
+ import { canonicalJson, hashCanonical, sourceSnapshot } from "../bundle/bundle.js";
2
+ import { loadConfig } from "../config/load-config.js";
3
+ import { readBoundedJsonFile } from "../utils/bounded-json.js";
4
+ import { packageVersion } from "../version.js";
5
+ export const GRAPHJSON_FORMAT = "mdgraph-graphjson";
6
+ export const GRAPHJSON_FORMAT_VERSION = 1;
7
+ const NODE_KINDS = new Set(["document", "section", "entity", "source_ref"]);
8
+ const EDGE_KINDS = new Set([
9
+ "CONTAINS",
10
+ "DEFINES",
11
+ "REFERENCES",
12
+ "DEPENDS_ON",
13
+ "LINKS_TO",
14
+ "IMPLEMENTS",
15
+ "REFERENCES_SOURCE",
16
+ "SUPERSEDES",
17
+ "DEPRECATED_BY",
18
+ "SAME_AS",
19
+ "RELATED_TO",
20
+ "CONTRADICTS"
21
+ ]);
22
+ export function buildGraphJsonExport(projectRoot, repository) {
23
+ const documents = repository.allDocuments();
24
+ const sections = repository.allSections();
25
+ const entities = repository.allEntities();
26
+ const sourceRefs = repository.allSourceRefs();
27
+ const nodeIds = new Set();
28
+ const documentNodes = documents
29
+ .map((document) => ({
30
+ id: document.id,
31
+ kind: "document",
32
+ label: document.title,
33
+ path: document.path,
34
+ documentType: document.type,
35
+ status: document.status,
36
+ trustTier: document.trustTier
37
+ }))
38
+ .sort(compareDocumentNodes);
39
+ const pathByDocumentId = documentPathById(documents);
40
+ const sectionNodes = sections
41
+ .map((section) => ({
42
+ id: section.id,
43
+ kind: "section",
44
+ label: section.heading,
45
+ documentId: section.documentId,
46
+ anchor: section.anchor,
47
+ level: section.level,
48
+ lines: { start: section.startLine, end: section.endLine }
49
+ }))
50
+ .sort((left, right) => compareSectionNodes(left, right, pathByDocumentId));
51
+ const entityNodes = entities
52
+ .map((entity) => ({
53
+ id: entity.id,
54
+ kind: "entity",
55
+ label: entity.name,
56
+ entityKind: entity.kind,
57
+ normalizedName: entity.normalizedName,
58
+ namespace: entity.namespace
59
+ }))
60
+ .sort(compareEntityNodes);
61
+ const sourceRefNodes = sourceRefs
62
+ .map((sourceRef) => ({
63
+ id: sourceRef.id,
64
+ kind: "source_ref",
65
+ label: sourceRef.path,
66
+ path: sourceRef.path,
67
+ normalizedPath: sourceRef.normalizedPath
68
+ }))
69
+ .sort(compareSourceRefNodes);
70
+ const nodes = [...documentNodes, ...sectionNodes, ...entityNodes, ...sourceRefNodes];
71
+ for (const node of nodes) {
72
+ nodeIds.add(node.id);
73
+ }
74
+ const edges = repository.allEdges()
75
+ .filter((edge) => nodeIds.has(edge.fromId) && nodeIds.has(edge.toId))
76
+ .map((edge) => ({
77
+ id: edge.id,
78
+ fromId: edge.fromId,
79
+ toId: edge.toId,
80
+ kind: edge.kind,
81
+ weight: edge.weight,
82
+ confidence: edge.confidence,
83
+ provenance: edge.provenance
84
+ }))
85
+ .sort(compareEdges);
86
+ const counts = repository.counts();
87
+ const schema = repository.schemaMetadata();
88
+ const source = sourceSnapshot(loadConfig(projectRoot), documents.map((document) => ({ path: document.path, hash: document.hash })));
89
+ const withoutHash = {
90
+ format: GRAPHJSON_FORMAT,
91
+ formatVersion: GRAPHJSON_FORMAT_VERSION,
92
+ schemaVersion: schema.schemaVersion,
93
+ mdgraphVersion: packageVersion(),
94
+ exportProfile: "structural",
95
+ sourceHash: source.sourceHash,
96
+ counts,
97
+ exportedCounts: {
98
+ documents: documents.length,
99
+ sections: sections.length,
100
+ entities: entities.length,
101
+ sourceRefs: sourceRefs.length,
102
+ nodes: nodes.length,
103
+ edges: edges.length
104
+ },
105
+ nodes,
106
+ edges
107
+ };
108
+ return {
109
+ ...withoutHash,
110
+ graphHash: hashCanonical(withoutHash)
111
+ };
112
+ }
113
+ export function readGraphJsonFile(filePath) {
114
+ return readBoundedJsonFile(filePath, "GraphJSON file");
115
+ }
116
+ export function verifyGraphJsonExport(value) {
117
+ const errors = [];
118
+ const warnings = [];
119
+ if (!isRecord(value)) {
120
+ return {
121
+ valid: false,
122
+ errors: [verificationError("graphjson.not_object", "GraphJSON input must be a JSON object.", undefined, "Export with `mdgraph export graphjson --json`.")],
123
+ warnings
124
+ };
125
+ }
126
+ const format = typeof value.format === "string" ? value.format : undefined;
127
+ const formatVersion = typeof value.formatVersion === "number" ? value.formatVersion : undefined;
128
+ const schemaVersion = typeof value.schemaVersion === "number" ? value.schemaVersion : undefined;
129
+ const graphHash = typeof value.graphHash === "string" ? value.graphHash : undefined;
130
+ if (value.format !== GRAPHJSON_FORMAT) {
131
+ errors.push(verificationError("graphjson.format", "GraphJSON format must be mdgraph-graphjson.", String(value.format), "Use a MDGraph GraphJSON export."));
132
+ }
133
+ if (value.formatVersion !== GRAPHJSON_FORMAT_VERSION) {
134
+ errors.push(verificationError("graphjson.format_version", `Unsupported GraphJSON formatVersion: ${String(value.formatVersion)}.`, String(value.formatVersion), "Use formatVersion 1 or upgrade this MDGraph binary."));
135
+ }
136
+ if (typeof value.schemaVersion !== "number") {
137
+ errors.push(verificationError("graphjson.schema_version", "GraphJSON schemaVersion must be a number.", String(value.schemaVersion), "Re-export from an indexed MDGraph workspace."));
138
+ }
139
+ if (!isStatusCounts(value.counts)) {
140
+ errors.push(verificationError("graphjson.counts", "GraphJSON counts must include documents, sections, entities, sourceRefs, edges, chunks, and vectors.", undefined, "Re-export with the current MDGraph CLI."));
141
+ }
142
+ if (!isExportedCounts(value.exportedCounts)) {
143
+ errors.push(verificationError("graphjson.exported_counts", "GraphJSON exportedCounts must include documents, sections, entities, sourceRefs, nodes, and edges.", undefined, "Re-export with the current MDGraph CLI."));
144
+ }
145
+ if (!Array.isArray(value.nodes)) {
146
+ errors.push(verificationError("graphjson.nodes", "GraphJSON nodes must be an array.", undefined, "Re-export with the current MDGraph CLI."));
147
+ }
148
+ if (!Array.isArray(value.edges)) {
149
+ errors.push(verificationError("graphjson.edges", "GraphJSON edges must be an array.", undefined, "Re-export with the current MDGraph CLI."));
150
+ }
151
+ const nodes = Array.isArray(value.nodes) ? value.nodes : [];
152
+ const edges = Array.isArray(value.edges) ? value.edges : [];
153
+ const nodeIds = new Set();
154
+ for (const [index, node] of nodes.entries()) {
155
+ if (!isRecord(node) || typeof node.id !== "string" || typeof node.kind !== "string") {
156
+ errors.push(verificationError("graphjson.node_shape", "GraphJSON node must include string id and kind.", `nodes[${index}]`, "Re-export with the current MDGraph CLI."));
157
+ continue;
158
+ }
159
+ if (!NODE_KINDS.has(node.kind)) {
160
+ errors.push(verificationError("graphjson.node_kind", `Unsupported GraphJSON node kind: ${node.kind}.`, node.id, "Use a supported node kind or upgrade this MDGraph binary."));
161
+ }
162
+ if (nodeIds.has(node.id)) {
163
+ errors.push(verificationError("graphjson.node_duplicate", `Duplicate GraphJSON node id: ${node.id}.`, node.id, "Ensure every exported node id is unique."));
164
+ }
165
+ nodeIds.add(node.id);
166
+ }
167
+ for (const [index, edge] of edges.entries()) {
168
+ if (!isRecord(edge) || typeof edge.id !== "string" || typeof edge.fromId !== "string" || typeof edge.toId !== "string" || typeof edge.kind !== "string") {
169
+ errors.push(verificationError("graphjson.edge_shape", "GraphJSON edge must include string id, fromId, toId, and kind.", `edges[${index}]`, "Re-export with the current MDGraph CLI."));
170
+ continue;
171
+ }
172
+ if (!EDGE_KINDS.has(edge.kind)) {
173
+ errors.push(verificationError("graphjson.edge_kind", `Unsupported GraphJSON edge kind: ${edge.kind}.`, edge.id, "Use a supported edge kind or upgrade this MDGraph binary."));
174
+ }
175
+ if (!nodeIds.has(edge.fromId)) {
176
+ errors.push(verificationError("graphjson.edge_endpoint", `Edge ${edge.id} references missing fromId ${edge.fromId}.`, edge.id, "Verify the export is complete and not manually edited."));
177
+ }
178
+ if (!nodeIds.has(edge.toId)) {
179
+ errors.push(verificationError("graphjson.edge_endpoint", `Edge ${edge.id} references missing toId ${edge.toId}.`, edge.id, "Verify the export is complete and not manually edited."));
180
+ }
181
+ }
182
+ if (isExportedCounts(value.exportedCounts)) {
183
+ compareExportedCounts(value.exportedCounts, nodes, edges, errors);
184
+ }
185
+ if (isRecord(value.counts) && typeof value.counts.edges === "number" && typeof value.exportedCounts === "object" && isRecord(value.exportedCounts) && typeof value.exportedCounts.edges === "number" && value.exportedCounts.edges < value.counts.edges) {
186
+ warnings.push("Structural GraphJSON excludes chunk endpoint edges; counts.edges may be larger than exportedCounts.edges.");
187
+ }
188
+ if (graphHash) {
189
+ const recalculated = graphJsonHash(value);
190
+ if (recalculated !== graphHash) {
191
+ errors.push(verificationError("graphjson.graph_hash", "GraphJSON graphHash does not match the structural payload.", graphHash, "Re-export the graph or discard the modified file."));
192
+ }
193
+ }
194
+ else {
195
+ errors.push(verificationError("graphjson.graph_hash", "GraphJSON graphHash must be present.", undefined, "Re-export with the current MDGraph CLI."));
196
+ }
197
+ return {
198
+ valid: errors.length === 0,
199
+ errors,
200
+ warnings,
201
+ format,
202
+ formatVersion,
203
+ schemaVersion,
204
+ graphHash,
205
+ counts: isStatusCounts(value.counts) ? value.counts : undefined,
206
+ exportedCounts: isExportedCounts(value.exportedCounts) ? value.exportedCounts : undefined
207
+ };
208
+ }
209
+ export function graphJsonHash(value) {
210
+ const { graphHash: _graphHash, ...withoutHash } = value;
211
+ return hashCanonical(withoutHash);
212
+ }
213
+ export function formatGraphJsonVerification(result) {
214
+ const lines = [
215
+ "MDGraph GraphJSON verification",
216
+ `Valid: ${result.valid}`,
217
+ `Format: ${result.format ?? "unknown"} v${result.formatVersion ?? "unknown"}`,
218
+ `Schema: ${result.schemaVersion ?? "unknown"}`,
219
+ `Graph hash: ${result.graphHash ?? "missing"}`
220
+ ];
221
+ if (result.exportedCounts) {
222
+ lines.push(`Exported: ${result.exportedCounts.nodes} nodes, ${result.exportedCounts.edges} edges.`);
223
+ }
224
+ if (result.warnings.length) {
225
+ lines.push("Warnings:", ...result.warnings.map((warning) => `- ${warning}`));
226
+ }
227
+ if (result.errors.length) {
228
+ lines.push("Errors:", ...result.errors.map((error) => `- ${error.code}: ${error.message}`));
229
+ }
230
+ return lines.join("\n");
231
+ }
232
+ export function stableGraphJson(value) {
233
+ return `${canonicalJson(value)}\n`;
234
+ }
235
+ function documentPathById(documents) {
236
+ return new Map(documents.map((document) => [document.id, document.path]));
237
+ }
238
+ function compareDocumentNodes(left, right) {
239
+ return compareStrings(left.path, right.path) || compareStrings(left.id, right.id);
240
+ }
241
+ function compareSectionNodes(left, right, pathByDocumentId) {
242
+ return compareStrings(pathByDocumentId.get(left.documentId) ?? "", pathByDocumentId.get(right.documentId) ?? "")
243
+ || left.lines.start - right.lines.start
244
+ || compareStrings(left.id, right.id);
245
+ }
246
+ function compareEntityNodes(left, right) {
247
+ return compareStrings(left.entityKind, right.entityKind) || compareStrings(left.normalizedName, right.normalizedName) || compareStrings(left.id, right.id);
248
+ }
249
+ function compareSourceRefNodes(left, right) {
250
+ return compareStrings(left.normalizedPath, right.normalizedPath) || compareStrings(left.id, right.id);
251
+ }
252
+ function compareEdges(left, right) {
253
+ return compareStrings(left.fromId, right.fromId)
254
+ || compareStrings(left.toId, right.toId)
255
+ || compareStrings(left.kind, right.kind)
256
+ || compareStrings(left.id, right.id);
257
+ }
258
+ function compareStrings(left, right) {
259
+ return left.localeCompare(right);
260
+ }
261
+ function compareExportedCounts(expected, nodes, edges, errors) {
262
+ const byKind = new Map();
263
+ for (const node of nodes) {
264
+ if (isRecord(node) && typeof node.kind === "string") {
265
+ byKind.set(node.kind, (byKind.get(node.kind) ?? 0) + 1);
266
+ }
267
+ }
268
+ const actual = {
269
+ documents: byKind.get("document") ?? 0,
270
+ sections: byKind.get("section") ?? 0,
271
+ entities: byKind.get("entity") ?? 0,
272
+ sourceRefs: byKind.get("source_ref") ?? 0,
273
+ nodes: nodes.length,
274
+ edges: edges.length
275
+ };
276
+ for (const key of Object.keys(expected)) {
277
+ if (expected[key] !== actual[key]) {
278
+ errors.push(verificationError("graphjson.count_mismatch", `exportedCounts.${key} is ${expected[key]}, but export contains ${actual[key]}.`, key, "Re-export the graph or fix the counts."));
279
+ }
280
+ }
281
+ }
282
+ function verificationError(code, message, evidence, remediation) {
283
+ return { code, message, evidence, remediation };
284
+ }
285
+ function isRecord(value) {
286
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
287
+ }
288
+ function isStatusCounts(value) {
289
+ if (!isRecord(value)) {
290
+ return false;
291
+ }
292
+ return ["documents", "sections", "entities", "sourceRefs", "edges", "chunks", "vectors"].every((key) => typeof value[key] === "number");
293
+ }
294
+ function isExportedCounts(value) {
295
+ if (!isRecord(value)) {
296
+ return false;
297
+ }
298
+ return ["documents", "sections", "entities", "sourceRefs", "nodes", "edges"].every((key) => typeof value[key] === "number");
299
+ }
@@ -0,0 +1,21 @@
1
+ import type { GraphJsonExport } from "./graphjson.js";
2
+ export interface DocsSiteIndex {
3
+ format: "mdgraph-docsite-index";
4
+ formatVersion: 1;
5
+ sourceFormat: "mdgraph-graphjson";
6
+ graphHash: string;
7
+ documents: DocsSiteDocument[];
8
+ }
9
+ export interface DocsSiteDocument {
10
+ path: string;
11
+ title: string;
12
+ status: string;
13
+ documentType: string;
14
+ trustTier: string;
15
+ defines: string[];
16
+ sourceRefs: string[];
17
+ outboundLinks: string[];
18
+ inboundLinks: string[];
19
+ }
20
+ export declare function buildDocsSiteIndex(graph: GraphJsonExport): DocsSiteIndex;
21
+ export declare function formatWikiLinkMarkdownIndex(graph: GraphJsonExport): string;
@@ -0,0 +1,89 @@
1
+ export function buildDocsSiteIndex(graph) {
2
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
3
+ const owningDocumentByNode = owningDocumentMap(graph.nodes);
4
+ const documents = graph.nodes
5
+ .filter((node) => node.kind === "document")
6
+ .map((document) => documentSummary(document, graph.edges, nodesById, owningDocumentByNode))
7
+ .sort((left, right) => left.path.localeCompare(right.path));
8
+ return {
9
+ format: "mdgraph-docsite-index",
10
+ formatVersion: 1,
11
+ sourceFormat: graph.format,
12
+ graphHash: graph.graphHash,
13
+ documents
14
+ };
15
+ }
16
+ export function formatWikiLinkMarkdownIndex(graph) {
17
+ const index = buildDocsSiteIndex(graph);
18
+ const lines = [
19
+ "# MDGraph Index",
20
+ "",
21
+ `Graph hash: \`${graph.graphHash}\``,
22
+ "",
23
+ "## Documents"
24
+ ];
25
+ for (const document of index.documents) {
26
+ lines.push("", `### [[${document.path}]]`, "", `- Status: ${document.status}`, `- Type: ${document.documentType}`, `- Trust tier: ${document.trustTier}`, `- Defines: ${formatList(document.defines)}`, `- Source refs: ${formatList(document.sourceRefs)}`, `- Outbound links: ${formatList(document.outboundLinks)}`, `- Inbound links: ${formatList(document.inboundLinks)}`);
27
+ }
28
+ return `${lines.join("\n")}\n`;
29
+ }
30
+ function documentSummary(document, edges, nodesById, owningDocumentByNode) {
31
+ const defines = new Set();
32
+ const sourceRefs = new Set();
33
+ const outboundLinks = new Set();
34
+ const inboundLinks = new Set();
35
+ for (const edge of edges) {
36
+ const fromDocument = owningDocumentByNode.get(edge.fromId);
37
+ const toDocument = owningDocumentByNode.get(edge.toId);
38
+ const toNode = nodesById.get(edge.toId);
39
+ const fromNode = nodesById.get(edge.fromId);
40
+ if (fromDocument === document.id && edge.kind === "DEFINES" && toNode?.kind === "entity") {
41
+ defines.add(toNode.label);
42
+ }
43
+ if (fromDocument === document.id && (edge.kind === "IMPLEMENTS" || edge.kind === "REFERENCES_SOURCE") && toNode?.kind === "source_ref") {
44
+ sourceRefs.add(toNode.path);
45
+ }
46
+ if (fromDocument === document.id && toDocument && toDocument !== document.id) {
47
+ outboundLinks.add(labelForDocument(nodesById, toDocument));
48
+ }
49
+ if (toDocument === document.id && fromDocument && fromDocument !== document.id) {
50
+ inboundLinks.add(labelForDocument(nodesById, fromDocument));
51
+ }
52
+ if (edge.toId === document.id && fromNode?.kind === "document") {
53
+ inboundLinks.add(fromNode.path);
54
+ }
55
+ }
56
+ return {
57
+ path: document.path,
58
+ title: document.label,
59
+ status: document.status,
60
+ documentType: document.documentType,
61
+ trustTier: document.trustTier,
62
+ defines: sorted(defines),
63
+ sourceRefs: sorted(sourceRefs),
64
+ outboundLinks: sorted(outboundLinks),
65
+ inboundLinks: sorted(inboundLinks)
66
+ };
67
+ }
68
+ function owningDocumentMap(nodes) {
69
+ const map = new Map();
70
+ for (const node of nodes) {
71
+ if (node.kind === "document") {
72
+ map.set(node.id, node.id);
73
+ }
74
+ else if (node.kind === "section") {
75
+ map.set(node.id, node.documentId);
76
+ }
77
+ }
78
+ return map;
79
+ }
80
+ function labelForDocument(nodesById, documentId) {
81
+ const node = nodesById.get(documentId);
82
+ return node?.kind === "document" ? node.path : documentId;
83
+ }
84
+ function sorted(values) {
85
+ return [...values].sort((left, right) => left.localeCompare(right));
86
+ }
87
+ function formatList(values) {
88
+ return values.length ? values.map((value) => `\`${value}\``).join(", ") : "none";
89
+ }
@@ -0,0 +1,22 @@
1
+ import type { GraphRepository } from "../db/repositories.js";
2
+ export interface SourceBridgeReport {
3
+ format: "mdgraph-source-bridge";
4
+ formatVersion: 1;
5
+ provider: "json";
6
+ status: "ready" | "unsupported";
7
+ reason?: string;
8
+ sourceRefs: number;
9
+ matched: SourceBridgeMatch[];
10
+ unmatched: string[];
11
+ }
12
+ export interface SourceBridgeMatch {
13
+ sourceRef: string;
14
+ artifactPath: string;
15
+ symbols: Array<{
16
+ name: string;
17
+ kind?: string;
18
+ }>;
19
+ }
20
+ export declare function buildSourceBridgeReport(repository: GraphRepository, options?: {
21
+ artifact?: string;
22
+ }): SourceBridgeReport;
@@ -0,0 +1,83 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readBoundedJsonFile } from "../utils/bounded-json.js";
4
+ import { normalizePath } from "../utils/text.js";
5
+ export function buildSourceBridgeReport(repository, options = {}) {
6
+ const sourceRefs = repository.allSourceRefs();
7
+ if (!options.artifact) {
8
+ return {
9
+ format: "mdgraph-source-bridge",
10
+ formatVersion: 1,
11
+ provider: "json",
12
+ status: "unsupported",
13
+ reason: "No source bridge artifact supplied; pass --artifact <file> to inspect a read-only JSON bridge.",
14
+ sourceRefs: sourceRefs.length,
15
+ matched: [],
16
+ unmatched: sourceRefs.map((sourceRef) => sourceRef.path)
17
+ };
18
+ }
19
+ const artifactPath = path.resolve(options.artifact);
20
+ if (!fs.existsSync(artifactPath)) {
21
+ return {
22
+ format: "mdgraph-source-bridge",
23
+ formatVersion: 1,
24
+ provider: "json",
25
+ status: "unsupported",
26
+ reason: `Source bridge artifact not found: ${options.artifact}`,
27
+ sourceRefs: sourceRefs.length,
28
+ matched: [],
29
+ unmatched: sourceRefs.map((sourceRef) => sourceRef.path)
30
+ };
31
+ }
32
+ let artifact;
33
+ try {
34
+ artifact = readBoundedJsonFile(artifactPath, "source bridge artifact");
35
+ }
36
+ catch (error) {
37
+ return {
38
+ format: "mdgraph-source-bridge",
39
+ formatVersion: 1,
40
+ provider: "json",
41
+ status: "unsupported",
42
+ reason: `Source bridge artifact could not be parsed: ${error instanceof Error ? error.message : String(error)}`,
43
+ sourceRefs: sourceRefs.length,
44
+ matched: [],
45
+ unmatched: sourceRefs.map((sourceRef) => sourceRef.path)
46
+ };
47
+ }
48
+ const files = new Map();
49
+ for (const file of artifact.files ?? []) {
50
+ if (typeof file.path === "string") {
51
+ files.set(normalizePath(file.path).toLowerCase(), file);
52
+ }
53
+ }
54
+ const matched = [];
55
+ const unmatched = [];
56
+ for (const sourceRef of sourceRefs) {
57
+ const file = files.get(sourceRef.normalizedPath);
58
+ if (!file || typeof file.path !== "string") {
59
+ unmatched.push(sourceRef.path);
60
+ continue;
61
+ }
62
+ matched.push({
63
+ sourceRef: sourceRef.path,
64
+ artifactPath: normalizePath(file.path),
65
+ symbols: (file.symbols ?? [])
66
+ .filter((symbol) => typeof symbol.name === "string")
67
+ .map((symbol) => ({
68
+ name: String(symbol.name),
69
+ kind: typeof symbol.kind === "string" ? symbol.kind : undefined
70
+ }))
71
+ .sort((left, right) => left.name.localeCompare(right.name) || String(left.kind ?? "").localeCompare(String(right.kind ?? "")))
72
+ });
73
+ }
74
+ return {
75
+ format: "mdgraph-source-bridge",
76
+ formatVersion: 1,
77
+ provider: "json",
78
+ status: "ready",
79
+ sourceRefs: sourceRefs.length,
80
+ matched: matched.sort((left, right) => left.sourceRef.localeCompare(right.sourceRef)),
81
+ unmatched: unmatched.sort((left, right) => left.localeCompare(right))
82
+ };
83
+ }
@@ -0,0 +1,12 @@
1
+ import type { EntityKind, MDGraphConfig, ParsedDocument, Provenance } from "../types.js";
2
+ export interface ExtractedEntity {
3
+ name: string;
4
+ kind: EntityKind;
5
+ role: "definition" | "reference";
6
+ provenance: Provenance;
7
+ confidence: number;
8
+ sectionId?: string;
9
+ metadata?: Record<string, unknown>;
10
+ }
11
+ export declare function extractEntities(document: ParsedDocument, config: MDGraphConfig): ExtractedEntity[];
12
+ export declare function inferEntityKind(name: string): EntityKind;
@@ -0,0 +1,153 @@
1
+ import { normalizeEntityName, uniqueStrings } from "../utils/text.js";
2
+ const apiRoutePattern = /\b(?:GET|POST|PUT|PATCH|DELETE)\s+\/[A-Za-z0-9_./:{}-]+|\/[A-Za-z0-9_./:{}-]+/g;
3
+ const errorCodePattern = /\b(?:[A-Z][A-Za-z0-9]+Error|ERR_[A-Z0-9_]+|[A-Z]+_[0-9]{3,}|[A-Z]+_[A-Z0-9_]*ERROR[A-Z0-9_]*)\b/g;
4
+ const configKeyPattern = /\b(?:[A-Z][A-Z0-9_]{2,}|[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,})\b/g;
5
+ const filePathPattern = /(?:^|\s)([\w@.-]+\/[\w@./-]+\.(?:ts|tsx|js|jsx|md|mdx|json|yaml|yml|toml|rs|go|py|java|cs|sql))/g;
6
+ const commandPattern = /\b(?:npm|pnpm|yarn|go|cargo|docker|kubectl|node|npx)\s+[^\n`]+/g;
7
+ const functionPattern = /\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?\(\)/g;
8
+ const symbolPattern = /\b[A-Z][A-Za-z0-9]+(?:\.[A-Za-z_$][\w$]*)?\b/g;
9
+ export function extractEntities(document, config) {
10
+ const stopEntities = new Set(config.entities.stopEntities.map(normalizeEntityName));
11
+ const entities = [];
12
+ for (const name of document.frontmatter.defines ?? []) {
13
+ pushEntity(entities, name, "definition", "frontmatter", 1, undefined, stopEntities, true);
14
+ }
15
+ for (const section of document.sections) {
16
+ if (isDefinesHeading(section.heading)) {
17
+ for (const name of extractDeclaredDefinitionNames(section.content)) {
18
+ pushEntity(entities, name, "definition", "declared_section", 0.85, section.id, stopEntities, true);
19
+ }
20
+ }
21
+ if (looksLikeEntity(section.heading)) {
22
+ pushEntity(entities, section.heading, "definition", "heading", 0.8, section.id, stopEntities, true);
23
+ }
24
+ for (const name of extractHighConfidenceReferences(section.content)) {
25
+ pushEntity(entities, name, "reference", "regex", 0.6, section.id, stopEntities, false);
26
+ }
27
+ }
28
+ for (const snippet of document.inlineCode) {
29
+ for (const name of extractStructuredNames(snippet.value, true)) {
30
+ pushEntity(entities, name, "reference", "inline_code", 0.75, snippet.sectionId, stopEntities, false);
31
+ }
32
+ }
33
+ for (const snippet of document.codeBlocks) {
34
+ for (const name of extractStructuredNames(snippet.value, true)) {
35
+ pushEntity(entities, name, "reference", "code_block", 0.7, snippet.sectionId, stopEntities, false);
36
+ }
37
+ }
38
+ for (const link of document.markdownLinks) {
39
+ for (const name of extractStructuredNames(`${link.text} ${link.url}`, false)) {
40
+ pushEntity(entities, name, "reference", "markdown_link", 0.7, link.sectionId, stopEntities, false);
41
+ }
42
+ }
43
+ for (const link of document.wikiLinks) {
44
+ const label = link.alias ?? link.target;
45
+ if (looksLikeEntity(label)) {
46
+ pushEntity(entities, label, "reference", "wikilink", 0.7, link.sectionId, stopEntities, false);
47
+ }
48
+ }
49
+ return dedupeEntities(entities).filter((entity) => config.entities.enabledKinds.includes(entity.kind));
50
+ }
51
+ export function inferEntityKind(name) {
52
+ const trimmed = name.trim();
53
+ if (/^(?:GET|POST|PUT|PATCH|DELETE)\s+\//.test(trimmed) || trimmed.startsWith("/")) {
54
+ return "api_route";
55
+ }
56
+ if (filePathPattern.test(` ${trimmed}`)) {
57
+ filePathPattern.lastIndex = 0;
58
+ return "file_path";
59
+ }
60
+ filePathPattern.lastIndex = 0;
61
+ if (/^(?:npm|pnpm|yarn|go|cargo|docker|kubectl|node|npx)\s+/.test(trimmed)) {
62
+ return "command";
63
+ }
64
+ if (errorCodePattern.test(trimmed)) {
65
+ errorCodePattern.lastIndex = 0;
66
+ return "error_code";
67
+ }
68
+ errorCodePattern.lastIndex = 0;
69
+ if (/^[A-Z][A-Z0-9_]{2,}$/.test(trimmed) || /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,}$/.test(trimmed)) {
70
+ return "config_key";
71
+ }
72
+ if (/^@?[a-z0-9_.-]+\/[a-z0-9_.-]+$/.test(trimmed)) {
73
+ return "package";
74
+ }
75
+ if (/^ADR-?\d+$/i.test(trimmed)) {
76
+ return "decision";
77
+ }
78
+ return "symbol";
79
+ }
80
+ function pushEntity(target, rawName, role, provenance, confidence, sectionId, stopEntities, allowStopEntity) {
81
+ const name = cleanupName(rawName);
82
+ if (!name) {
83
+ return;
84
+ }
85
+ const kind = inferEntityKind(name);
86
+ if (!allowStopEntity && kind === "symbol" && stopEntities.has(normalizeEntityName(name))) {
87
+ return;
88
+ }
89
+ target.push({ name, kind, role, provenance, confidence, sectionId });
90
+ }
91
+ function extractDeclaredDefinitionNames(content) {
92
+ const names = [];
93
+ for (const match of content.matchAll(/[-*]\s+`([^`]+)`/g)) {
94
+ names.push(match[1]);
95
+ }
96
+ for (const match of content.matchAll(/^[-*]\s+([A-Za-z0-9_.:/-]+)\s*:/gm)) {
97
+ names.push(match[1]);
98
+ }
99
+ return uniqueStrings(names);
100
+ }
101
+ function extractHighConfidenceReferences(content) {
102
+ return uniqueStrings([
103
+ ...matches(content, apiRoutePattern),
104
+ ...matches(content, errorCodePattern),
105
+ ...matches(content, configKeyPattern)
106
+ ]);
107
+ }
108
+ function extractStructuredNames(content, includeSymbols) {
109
+ const names = [
110
+ ...matches(content, apiRoutePattern),
111
+ ...matches(content, errorCodePattern),
112
+ ...matches(content, configKeyPattern),
113
+ ...matches(content, commandPattern),
114
+ ...matches(content, functionPattern),
115
+ ...matches(content, filePathPattern, 1)
116
+ ];
117
+ if (includeSymbols) {
118
+ names.push(...matches(content, symbolPattern));
119
+ }
120
+ return uniqueStrings(names);
121
+ }
122
+ function matches(content, pattern, group = 0) {
123
+ pattern.lastIndex = 0;
124
+ const result = [...content.matchAll(pattern)].map((match) => match[group] ?? match[0]);
125
+ pattern.lastIndex = 0;
126
+ return result;
127
+ }
128
+ function isDefinesHeading(heading) {
129
+ return /^(defines?|definitions?|定义)$/i.test(heading.trim());
130
+ }
131
+ function looksLikeEntity(value) {
132
+ const trimmed = cleanupName(value);
133
+ return Boolean(trimmed) && (/^\/[A-Za-z0-9_./:{}-]+$/.test(trimmed) ||
134
+ /^(?:GET|POST|PUT|PATCH|DELETE)\s+\//.test(trimmed) ||
135
+ /^[A-Z][A-Za-z0-9]+(?:\.[A-Za-z_$][\w$]*)?$/.test(trimmed) ||
136
+ /^[A-Z][A-Z0-9_]{2,}$/.test(trimmed) ||
137
+ /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,}$/.test(trimmed));
138
+ }
139
+ function cleanupName(value) {
140
+ return value.trim().replace(/^`|`$/g, "").replace(/[.,;:]$/g, "");
141
+ }
142
+ function dedupeEntities(entities) {
143
+ const seen = new Set();
144
+ const deduped = [];
145
+ for (const entity of entities) {
146
+ const key = `${entity.role}:${entity.kind}:${normalizeEntityName(entity.name)}:${entity.sectionId ?? "doc"}:${entity.provenance}`;
147
+ if (!seen.has(key)) {
148
+ seen.add(key);
149
+ deduped.push(entity);
150
+ }
151
+ }
152
+ return deduped;
153
+ }