@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,66 @@
1
+ import { type StatusCounts } from "../db/repositories.js";
2
+ import type { MDGraphConfig } from "../types.js";
3
+ export type BundleVisibility = "private";
4
+ export interface BundleDocumentManifestEntry {
5
+ path: string;
6
+ hash: string;
7
+ }
8
+ export interface SourceSnapshot {
9
+ configHash: string;
10
+ documents: BundleDocumentManifestEntry[];
11
+ documentsHash: string;
12
+ sourceHash: string;
13
+ }
14
+ export interface GraphBundleManifest {
15
+ format: "mdgraph-bundle";
16
+ formatVersion: 1;
17
+ schemaVersion: number;
18
+ mdgraphVersion: string;
19
+ createdAt: string;
20
+ visibility: BundleVisibility;
21
+ sourceHash: string;
22
+ configHash: string;
23
+ provenance: {
24
+ command: string;
25
+ gitRevision?: string;
26
+ gitDirty?: boolean;
27
+ indexedAt: string;
28
+ };
29
+ counts: StatusCounts;
30
+ documents: {
31
+ count: number;
32
+ hash: string;
33
+ };
34
+ reports?: Record<string, {
35
+ path: string;
36
+ sha256: string;
37
+ }>;
38
+ }
39
+ export interface BundleCreateResult {
40
+ bundleDir: string;
41
+ manifestPath: string;
42
+ manifest: GraphBundleManifest;
43
+ }
44
+ export interface BundleVerificationResult {
45
+ bundleDir: string;
46
+ valid: boolean;
47
+ errors: string[];
48
+ manifest?: GraphBundleManifest;
49
+ counts?: StatusCounts;
50
+ schemaVersion?: number;
51
+ sourceHash?: string;
52
+ configHash?: string;
53
+ freshness: {
54
+ state: "fresh" | "stale" | "unknown";
55
+ reason: string;
56
+ };
57
+ }
58
+ export declare function createGraphBundle(projectRoot: string, options?: {
59
+ profile?: string;
60
+ }): Promise<BundleCreateResult>;
61
+ export declare function verifyGraphBundle(bundleDir: string, options?: {
62
+ projectRoot?: string;
63
+ }): BundleVerificationResult;
64
+ export declare function sourceSnapshot(config: MDGraphConfig, documents: BundleDocumentManifestEntry[]): SourceSnapshot;
65
+ export declare function hashCanonical(value: unknown): string;
66
+ export declare function canonicalJson(value: unknown): string;
@@ -0,0 +1,320 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { databasePath, loadConfig } from "../config/load-config.js";
6
+ import { createDatabase } from "../db/sqlite-adapter.js";
7
+ import { openExistingDatabase } from "../db/connection.js";
8
+ import { GraphRepository } from "../db/repositories.js";
9
+ import { readBoundedJsonFile } from "../utils/bounded-json.js";
10
+ import { packageVersion } from "../version.js";
11
+ export async function createGraphBundle(projectRoot, options = {}) {
12
+ const profile = options.profile ?? "private";
13
+ if (profile !== "private") {
14
+ throw new Error(`Unsupported bundle profile: ${profile}. MDGraph 0.6 only supports private directory bundles.`);
15
+ }
16
+ const resolvedRoot = path.resolve(projectRoot);
17
+ const dbPath = databasePath(resolvedRoot);
18
+ if (!fs.existsSync(dbPath)) {
19
+ throw new Error(`MDGraph database not found at ${dbPath}. Run \`mdgraph index\` before creating a bundle.`);
20
+ }
21
+ const config = loadConfig(resolvedRoot);
22
+ const repository = new GraphRepository(openExistingDatabase(resolvedRoot));
23
+ let manifest;
24
+ let statusStorageReport;
25
+ try {
26
+ const counts = repository.counts();
27
+ const storage = repository.storageDiagnostics();
28
+ const schema = repository.schemaMetadata();
29
+ const source = sourceSnapshot(config, repository.allDocuments().map((document) => ({ path: document.path, hash: document.hash })));
30
+ const createdAt = new Date().toISOString();
31
+ statusStorageReport = { counts, storage };
32
+ manifest = {
33
+ format: "mdgraph-bundle",
34
+ formatVersion: 1,
35
+ schemaVersion: schema.schemaVersion,
36
+ mdgraphVersion: packageVersion(),
37
+ createdAt,
38
+ visibility: "private",
39
+ sourceHash: source.sourceHash,
40
+ configHash: source.configHash,
41
+ provenance: {
42
+ command: "mdgraph bundle create --profile private",
43
+ gitRevision: gitRevision(resolvedRoot),
44
+ gitDirty: gitDirty(resolvedRoot),
45
+ indexedAt: repository.latestIndexedAt() ?? createdAt
46
+ },
47
+ counts,
48
+ documents: {
49
+ count: source.documents.length,
50
+ hash: source.documentsHash
51
+ }
52
+ };
53
+ repository.checkpointStorage();
54
+ }
55
+ finally {
56
+ repository.close();
57
+ }
58
+ const bundleDir = path.join(resolvedRoot, ".mdgraph", "bundles", "private", safeTimestamp(manifest.createdAt));
59
+ const reportsDir = path.join(bundleDir, "reports");
60
+ fs.mkdirSync(reportsDir, { recursive: true });
61
+ const configSnapshotPath = path.join(bundleDir, "config.json");
62
+ fs.writeFileSync(configSnapshotPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
63
+ fs.copyFileSync(dbPath, path.join(bundleDir, "graph.db"));
64
+ const reportPath = path.join(reportsDir, "status-storage.json");
65
+ writeJson(reportPath, statusStorageReport);
66
+ manifest.reports = {
67
+ "status-storage": {
68
+ path: "reports/status-storage.json",
69
+ sha256: fileHash(reportPath)
70
+ }
71
+ };
72
+ const manifestPath = path.join(bundleDir, "manifest.json");
73
+ writeJson(manifestPath, manifest);
74
+ return { bundleDir, manifestPath, manifest };
75
+ }
76
+ export function verifyGraphBundle(bundleDir, options = {}) {
77
+ const resolvedBundleDir = path.resolve(bundleDir);
78
+ const errors = [];
79
+ const manifestPath = path.join(resolvedBundleDir, "manifest.json");
80
+ const graphPath = path.join(resolvedBundleDir, "graph.db");
81
+ const configSnapshotPath = path.join(resolvedBundleDir, "config.json");
82
+ const graphExists = fs.existsSync(graphPath);
83
+ const configExists = fs.existsSync(configSnapshotPath);
84
+ const manifest = readManifest(manifestPath, errors);
85
+ if (!graphExists) {
86
+ errors.push("Missing graph.db.");
87
+ }
88
+ if (!configExists) {
89
+ errors.push("Missing config.json.");
90
+ }
91
+ if (!manifest) {
92
+ return {
93
+ bundleDir: resolvedBundleDir,
94
+ valid: false,
95
+ errors,
96
+ freshness: { state: "unknown", reason: "manifest could not be read" }
97
+ };
98
+ }
99
+ validateManifestShape(manifest, errors);
100
+ let counts;
101
+ let schemaVersion;
102
+ let sourceHash;
103
+ let configHash;
104
+ if (graphExists && configExists) {
105
+ try {
106
+ const config = readJsonFile(configSnapshotPath);
107
+ const db = createDatabase(graphPath);
108
+ const repository = new GraphRepository(db);
109
+ try {
110
+ counts = repository.counts();
111
+ schemaVersion = repository.schemaMetadata().schemaVersion;
112
+ const source = sourceSnapshot(config, repository.allDocuments().map((document) => ({ path: document.path, hash: document.hash })));
113
+ sourceHash = source.sourceHash;
114
+ configHash = source.configHash;
115
+ if (sourceHash !== manifest.sourceHash) {
116
+ errors.push("Manifest sourceHash does not match bundled config and document hashes.");
117
+ }
118
+ if (configHash !== manifest.configHash) {
119
+ errors.push("Manifest configHash does not match bundled config.json.");
120
+ }
121
+ if (schemaVersion !== manifest.schemaVersion) {
122
+ errors.push(`Manifest schemaVersion ${manifest.schemaVersion} does not match bundled database schemaVersion ${schemaVersion}.`);
123
+ }
124
+ if (isStatusCounts(manifest.counts)) {
125
+ compareCounts(manifest.counts, counts, errors);
126
+ }
127
+ if (isDocumentSummary(manifest.documents)) {
128
+ if (source.documentsHash !== manifest.documents.hash) {
129
+ errors.push("Manifest documents hash does not match bundled database documents.");
130
+ }
131
+ if (source.documents.length !== manifest.documents.count) {
132
+ errors.push(`Manifest document count ${manifest.documents.count} does not match bundled database document count ${source.documents.length}.`);
133
+ }
134
+ }
135
+ }
136
+ finally {
137
+ repository.close();
138
+ }
139
+ }
140
+ catch (error) {
141
+ errors.push(`Failed to inspect bundled graph.db: ${errorMessage(error)}`);
142
+ }
143
+ }
144
+ if (manifest.reports) {
145
+ for (const [name, report] of Object.entries(manifest.reports)) {
146
+ const reportPath = resolveBundlePath(resolvedBundleDir, report.path);
147
+ if (!reportPath) {
148
+ errors.push(`Invalid report path for ${name}: ${String(report.path)}.`);
149
+ continue;
150
+ }
151
+ if (!fs.existsSync(reportPath)) {
152
+ errors.push(`Missing report ${name}: ${report.path}.`);
153
+ }
154
+ else if (fileHash(reportPath) !== report.sha256) {
155
+ errors.push(`Report hash mismatch for ${name}.`);
156
+ }
157
+ }
158
+ }
159
+ const freshness = bundleFreshness(manifest, options.projectRoot);
160
+ return {
161
+ bundleDir: resolvedBundleDir,
162
+ valid: errors.length === 0,
163
+ errors,
164
+ manifest,
165
+ counts,
166
+ schemaVersion,
167
+ sourceHash,
168
+ configHash,
169
+ freshness
170
+ };
171
+ }
172
+ export function sourceSnapshot(config, documents) {
173
+ const sortedDocuments = [...documents].sort((left, right) => left.path.localeCompare(right.path));
174
+ const configHash = hashCanonical(config);
175
+ const documentsHash = hashCanonical(sortedDocuments);
176
+ const sourceHash = hashCanonical({ configHash, documents: sortedDocuments });
177
+ return { configHash, documents: sortedDocuments, documentsHash, sourceHash };
178
+ }
179
+ export function hashCanonical(value) {
180
+ return hashString(canonicalJson(value));
181
+ }
182
+ export function canonicalJson(value) {
183
+ return JSON.stringify(canonicalize(value));
184
+ }
185
+ function canonicalize(value) {
186
+ if (Array.isArray(value)) {
187
+ return value.map(canonicalize);
188
+ }
189
+ if (value && typeof value === "object") {
190
+ const record = value;
191
+ return Object.fromEntries(Object.keys(record).sort().map((key) => [key, canonicalize(record[key])]));
192
+ }
193
+ return value;
194
+ }
195
+ function bundleFreshness(manifest, projectRoot) {
196
+ if (!projectRoot) {
197
+ return { state: "unknown", reason: "no project root supplied" };
198
+ }
199
+ const resolvedRoot = path.resolve(projectRoot);
200
+ const dbPath = databasePath(resolvedRoot);
201
+ if (!fs.existsSync(dbPath)) {
202
+ return { state: "unknown", reason: "current workspace is not indexed" };
203
+ }
204
+ try {
205
+ const config = loadConfig(resolvedRoot);
206
+ const repository = new GraphRepository(openExistingDatabase(resolvedRoot));
207
+ try {
208
+ const current = sourceSnapshot(config, repository.allDocuments().map((document) => ({ path: document.path, hash: document.hash })));
209
+ return current.sourceHash === manifest.sourceHash
210
+ ? { state: "fresh", reason: "bundle source hash matches current workspace index" }
211
+ : { state: "stale", reason: "bundle source hash differs from current workspace index" };
212
+ }
213
+ finally {
214
+ repository.close();
215
+ }
216
+ }
217
+ catch (error) {
218
+ return { state: "unknown", reason: errorMessage(error) };
219
+ }
220
+ }
221
+ function readManifest(manifestPath, errors) {
222
+ if (!fs.existsSync(manifestPath)) {
223
+ errors.push("Missing manifest.json.");
224
+ return undefined;
225
+ }
226
+ try {
227
+ return readJsonFile(manifestPath);
228
+ }
229
+ catch (error) {
230
+ errors.push(`Invalid manifest.json: ${errorMessage(error)}.`);
231
+ return undefined;
232
+ }
233
+ }
234
+ function validateManifestShape(manifest, errors) {
235
+ if (manifest.format !== "mdgraph-bundle") {
236
+ errors.push("Manifest format must be mdgraph-bundle.");
237
+ }
238
+ if (manifest.formatVersion !== 1) {
239
+ errors.push(`Unsupported bundle formatVersion: ${manifest.formatVersion}.`);
240
+ }
241
+ if (manifest.visibility !== "private") {
242
+ errors.push(`Unsupported bundle visibility: ${manifest.visibility}.`);
243
+ }
244
+ if (!isStatusCounts(manifest.counts)) {
245
+ errors.push("Manifest counts must include documents, sections, entities, sourceRefs, edges, chunks, and vectors.");
246
+ }
247
+ if (!isDocumentSummary(manifest.documents)) {
248
+ errors.push("Manifest documents summary must include count and hash.");
249
+ }
250
+ }
251
+ function compareCounts(expected, actual, errors) {
252
+ for (const key of Object.keys(expected)) {
253
+ if (expected[key] !== actual[key]) {
254
+ errors.push(`Count mismatch for ${key}: manifest=${expected[key]}, database=${actual[key]}.`);
255
+ }
256
+ }
257
+ }
258
+ function isStatusCounts(value) {
259
+ if (!value || typeof value !== "object") {
260
+ return false;
261
+ }
262
+ const record = value;
263
+ return ["documents", "sections", "entities", "sourceRefs", "edges", "chunks", "vectors"].every((key) => typeof record[key] === "number");
264
+ }
265
+ function isDocumentSummary(value) {
266
+ if (!value || typeof value !== "object") {
267
+ return false;
268
+ }
269
+ const record = value;
270
+ return typeof record.count === "number" && typeof record.hash === "string";
271
+ }
272
+ function readJsonFile(filePath) {
273
+ return readBoundedJsonFile(filePath, "Bundle JSON file");
274
+ }
275
+ function writeJson(filePath, value) {
276
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
277
+ }
278
+ function resolveBundlePath(bundleDir, relativePath) {
279
+ if (typeof relativePath !== "string" || path.isAbsolute(relativePath)) {
280
+ return undefined;
281
+ }
282
+ const resolved = path.resolve(bundleDir, relativePath);
283
+ const relative = path.relative(bundleDir, resolved);
284
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative) ? resolved : undefined;
285
+ }
286
+ function fileHash(filePath) {
287
+ return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
288
+ }
289
+ function hashString(value) {
290
+ return createHash("sha256").update(value).digest("hex");
291
+ }
292
+ function safeTimestamp(value) {
293
+ return value.replace(/[:.]/g, "-");
294
+ }
295
+ function gitRevision(projectRoot) {
296
+ return runGit(projectRoot, ["rev-parse", "HEAD"]);
297
+ }
298
+ function gitDirty(projectRoot) {
299
+ const status = runGit(projectRoot, ["status", "--porcelain"]);
300
+ return status === undefined ? undefined : status.length > 0;
301
+ }
302
+ function runGit(projectRoot, args) {
303
+ if (!fs.existsSync(path.join(projectRoot, ".git"))) {
304
+ return undefined;
305
+ }
306
+ try {
307
+ const result = spawnSync("git", args, {
308
+ cwd: projectRoot,
309
+ encoding: "utf8",
310
+ windowsHide: true
311
+ });
312
+ return result.status === 0 ? result.stdout.trim() : undefined;
313
+ }
314
+ catch {
315
+ return undefined;
316
+ }
317
+ }
318
+ function errorMessage(error) {
319
+ return error instanceof Error ? error.message : String(error);
320
+ }
@@ -0,0 +1,24 @@
1
+ export declare const CONFIG_LIMITS: {
2
+ readonly indexMaxFileBytes: number;
3
+ readonly searchDefaultLimit: 100;
4
+ readonly searchMaxDepth: 12;
5
+ readonly searchMaxContextChars: 200000;
6
+ readonly searchHighFrequencyEntityThreshold: 100000;
7
+ readonly embeddingDimensions: 4096;
8
+ };
9
+ export declare const MCP_LIMITS: {
10
+ readonly searchLimit: 100;
11
+ readonly traceDepth: 12;
12
+ readonly contextMaxChars: 200000;
13
+ readonly jsonRpcLineBytes: number;
14
+ };
15
+ export declare const PARSER_LIMITS: {
16
+ readonly maxAstNodes: 10000;
17
+ readonly maxAstDepth: 256;
18
+ };
19
+ export declare const JSON_ARTIFACT_LIMITS: {
20
+ readonly maxBytes: number;
21
+ readonly maxDepth: 128;
22
+ readonly maxNodes: 1000000;
23
+ readonly maxArrayLength: 1000000;
24
+ };
@@ -0,0 +1,24 @@
1
+ export const CONFIG_LIMITS = {
2
+ indexMaxFileBytes: 10 * 1024 * 1024,
3
+ searchDefaultLimit: 100,
4
+ searchMaxDepth: 12,
5
+ searchMaxContextChars: 200_000,
6
+ searchHighFrequencyEntityThreshold: 100_000,
7
+ embeddingDimensions: 4096
8
+ };
9
+ export const MCP_LIMITS = {
10
+ searchLimit: CONFIG_LIMITS.searchDefaultLimit,
11
+ traceDepth: CONFIG_LIMITS.searchMaxDepth,
12
+ contextMaxChars: CONFIG_LIMITS.searchMaxContextChars,
13
+ jsonRpcLineBytes: 1024 * 1024
14
+ };
15
+ export const PARSER_LIMITS = {
16
+ maxAstNodes: 10_000,
17
+ maxAstDepth: 256
18
+ };
19
+ export const JSON_ARTIFACT_LIMITS = {
20
+ maxBytes: 50 * 1024 * 1024,
21
+ maxDepth: 128,
22
+ maxNodes: 1_000_000,
23
+ maxArrayLength: 1_000_000
24
+ };
@@ -0,0 +1,14 @@
1
+ import type { MDGraphConfig } from "../types.js";
2
+ export declare const BUILT_IN_DOC_EXCLUDES: readonly ["**/node_modules/**", "**/dist/**", "**/build/**", "**/coverage/**", "**/.git/**", "**/.mdgraph/**", "**/.next/**", "**/.turbo/**", "**/.cache/**", "temp/**", "**/temp/**", "tmp/**", "**/tmp/**"];
3
+ export interface InitProjectConfigResult {
4
+ configPath: string;
5
+ configCreated: boolean;
6
+ gitignorePath: string;
7
+ gitignoreUpdated: boolean;
8
+ }
9
+ export declare const DEFAULT_CONFIG: MDGraphConfig;
10
+ export declare function configPath(projectRoot: string): string;
11
+ export declare function databasePath(projectRoot: string): string;
12
+ export declare function loadConfig(projectRoot: string): MDGraphConfig;
13
+ export declare function initConfig(projectRoot: string, docsInclude?: string[]): string;
14
+ export declare function initProjectConfig(projectRoot: string, docsInclude?: string[]): InitProjectConfigResult;
@@ -0,0 +1,177 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { CONFIG_LIMITS } from "./limits.js";
4
+ const defaultEnabledKinds = [
5
+ "symbol",
6
+ "api_route",
7
+ "error_code",
8
+ "config_key",
9
+ "file_path",
10
+ "command",
11
+ "package",
12
+ "concept"
13
+ ];
14
+ const MDGRAPH_GITIGNORE_MARKER = "# MDGraph local artifacts";
15
+ const MDGRAPH_GITIGNORE_BLOCK = [
16
+ MDGRAPH_GITIGNORE_MARKER,
17
+ "!.mdgraph/",
18
+ ".mdgraph/*",
19
+ "!.mdgraph/config.json"
20
+ ].join("\n");
21
+ export const BUILT_IN_DOC_EXCLUDES = [
22
+ "**/node_modules/**",
23
+ "**/dist/**",
24
+ "**/build/**",
25
+ "**/coverage/**",
26
+ "**/.git/**",
27
+ "**/.mdgraph/**",
28
+ "**/.next/**",
29
+ "**/.turbo/**",
30
+ "**/.cache/**",
31
+ "temp/**",
32
+ "**/temp/**",
33
+ "tmp/**",
34
+ "**/tmp/**"
35
+ ];
36
+ export const DEFAULT_CONFIG = {
37
+ docs: {
38
+ include: ["**/*.md", "**/*.mdx"],
39
+ exclude: []
40
+ },
41
+ index: {
42
+ parseMdx: false,
43
+ followGitignore: true,
44
+ maxFileBytes: 524288
45
+ },
46
+ search: {
47
+ defaultLimit: 8,
48
+ maxDepth: 2,
49
+ maxContextChars: 28000,
50
+ highFrequencyEntityThreshold: 50
51
+ },
52
+ entities: {
53
+ enabledKinds: defaultEnabledKinds,
54
+ stopEntities: ["Config", "Error", "Service", "API", "User", "Data"]
55
+ },
56
+ embedding: {
57
+ enabled: false,
58
+ provider: "local-hash",
59
+ model: "mdgraph-local-hash-v1",
60
+ dimensions: 128
61
+ }
62
+ };
63
+ export function configPath(projectRoot) {
64
+ return path.join(projectRoot, ".mdgraph", "config.json");
65
+ }
66
+ export function databasePath(projectRoot) {
67
+ return path.join(projectRoot, ".mdgraph", "graph.db");
68
+ }
69
+ export function loadConfig(projectRoot) {
70
+ const target = configPath(projectRoot);
71
+ if (!fs.existsSync(target)) {
72
+ return DEFAULT_CONFIG;
73
+ }
74
+ const raw = fs.readFileSync(target, "utf8");
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(raw);
78
+ }
79
+ catch (error) {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ throw new Error(`Invalid MDGraph config at ${target}: ${message}. Fix the JSON syntax or delete the file and run \`mdgraph init\` to regenerate it.`);
82
+ }
83
+ return mergeConfig(DEFAULT_CONFIG, parsed);
84
+ }
85
+ export function initConfig(projectRoot, docsInclude) {
86
+ const target = configPath(projectRoot);
87
+ fs.mkdirSync(path.dirname(target), { recursive: true });
88
+ if (!fs.existsSync(target)) {
89
+ const config = docsInclude?.length
90
+ ? mergeConfig(DEFAULT_CONFIG, { docs: { ...DEFAULT_CONFIG.docs, include: docsInclude } })
91
+ : DEFAULT_CONFIG;
92
+ fs.writeFileSync(target, `${JSON.stringify(config, null, 2)}\n`, "utf8");
93
+ }
94
+ return target;
95
+ }
96
+ export function initProjectConfig(projectRoot, docsInclude) {
97
+ const target = configPath(projectRoot);
98
+ const configCreated = !fs.existsSync(target);
99
+ initConfig(projectRoot, docsInclude);
100
+ const gitignore = ensureMdgraphGitignore(projectRoot);
101
+ return {
102
+ configPath: target,
103
+ configCreated,
104
+ gitignorePath: gitignore.path,
105
+ gitignoreUpdated: gitignore.updated
106
+ };
107
+ }
108
+ function ensureMdgraphGitignore(projectRoot) {
109
+ const target = path.join(projectRoot, ".gitignore");
110
+ const existing = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : "";
111
+ if (hasMdgraphIgnoreProtection(existing)) {
112
+ return { path: target, updated: false };
113
+ }
114
+ const separator = existing.length ? (existing.endsWith("\n") ? "\n" : "\n\n") : "";
115
+ fs.writeFileSync(target, `${existing}${separator}${MDGRAPH_GITIGNORE_BLOCK}\n`, "utf8");
116
+ return { path: target, updated: true };
117
+ }
118
+ function hasMdgraphIgnoreProtection(content) {
119
+ return content.includes(MDGRAPH_GITIGNORE_BLOCK);
120
+ }
121
+ function mergeConfig(base, override) {
122
+ return {
123
+ docs: {
124
+ include: nonEmptyStringArray(override.docs?.include, base.docs.include),
125
+ exclude: stringArray(override.docs?.exclude, base.docs.exclude)
126
+ },
127
+ index: {
128
+ parseMdx: boolOr(override.index?.parseMdx, base.index.parseMdx),
129
+ followGitignore: boolOr(override.index?.followGitignore, base.index.followGitignore),
130
+ maxFileBytes: boundedPositiveInteger(override.index?.maxFileBytes, base.index.maxFileBytes, "index.maxFileBytes", CONFIG_LIMITS.indexMaxFileBytes)
131
+ },
132
+ search: {
133
+ defaultLimit: boundedPositiveInteger(override.search?.defaultLimit, base.search.defaultLimit, "search.defaultLimit", CONFIG_LIMITS.searchDefaultLimit),
134
+ maxDepth: boundedPositiveInteger(override.search?.maxDepth, base.search.maxDepth, "search.maxDepth", CONFIG_LIMITS.searchMaxDepth),
135
+ maxContextChars: boundedPositiveInteger(override.search?.maxContextChars, base.search.maxContextChars, "search.maxContextChars", CONFIG_LIMITS.searchMaxContextChars),
136
+ highFrequencyEntityThreshold: boundedPositiveInteger(override.search?.highFrequencyEntityThreshold, base.search.highFrequencyEntityThreshold, "search.highFrequencyEntityThreshold", CONFIG_LIMITS.searchHighFrequencyEntityThreshold)
137
+ },
138
+ entities: {
139
+ enabledKinds: nonEmptyStringArray(override.entities?.enabledKinds, base.entities.enabledKinds),
140
+ stopEntities: nonEmptyStringArray(override.entities?.stopEntities, base.entities.stopEntities)
141
+ },
142
+ embedding: {
143
+ enabled: boolOr(override.embedding?.enabled, base.embedding.enabled),
144
+ provider: stringOr(override.embedding?.provider, base.embedding.provider),
145
+ model: stringOr(override.embedding?.model, base.embedding.model),
146
+ dimensions: boundedPositiveInteger(override.embedding?.dimensions, base.embedding.dimensions, "embedding.dimensions", CONFIG_LIMITS.embeddingDimensions)
147
+ }
148
+ };
149
+ }
150
+ function nonEmptyStringArray(value, fallback) {
151
+ if (!Array.isArray(value)) {
152
+ return fallback;
153
+ }
154
+ const result = value.filter((item) => typeof item === "string" && item.trim().length > 0);
155
+ return result.length ? result : fallback;
156
+ }
157
+ function stringArray(value, fallback) {
158
+ if (!Array.isArray(value)) {
159
+ return fallback;
160
+ }
161
+ return value.filter((item) => typeof item === "string" && item.trim().length > 0);
162
+ }
163
+ function boundedPositiveInteger(value, fallback, field, max) {
164
+ if (value === undefined || value === null) {
165
+ return fallback;
166
+ }
167
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0 || value > max) {
168
+ throw new Error(`Invalid MDGraph config: ${field} must be a positive integer at most ${max}.`);
169
+ }
170
+ return value;
171
+ }
172
+ function boolOr(value, fallback) {
173
+ return typeof value === "boolean" ? value : fallback;
174
+ }
175
+ function stringOr(value, fallback) {
176
+ return typeof value === "string" && value.trim() ? value : fallback;
177
+ }
@@ -0,0 +1,15 @@
1
+ import { type SqliteDatabase } from "./sqlite-adapter.js";
2
+ export declare const CURRENT_SCHEMA_VERSION = 1;
3
+ export interface OpenDatabaseOptions {
4
+ createIfMissing?: boolean;
5
+ applySchema?: boolean;
6
+ }
7
+ export interface SchemaMetadata {
8
+ schemaVersion: number;
9
+ createdByVersion?: string;
10
+ updatedAt?: string;
11
+ baseline: "current" | "legacy";
12
+ }
13
+ export declare function openDatabase(projectRoot: string, options?: OpenDatabaseOptions): SqliteDatabase;
14
+ export declare function openExistingDatabase(projectRoot: string): SqliteDatabase;
15
+ export declare function readSchemaMetadata(db: SqliteDatabase): SchemaMetadata;