@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,877 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { Command } from "commander";
5
+ import { formatDoctorReport, runDoctor } from "../analysis/doctor.js";
6
+ import { collectDoctorScope } from "../analysis/doctor-scope.js";
7
+ import { computeStatusFreshness } from "../analysis/status-freshness.js";
8
+ import { createGraphBundle, verifyGraphBundle } from "../bundle/bundle.js";
9
+ import { databasePath, initProjectConfig, loadConfig } from "../config/load-config.js";
10
+ import { openExistingDatabase } from "../db/connection.js";
11
+ import { GraphRepository } from "../db/repositories.js";
12
+ import { formatGraphDiff, generateGraphDiff } from "../diff/graph-diff.js";
13
+ import { EVALUATION_QUERY_SET_NAMES, evaluateRetrieval } from "../evaluation/retrieval-eval.js";
14
+ import { buildMermaidTraceExport } from "../export/diagram.js";
15
+ import { buildGraphJsonExport, formatGraphJsonVerification, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "../export/graphjson.js";
16
+ import { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "../export/markdown-index.js";
17
+ import { buildSourceBridgeReport } from "../export/source-bridge.js";
18
+ import { indexProject } from "../indexer.js";
19
+ import { startStdioMcpServer } from "../mcp/server.js";
20
+ import { buildContext } from "../query/context-builder.js";
21
+ import { explainSearchGraph, searchGraph } from "../query/search.js";
22
+ import { traceNodes } from "../query/trace.js";
23
+ import { formatReport, generateReport } from "../reporting/report.js";
24
+ import { semanticStatusReport } from "../semantic/status.js";
25
+ import { packageVersion } from "../version.js";
26
+ import { watchProject } from "../watcher/file-watcher.js";
27
+ const program = new Command();
28
+ program
29
+ .name("mdgraph")
30
+ .description("Local-first Markdown document graph for AI coding workflows")
31
+ .version(packageVersion());
32
+ program
33
+ .command("usage")
34
+ .description("Print agent-friendly MDGraph workflows and command examples")
35
+ .option("--json", "Print JSON output")
36
+ .option("--path <path>", "Project root to use in examples. Defaults to the current working directory")
37
+ .action((options) => {
38
+ const guide = buildUsageGuide(projectRootFromOption(options.path));
39
+ printResult(options.json, guide, formatUsageGuide(guide));
40
+ });
41
+ program
42
+ .command("init")
43
+ .description("Create .mdgraph/config.json and build the initial index")
44
+ .option("--docs <glob...>", "Markdown include glob(s)")
45
+ .option("--no-index", "Skip initial indexing after writing config")
46
+ .option("--path <path>", "Project root. Defaults to the current working directory")
47
+ .action(async (options) => {
48
+ const projectRoot = projectRootFromOption(options.path);
49
+ const result = initProjectConfig(projectRoot, options.docs);
50
+ const configStatus = result.configCreated ? "Created" : "Already exists";
51
+ const gitignoreStatus = result.gitignoreUpdated ? "Updated" : "Already protected";
52
+ console.log(`${configStatus} ${result.configPath}`);
53
+ console.log(`${gitignoreStatus} ${result.gitignorePath}`);
54
+ if (options.index === false) {
55
+ console.log("Skipped initial index. Run `mdgraph index` to create the local graph.");
56
+ return;
57
+ }
58
+ const index = await indexProject(projectRoot);
59
+ console.log(formatIndexResult(index));
60
+ });
61
+ program
62
+ .command("index")
63
+ .description("Index Markdown documents into the local graph database")
64
+ .option("--json", "Print JSON output")
65
+ .option("--full", "Rebuild the whole index instead of hash-based incremental sync")
66
+ .option("--semantic", "Build local semantic vectors for chunks")
67
+ .option("--path <path>", "Project root. Defaults to the current working directory")
68
+ .action(async (options) => {
69
+ const result = await indexProject(projectRootFromOption(options.path), { full: options.full, semantic: options.semantic });
70
+ printResult(options.json, result, formatIndexResult(result));
71
+ });
72
+ program
73
+ .command("status")
74
+ .description("Show graph database status")
75
+ .option("--json", "Print JSON output")
76
+ .option("--storage", "Include storage diagnostics")
77
+ .option("--freshness", "Include lightweight index freshness diagnostics")
78
+ .option("--path <path>", "Project root. Defaults to the current working directory")
79
+ .action((options) => {
80
+ const projectRoot = projectRootFromOption(options.path);
81
+ const database = databasePath(projectRoot);
82
+ if (!fs.existsSync(database)) {
83
+ printResult(options.json, { indexed: false, projectRoot, database }, [`MDGraph index status: inactive`, `Project: ${projectRoot}`, `Database: ${database}`, "Run `mdgraph index` to create the local graph."].join("\n"));
84
+ return;
85
+ }
86
+ const repository = openRepository(projectRoot);
87
+ try {
88
+ const counts = repository.counts();
89
+ const freshness = options.freshness ? computeStatusFreshness(projectRoot, loadConfig(projectRoot), repository) : undefined;
90
+ if (options.storage) {
91
+ const storage = repository.storageDiagnostics();
92
+ printResult(options.json, freshness ? { counts, storage, freshness } : { counts, storage }, formatStatusWithStorage(counts, storage, freshness));
93
+ return;
94
+ }
95
+ if (freshness) {
96
+ printResult(options.json, { counts, freshness }, formatStatusWithFreshness(counts, freshness));
97
+ return;
98
+ }
99
+ printResult(options.json, counts, formatStatusCounts(counts));
100
+ }
101
+ finally {
102
+ closeRepository(repository);
103
+ }
104
+ });
105
+ program
106
+ .command("search")
107
+ .description("Search documents, sections, and entities")
108
+ .argument("<query>")
109
+ .option("--json", "Print JSON output")
110
+ .option("--limit <number>", "Maximum results", parseInteger)
111
+ .option("--semantic", "Include local semantic vector matches when vectors are indexed")
112
+ .option("--explain", "Include query parsing and ranking explanation details")
113
+ .option("--path <path>", "Project root. Defaults to the current working directory")
114
+ .action((query, options) => {
115
+ const projectRoot = projectRootFromOption(options.path);
116
+ const config = loadConfig(projectRoot);
117
+ const repository = openRepository(projectRoot);
118
+ try {
119
+ if (options.explain) {
120
+ const explanation = explainSearchGraph(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
121
+ printResult(options.json, explanation, formatSearchExplanation(explanation));
122
+ return;
123
+ }
124
+ const results = searchGraph(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
125
+ printResult(options.json, results, formatSearchResults(results));
126
+ }
127
+ finally {
128
+ closeRepository(repository);
129
+ }
130
+ });
131
+ program
132
+ .command("context")
133
+ .description("Build an explainable context package for a question")
134
+ .argument("<query>")
135
+ .option("--json", "Print JSON output")
136
+ .option("--debug", "Include context packing and graph expansion debug details")
137
+ .option("--path <path>", "Project root. Defaults to the current working directory")
138
+ .action((query, options) => {
139
+ const projectRoot = projectRootFromOption(options.path);
140
+ const config = loadConfig(projectRoot);
141
+ const repository = openRepository(projectRoot);
142
+ try {
143
+ const context = buildContext(repository, config, query, { debug: options.debug });
144
+ printResult(options.json, context, formatContext(context));
145
+ }
146
+ finally {
147
+ closeRepository(repository);
148
+ }
149
+ });
150
+ program
151
+ .command("node")
152
+ .description("Show a document, entity, source ref, section, or chunk")
153
+ .argument("<query>")
154
+ .option("--json", "Print JSON output")
155
+ .option("--path <path>", "Project root. Defaults to the current working directory")
156
+ .action((query, options) => {
157
+ const repository = openRepository(projectRootFromOption(options.path));
158
+ try {
159
+ const resolution = repository.resolveNodeDetailed(query);
160
+ printResult(options.json, nodeResolutionJson(resolution), formatNodeResolution(resolution));
161
+ }
162
+ finally {
163
+ closeRepository(repository);
164
+ }
165
+ });
166
+ program
167
+ .command("trace")
168
+ .description("Trace a graph path between two documents, entities, or source refs")
169
+ .argument("<from>")
170
+ .argument("<to>")
171
+ .option("--json", "Print JSON output")
172
+ .option("--depth <number>", "Maximum graph depth", parseInteger)
173
+ .option("--path <path>", "Project root. Defaults to the current working directory")
174
+ .action((from, to, options) => {
175
+ const repository = openRepository(projectRootFromOption(options.path));
176
+ try {
177
+ const trace = traceNodes(repository, from, to, options.depth ?? 6);
178
+ printResult(options.json, trace, formatTrace(trace));
179
+ }
180
+ finally {
181
+ closeRepository(repository);
182
+ }
183
+ });
184
+ program
185
+ .command("eval")
186
+ .description("Run retrieval quality evaluation against an indexed project")
187
+ .option("--json", "Print JSON output")
188
+ .option("--path <path>", "Project root to evaluate", process.cwd())
189
+ .option("--limit <number>", "Search results per evaluation case", parseInteger)
190
+ .option("--query-set <name>", `Evaluation query set (${EVALUATION_QUERY_SET_NAMES.join(", ")})`, "alpha")
191
+ .option("--query-mode <mode>", "Search query mode for evaluation (auto, keyword, semantic)", parseSearchQueryMode, "auto")
192
+ .action((options) => {
193
+ const projectRoot = validateProjectRoot(options.path);
194
+ const config = loadConfig(projectRoot);
195
+ const repository = openRepository(projectRoot);
196
+ try {
197
+ const report = evaluateRetrieval(repository, config, { limit: options.limit, querySet: options.querySet, queryMode: options.queryMode });
198
+ printResult(options.json, report, formatEvaluationReport(report));
199
+ }
200
+ finally {
201
+ closeRepository(repository);
202
+ }
203
+ });
204
+ const semanticCommand = program
205
+ .command("semantic")
206
+ .description("Inspect optional semantic vector indexing");
207
+ semanticCommand
208
+ .command("status")
209
+ .description("Show semantic provider, vector coverage, and reindex guidance")
210
+ .option("--json", "Print JSON output")
211
+ .option("--path <path>", "Project root to inspect", process.cwd())
212
+ .action((options) => {
213
+ const projectRoot = validateProjectRoot(options.path);
214
+ const config = loadConfig(projectRoot);
215
+ if (!fs.existsSync(databasePath(projectRoot))) {
216
+ const report = semanticStatusReport(config, undefined, undefined);
217
+ printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
218
+ return;
219
+ }
220
+ const repository = openRepository(projectRoot);
221
+ try {
222
+ const report = semanticStatusReport(config, repository.counts(), repository.storageDiagnostics());
223
+ printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
224
+ }
225
+ finally {
226
+ closeRepository(repository);
227
+ }
228
+ });
229
+ const bundleCommand = program
230
+ .command("bundle")
231
+ .description("Create and verify reusable local graph bundle artifacts");
232
+ bundleCommand
233
+ .command("create")
234
+ .description("Create a private directory bundle from the current graph")
235
+ .option("--json", "Print JSON output")
236
+ .option("--profile <profile>", "Bundle profile", "private")
237
+ .option("--path <path>", "Project root. Defaults to the current working directory")
238
+ .action(async (options) => {
239
+ const result = await createGraphBundle(projectRootFromOption(options.path), { profile: options.profile });
240
+ printResult(options.json, result, formatBundleCreate(result));
241
+ });
242
+ bundleCommand
243
+ .command("verify")
244
+ .description("Verify a graph bundle directory")
245
+ .argument("<dir>")
246
+ .option("--json", "Print JSON output")
247
+ .option("--path <path>", "Project root for freshness comparison. Defaults to the current working directory")
248
+ .action((dir, options) => {
249
+ const result = verifyGraphBundle(dir, { projectRoot: projectRootFromOption(options.path) });
250
+ printResult(options.json, result, formatBundleVerify(result));
251
+ if (!result.valid) {
252
+ process.exitCode = 1;
253
+ }
254
+ });
255
+ const exportCommand = program
256
+ .command("export")
257
+ .description("Export MDGraph interoperability artifacts");
258
+ exportCommand
259
+ .command("graphjson")
260
+ .description("Export a deterministic structural GraphJSON view")
261
+ .option("--json", "Print JSON output")
262
+ .option("--path <path>", "Project root. Defaults to the current working directory")
263
+ .action((options) => {
264
+ const projectRoot = projectRootFromOption(options.path);
265
+ const repository = openRepository(projectRoot);
266
+ try {
267
+ const graph = buildGraphJsonExport(projectRoot, repository);
268
+ if (options.json) {
269
+ printResult(true, graph, "");
270
+ return;
271
+ }
272
+ process.stdout.write(stableGraphJson(graph));
273
+ }
274
+ finally {
275
+ closeRepository(repository);
276
+ }
277
+ });
278
+ const exportMermaidCommand = exportCommand
279
+ .command("mermaid")
280
+ .description("Export deterministic Mermaid diagrams");
281
+ exportMermaidCommand
282
+ .command("trace")
283
+ .description("Export a Mermaid trace path diagram")
284
+ .argument("<from>")
285
+ .argument("<to>")
286
+ .option("--json", "Print JSON output")
287
+ .option("--depth <number>", "Maximum graph depth", parseInteger)
288
+ .option("--path <path>", "Project root. Defaults to the current working directory")
289
+ .action((from, to, options) => {
290
+ const repository = openRepository(projectRootFromOption(options.path));
291
+ try {
292
+ const trace = traceNodes(repository, from, to, options.depth ?? 6);
293
+ const result = buildMermaidTraceExport(trace);
294
+ printResult(options.json, result, result.diagram);
295
+ }
296
+ finally {
297
+ closeRepository(repository);
298
+ }
299
+ });
300
+ exportCommand
301
+ .command("markdown-index")
302
+ .description("Export a WikiLink-based Markdown graph index")
303
+ .option("--path <path>", "Project root. Defaults to the current working directory")
304
+ .action((options) => {
305
+ const projectRoot = projectRootFromOption(options.path);
306
+ const repository = openRepository(projectRoot);
307
+ try {
308
+ const graph = buildGraphJsonExport(projectRoot, repository);
309
+ console.log(formatWikiLinkMarkdownIndex(graph));
310
+ }
311
+ finally {
312
+ closeRepository(repository);
313
+ }
314
+ });
315
+ exportCommand
316
+ .command("docs-site")
317
+ .description("Export lightweight docs-site graph data")
318
+ .option("--json", "Print JSON output")
319
+ .option("--path <path>", "Project root. Defaults to the current working directory")
320
+ .action((options) => {
321
+ const projectRoot = projectRootFromOption(options.path);
322
+ const repository = openRepository(projectRoot);
323
+ try {
324
+ const graph = buildGraphJsonExport(projectRoot, repository);
325
+ const index = buildDocsSiteIndex(graph);
326
+ printResult(options.json, index, JSON.stringify(index, null, 2));
327
+ }
328
+ finally {
329
+ closeRepository(repository);
330
+ }
331
+ });
332
+ exportCommand
333
+ .command("source-bridge")
334
+ .description("Export a read-only source bridge report")
335
+ .option("--json", "Print JSON output")
336
+ .option("--provider <provider>", "Bridge provider", "json")
337
+ .option("--artifact <file>", "Read-only provider artifact to inspect")
338
+ .option("--path <path>", "Project root. Defaults to the current working directory")
339
+ .action((options) => {
340
+ if (options.provider !== "json") {
341
+ throw new Error(`Unsupported source bridge provider: ${options.provider}. MDGraph 1.0 supports the read-only json provider.`);
342
+ }
343
+ const repository = openRepository(projectRootFromOption(options.path));
344
+ try {
345
+ const report = buildSourceBridgeReport(repository, { artifact: options.artifact });
346
+ printResult(options.json, report, formatSourceBridgeReport(report));
347
+ }
348
+ finally {
349
+ closeRepository(repository);
350
+ }
351
+ });
352
+ const importCommand = program
353
+ .command("import")
354
+ .description("Inspect external MDGraph interoperability artifacts without writing the local index");
355
+ importCommand
356
+ .command("graphjson")
357
+ .description("Verify a GraphJSON export")
358
+ .argument("<file>")
359
+ .option("--json", "Print JSON output")
360
+ .option("--verify", "Verify only; required because GraphJSON merge import is not supported")
361
+ .action((file, options) => {
362
+ if (!options.verify) {
363
+ throw new Error("GraphJSON import is verify-only in MDGraph 0.7. Pass --verify.");
364
+ }
365
+ let value;
366
+ try {
367
+ value = readGraphJsonFile(file);
368
+ }
369
+ catch (error) {
370
+ const result = {
371
+ valid: false,
372
+ errors: [{
373
+ code: "graphjson.read_failed",
374
+ message: `Failed to read GraphJSON file: ${error instanceof Error ? error.message : String(error)}`,
375
+ remediation: "Pass a readable JSON file exported by `mdgraph export graphjson --json`."
376
+ }],
377
+ warnings: []
378
+ };
379
+ printResult(options.json, result, formatGraphJsonVerification(result));
380
+ process.exitCode = 1;
381
+ return;
382
+ }
383
+ const result = verifyGraphJsonExport(value);
384
+ printResult(options.json, result, formatGraphJsonVerification(result));
385
+ if (!result.valid) {
386
+ process.exitCode = 1;
387
+ }
388
+ });
389
+ program
390
+ .command("diff")
391
+ .description("Compare the current graph index against a base Git revision")
392
+ .requiredOption("--base <ref>", "Base Git revision")
393
+ .option("--json", "Print JSON output")
394
+ .option("--path <path>", "Project root. Defaults to the current working directory")
395
+ .action(async (options) => {
396
+ const report = await generateGraphDiff(projectRootFromOption(options.path), { base: options.base });
397
+ printResult(options.json, report, formatGraphDiff(report));
398
+ });
399
+ program
400
+ .command("report")
401
+ .description("Generate a CI-friendly graph health and workflow report")
402
+ .option("--json", "Print JSON output")
403
+ .option("--eval", "Include retrieval evaluation summary")
404
+ .option("--bundle <dir>", "Include bundle verification summary")
405
+ .option("--base <ref>", "Include graph diff summary against a base Git revision")
406
+ .option("--benchmark <file>", "Include paired agent benchmark summary from structured run records")
407
+ .option("--previous-report <file>", "Explicit previous report JSON for trend context")
408
+ .option("--path <path>", "Project root. Defaults to the current working directory")
409
+ .action(async (options) => {
410
+ const report = await generateReport(projectRootFromOption(options.path), {
411
+ eval: options.eval,
412
+ bundle: options.bundle,
413
+ base: options.base,
414
+ benchmark: options.benchmark,
415
+ previousReport: options.previousReport
416
+ });
417
+ printResult(options.json, report, formatReport(report));
418
+ });
419
+ program
420
+ .command("serve")
421
+ .description("Serve MDGraph over the Model Context Protocol")
422
+ .option("--mcp", "Run an MCP server over stdio")
423
+ .option("--watch", "Keep the Markdown graph fresh while serving MCP requests (default)")
424
+ .option("--no-watch", "Disable automatic index updates while serving MCP requests")
425
+ .option("--semantic", "Build local semantic vectors during watch indexing")
426
+ .option("--debounce <ms>", "Debounce delay in milliseconds for serve watch mode", parseInteger)
427
+ .option("--path <path>", "Project root to serve", process.cwd())
428
+ .action((options) => {
429
+ if (!options.mcp) {
430
+ throw new Error("Only MCP stdio serving is currently supported. Pass --mcp.");
431
+ }
432
+ const watch = options.watch !== false;
433
+ startStdioMcpServer({
434
+ projectRoot: validateProjectRoot(options.path),
435
+ watch,
436
+ semantic: watch ? options.semantic : undefined,
437
+ debounceMs: watch ? options.debounce : undefined
438
+ });
439
+ });
440
+ program
441
+ .command("watch")
442
+ .description("Watch Markdown files and incrementally update the graph index")
443
+ .option("--semantic", "Build local semantic vectors during watch indexing")
444
+ .option("--debounce <ms>", "Debounce delay in milliseconds", parseInteger)
445
+ .option("--path <path>", "Project root. Defaults to the current working directory")
446
+ .action(async (options) => {
447
+ const projectRoot = projectRootFromOption(options.path);
448
+ console.error("MDGraph watch started. Press Ctrl+C to stop.");
449
+ const handle = await watchProject(projectRoot, {
450
+ semantic: options.semantic,
451
+ debounceMs: options.debounce,
452
+ onIndexed: (result) => {
453
+ console.error(`Indexed ${result.changed} changed, ${result.deleted} deleted, ${result.unchanged} unchanged, ${result.skipped} skipped document(s).`);
454
+ },
455
+ onError: (error) => {
456
+ console.error(`Watch indexing failed: ${error.message}`);
457
+ }
458
+ });
459
+ await new Promise((resolve) => {
460
+ process.once("SIGINT", () => resolve());
461
+ process.once("SIGTERM", () => resolve());
462
+ });
463
+ await handle.close();
464
+ });
465
+ program
466
+ .command("doctor")
467
+ .description("Analyze documentation graph health and governance issues")
468
+ .option("--json", "Print JSON output")
469
+ .option("--strict", "Exit with a non-zero status if any issue is reported")
470
+ .option("--fail-on <severity>", "Exit with non-zero status when warnings at or above severity exist (error, warn, info)")
471
+ .option("--changed", "Limit doctor output to changed Markdown paths in the Git worktree")
472
+ .option("--since <ref>", "Limit doctor output to Markdown paths changed since a Git ref")
473
+ .option("--path <path>", "Project root. Defaults to the current working directory")
474
+ .action(async (options) => {
475
+ if (options.changed && options.since) {
476
+ throw new Error("Use either --changed or --since <ref>, not both.");
477
+ }
478
+ const failOn = parseDoctorSeverity(options.failOn);
479
+ const projectRoot = projectRootFromOption(options.path);
480
+ const scope = options.changed
481
+ ? collectDoctorScope(projectRoot, { mode: "changed" })
482
+ : options.since
483
+ ? collectDoctorScope(projectRoot, { mode: "since", baseRef: options.since })
484
+ : undefined;
485
+ const report = await runDoctor(projectRoot, { scope });
486
+ printResult(options.json, report, formatDoctorReport(report));
487
+ if (options.strict && doctorIssueCount(report.summary) > 0) {
488
+ process.exitCode = 1;
489
+ }
490
+ if (failOn && doctorWarningsAtOrAbove(report.warnings, failOn)) {
491
+ process.exitCode = 1;
492
+ }
493
+ });
494
+ program.parseAsync().catch((error) => {
495
+ console.error(error instanceof Error ? error.message : String(error));
496
+ process.exitCode = 1;
497
+ });
498
+ function openRepository(projectRoot = process.cwd()) {
499
+ return new GraphRepository(openExistingDatabase(validateProjectRoot(projectRoot)));
500
+ }
501
+ function closeRepository(repository) {
502
+ repository.close();
503
+ }
504
+ function printResult(json, value, text) {
505
+ if (json) {
506
+ console.log(JSON.stringify(value, null, 2));
507
+ return;
508
+ }
509
+ console.log(text);
510
+ }
511
+ function buildUsageGuide(projectRoot) {
512
+ const project = shellPath(projectRoot);
513
+ return {
514
+ projectRoot,
515
+ commonOptions: [
516
+ { flag: "--path <project>", description: "Run against an explicit project root; defaults to the current working directory." },
517
+ { flag: "--json", description: "Print machine-readable output when the command supports structured output." }
518
+ ],
519
+ workflows: [
520
+ {
521
+ name: "Initialize",
522
+ purpose: "Create configuration, protect local artifacts, and build the initial graph index.",
523
+ commands: [
524
+ `mdgraph init --path ${project}`,
525
+ `mdgraph init --path ${project} --docs "docs/**/*.md"`,
526
+ `mdgraph init --path ${project} --no-index`
527
+ ]
528
+ },
529
+ {
530
+ name: "Refresh Index",
531
+ purpose: "Update the local graph after Markdown changes.",
532
+ commands: [
533
+ `mdgraph index --path ${project}`,
534
+ `mdgraph index --path ${project} --full`,
535
+ `mdgraph index --path ${project} --full --semantic`
536
+ ],
537
+ notes: ["`index` is hash-based incremental by default; use `--full` for a rebuild and compaction."]
538
+ },
539
+ {
540
+ name: "Check Health",
541
+ purpose: "Inspect availability, storage, freshness, and documentation-health warnings.",
542
+ commands: [
543
+ `mdgraph status --path ${project} --json`,
544
+ `mdgraph status --path ${project} --freshness --json`,
545
+ `mdgraph status --path ${project} --storage --freshness --json`,
546
+ `mdgraph doctor --path ${project} --json`,
547
+ `mdgraph doctor --path ${project} --strict`
548
+ ],
549
+ notes: ["`node:sqlite` experimental warnings are informational when the command exits successfully."]
550
+ },
551
+ {
552
+ name: "Task Start",
553
+ purpose: "Gather explainable context before reading multiple Markdown files manually.",
554
+ commands: [
555
+ `mdgraph context "what should I read before changing indexing?" --path ${project}`,
556
+ `mdgraph search "indexing config" --path ${project} --explain --json`,
557
+ `mdgraph node "docs/EN/Architecture.md" --path ${project}`,
558
+ `mdgraph trace "Architecture.md" "src/indexer.ts" --path ${project}`
559
+ ]
560
+ },
561
+ {
562
+ name: "CI And Artifacts",
563
+ purpose: "Produce reproducible graph reports and interoperability artifacts.",
564
+ commands: [
565
+ `mdgraph report --path ${project} --json`,
566
+ `mdgraph diff --path ${project} --base main --json`,
567
+ `mdgraph export graphjson --path ${project} --json`,
568
+ `mdgraph bundle create --path ${project} --profile private --json`
569
+ ]
570
+ },
571
+ {
572
+ name: "Help",
573
+ purpose: "Inspect syntax for all commands or a specific command.",
574
+ commands: ["mdgraph help", "mdgraph help search", "mdgraph usage --json"]
575
+ },
576
+ {
577
+ name: "Agent MCP",
578
+ purpose: "Serve MDGraph to an MCP client with integrated watch-based freshness by default.",
579
+ commands: [
580
+ `mdgraph serve --mcp --path ${project}`,
581
+ `mdgraph serve --mcp --debounce 250 --path ${project}`,
582
+ `mdgraph serve --mcp --no-watch --path ${project}`
583
+ ],
584
+ notes: ["MCP serve starts one index and keeps Markdown changes fresh by default; use `--no-watch` for read-only sessions."]
585
+ }
586
+ ]
587
+ };
588
+ }
589
+ function formatUsageGuide(guide) {
590
+ const workflows = guide.workflows.map((workflow) => {
591
+ const notes = workflow.notes?.length ? ["Notes:", ...workflow.notes.map((note) => `- ${note}`)] : [];
592
+ return [
593
+ `## ${workflow.name}`,
594
+ workflow.purpose,
595
+ "Commands:",
596
+ ...workflow.commands.map((command) => `- ${command}`),
597
+ ...notes
598
+ ].join("\n");
599
+ });
600
+ return [
601
+ "MDGraph usage",
602
+ `Project: ${guide.projectRoot}`,
603
+ "Common options:",
604
+ ...guide.commonOptions.map((option) => `- ${option.flag}: ${option.description}`),
605
+ "",
606
+ ...workflows
607
+ ].join("\n\n");
608
+ }
609
+ function shellPath(value) {
610
+ return /\s/.test(value) ? `"${value.replace(/"/g, "\\\"")}"` : value;
611
+ }
612
+ function projectRootFromOption(projectRoot) {
613
+ return validateProjectRoot(projectRoot ?? process.cwd());
614
+ }
615
+ function formatIndexResult(result) {
616
+ return `Indexed ${result.files} file(s) in ${result.mode} mode. Changed: ${result.changed}, deleted: ${result.deleted}, unchanged: ${result.unchanged}, skipped: ${result.skipped}. Documents: ${result.counts.documents}, entities: ${result.counts.entities}, edges: ${result.counts.edges}.`;
617
+ }
618
+ function formatStatusCounts(counts) {
619
+ return `Documents: ${counts.documents}, sections: ${counts.sections}, entities: ${counts.entities}, edges: ${counts.edges}, chunks: ${counts.chunks}, vectors: ${counts.vectors}.`;
620
+ }
621
+ function formatStatusWithStorage(counts, storage, freshness) {
622
+ const wal = storage.database.walCheckpoint.available
623
+ ? `WAL pages: ${storage.database.walCheckpoint.log}, checkpointed: ${storage.database.walCheckpoint.checkpointed}`
624
+ : `WAL status unavailable: ${storage.database.walCheckpoint.reason}`;
625
+ const lines = [
626
+ formatStatusCounts(counts),
627
+ `Storage: ${formatBytes(storage.database.estimatedBytes)} (${storage.database.pageCount} pages, ${storage.database.freelistCount} freelist pages, ${storage.database.journalMode} journal).`,
628
+ wal,
629
+ `Objects: ${storage.objects.entries.length} tracked${storage.objects.dbstatAvailable ? " with dbstat sizes" : " without dbstat sizes"}.`,
630
+ `Top path groups: ${storage.pathGroups.slice(0, 5).map((item) => `${item.group}=${formatBytes(item.contentBytes)}`).join(", ") || "none"}.`,
631
+ `Edge kinds: ${storage.edgeKinds.map((item) => `${item.kind}=${item.edges}`).join(", ") || "none"}.`,
632
+ `Vectors: ${storage.vectors.total}.`
633
+ ];
634
+ if (freshness) {
635
+ lines.push(formatFreshness(freshness));
636
+ }
637
+ return lines.join("\n");
638
+ }
639
+ function formatStatusWithFreshness(counts, freshness) {
640
+ return [formatStatusCounts(counts), formatFreshness(freshness)].join("\n");
641
+ }
642
+ function formatFreshness(freshness) {
643
+ return [
644
+ `Freshness: ${freshness.state} - ${freshness.recommendation}`,
645
+ freshness.lastIndexedAt ? `Last indexed: ${freshness.lastIndexedAt}` : "Last indexed: unavailable",
646
+ freshness.issues?.length ? `Stale issues: ${freshness.issues.slice(0, 5).map((issue) => `${issue.path}:${issue.reason}`).join(", ")}` : "Stale issues: none"
647
+ ].join("\n");
648
+ }
649
+ function formatBytes(bytes) {
650
+ if (bytes < 1024) {
651
+ return `${bytes} B`;
652
+ }
653
+ if (bytes < 1024 * 1024) {
654
+ return `${(bytes / 1024).toFixed(1)} KiB`;
655
+ }
656
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
657
+ }
658
+ function formatSearchResults(results) {
659
+ if (!results.length) {
660
+ return "No results.";
661
+ }
662
+ return results
663
+ .map((result, index) => {
664
+ const heading = result.section ? `#${result.section.anchor}` : "";
665
+ return `${index + 1}. ${result.document.path}${heading} - ${result.reason}`;
666
+ })
667
+ .join("\n");
668
+ }
669
+ function formatSearchExplanation(explanation) {
670
+ const entityLines = explanation.matchedEntities.length
671
+ ? explanation.matchedEntities.map((entity) => `- ${entity.name} (${entity.kind}) in ${entity.documentFrequency} document(s)`)
672
+ : ["- none"];
673
+ const resultLines = explanation.results.length
674
+ ? explanation.results.map((result, index) => `${index + 1}. ${result.document.path}${result.section ? `#${result.section.anchor}` : ""} score=${result.score.toFixed(2)} reason=${result.reason}`)
675
+ : ["No results."];
676
+ return [
677
+ `Query: ${explanation.query}`,
678
+ `Query mode: ${explanation.queryMode}`,
679
+ `FTS query: ${explanation.ftsQuery || "none"}`,
680
+ `Entity candidates: ${explanation.entityCandidates.join(", ") || "none"}`,
681
+ `Semantic requested: ${explanation.semanticEnabled}`,
682
+ `Semantic active: ${explanation.semanticActive}`,
683
+ `Ranking: ${explanation.ranking.fusion} (channels: ${explanation.ranking.channels.join(", ") || "none"}, reranker: ${explanation.ranking.optionalReranker})`,
684
+ "Matched entities:",
685
+ ...entityLines,
686
+ "Results:",
687
+ ...resultLines
688
+ ].join("\n");
689
+ }
690
+ function formatContext(context) {
691
+ if (!context.items.length) {
692
+ return "No context found.";
693
+ }
694
+ const items = context.items
695
+ .map((item, index) => {
696
+ const heading = item.heading ? `# ${item.heading}` : item.title;
697
+ const lines = item.lines ? `:${item.lines.start}` : "";
698
+ return `## ${index + 1}. ${item.path}${lines}\nReason: ${item.reason}\n${heading}\n${item.content}`;
699
+ })
700
+ .join("\n\n");
701
+ if (!context.debug) {
702
+ return items;
703
+ }
704
+ return [
705
+ items,
706
+ "",
707
+ "## Debug",
708
+ `Seed nodes: ${context.debug.seedNodes}`,
709
+ `Visited nodes: ${context.debug.visitedNodes}`,
710
+ `Expanded edges: ${context.debug.expandedEdges}`,
711
+ `Candidates: ${context.debug.candidateCount} (${context.debug.directCandidates} direct, ${context.debug.expandedCandidates} expanded)`,
712
+ `Packing: ${context.debug.packingStrategy}, items: ${context.debug.packedItems}, unique documents: ${context.debug.packedUniqueDocuments}, diversity: ${context.debug.packingDiversityRatio.toFixed(2)}`,
713
+ `Skipped visited: ${context.debug.skippedVisitedNodes}, node-limit: ${context.debug.skippedByNodeLimit}, depth: ${context.debug.skippedByDepth}`,
714
+ `Budget truncated items: ${context.debug.budgetTruncatedItems}, skipped items: ${context.debug.budgetSkippedItems}`
715
+ ].join("\n");
716
+ }
717
+ function formatTrace(trace) {
718
+ if (!trace.found) {
719
+ return trace.message ?? "No path found.";
720
+ }
721
+ return trace.steps
722
+ .map((step, index) => `${index + 1}. ${formatTraceStep(step)}`)
723
+ .join("\n");
724
+ }
725
+ function formatEvaluationReport(report) {
726
+ const lines = [
727
+ `Evaluation query set: ${report.querySet}`,
728
+ `Cases: ${report.summary.cases}, passed: ${report.summary.passed}, failed: ${report.summary.failed}`,
729
+ `Average top-K document recall: ${formatMetric(report.summary.averageTopKDocumentRecall)}`,
730
+ `Average expected-section recall: ${formatMetric(report.summary.averageExpectedSectionRecall)}`,
731
+ `Average context precision: ${formatMetric(report.summary.averageContextPrecision)}`,
732
+ `Average context diversity: ${formatMetric(report.summary.averageContextDiversity)}`,
733
+ `Ranking: ${report.ranking.searchFusion}, query mode: ${report.ranking.queryMode}, packing: ${report.ranking.contextPackingStrategy}, reranker: ${report.ranking.optionalReranker}`,
734
+ `Average latency: ${report.summary.averageLatencyMs.toFixed(1)} ms`,
735
+ "",
736
+ ...report.cases.map((result) => {
737
+ const status = result.passed ? "pass" : "fail";
738
+ return [
739
+ `${result.id}: ${status}`,
740
+ ` query: ${result.query}`,
741
+ ` topKDocumentRecall=${formatMetric(result.metrics.topKDocumentRecall)}, expectedSectionRecall=${formatMetric(result.metrics.expectedSectionRecall)}, contextPrecision=${formatMetric(result.metrics.contextPrecision)}, contextDiversity=${formatMetric(result.metrics.contextDiversity)}`,
742
+ ` traceSuccess=${result.metrics.traceSuccess ?? "n/a"}, returnedChars=${result.metrics.returnedChars}, budgetFit=${result.metrics.budgetFit}`
743
+ ].join("\n");
744
+ })
745
+ ];
746
+ return lines.join("\n");
747
+ }
748
+ function formatSemanticStatus(projectRoot, report) {
749
+ return [
750
+ "MDGraph semantic status",
751
+ `Project: ${projectRoot}`,
752
+ `State: ${report.state}`,
753
+ `Configured provider: ${report.provider}/${report.model} (${report.dimensions} dimensions, enabled: ${report.enabled})`,
754
+ `Provider supported: ${report.providerSupported}`,
755
+ `Indexed: ${report.indexed}`,
756
+ `Vectors: ${report.vectors}/${report.chunks} chunks`,
757
+ `Vector storage: ${report.vectorStorageFormat}`,
758
+ `Indexed providers: ${report.indexedProviders.map((provider) => `${provider.provider}/${provider.model}/${provider.dimensions}=${provider.vectors}`).join(", ") || "none"}`,
759
+ `Guidance: ${report.guidance.join(" ") || "none"}`
760
+ ].join("\n");
761
+ }
762
+ function formatBundleCreate(result) {
763
+ return [
764
+ "Created MDGraph bundle",
765
+ `Directory: ${result.bundleDir}`,
766
+ `Manifest: ${result.manifestPath}`,
767
+ `Schema: v${result.manifest.schemaVersion}`,
768
+ `Documents: ${result.manifest.counts.documents}`,
769
+ `Source hash: ${result.manifest.sourceHash}`
770
+ ].join("\n");
771
+ }
772
+ function formatBundleVerify(result) {
773
+ const lines = [
774
+ "MDGraph bundle verification",
775
+ `Directory: ${result.bundleDir}`,
776
+ `Valid: ${result.valid}`,
777
+ `Freshness: ${result.freshness.state} (${result.freshness.reason})`
778
+ ];
779
+ if (result.manifest) {
780
+ lines.push(`Schema: v${result.manifest.schemaVersion ?? "unknown"}`, `Documents: ${result.manifest.counts?.documents ?? "unknown"}`, `Source hash: ${result.manifest.sourceHash ?? "unknown"}`);
781
+ }
782
+ if (result.errors.length) {
783
+ lines.push("Errors:", ...result.errors.map((error) => `- ${error}`));
784
+ }
785
+ return lines.join("\n");
786
+ }
787
+ function formatSourceBridgeReport(report) {
788
+ const lines = [
789
+ "MDGraph source bridge",
790
+ `Provider: ${report.provider}`,
791
+ `Status: ${report.status}`,
792
+ `Source refs: ${report.sourceRefs}`,
793
+ `Matched: ${report.matched.length}`,
794
+ `Unmatched: ${report.unmatched.length}`
795
+ ];
796
+ if (report.reason) {
797
+ lines.push(`Reason: ${report.reason}`);
798
+ }
799
+ if (report.matched.length) {
800
+ lines.push("Matches:", ...report.matched.map((match) => `- ${match.sourceRef} -> ${match.artifactPath}${match.symbols.length ? ` (${match.symbols.map((symbol) => symbol.name).join(", ")})` : ""}`));
801
+ }
802
+ return lines.join("\n");
803
+ }
804
+ function formatMetric(value) {
805
+ return value.toFixed(2);
806
+ }
807
+ function nodeResolutionJson(resolution) {
808
+ if (resolution.status === "found") {
809
+ return resolution.node;
810
+ }
811
+ if (resolution.status === "ambiguous") {
812
+ return { error: resolution.error, query: resolution.query, candidates: resolution.candidates };
813
+ }
814
+ return { error: resolution.error, query: resolution.query };
815
+ }
816
+ function formatNodeResolution(resolution) {
817
+ if (resolution.status === "found") {
818
+ return `${resolution.node.kind}: ${resolution.node.label}`;
819
+ }
820
+ if (resolution.status === "ambiguous") {
821
+ const candidates = resolution.candidates
822
+ .map((candidate) => `- ${candidate.documentPath}#${candidate.anchor}:${candidate.line} (${candidate.heading})`)
823
+ .join("\n");
824
+ return `Ambiguous section query: ${resolution.query}\n${candidates}`;
825
+ }
826
+ return `Node not found: ${resolution.query}`;
827
+ }
828
+ function formatTraceStep(step) {
829
+ const edge = `${step.edgeKind}/${step.provenance}/${step.confidence}`;
830
+ return step.traversalDirection === "forward"
831
+ ? `${step.fromLabel} --${edge}--> ${step.toLabel}`
832
+ : `${step.fromLabel} <--${edge}-- ${step.toLabel}`;
833
+ }
834
+ function parseInteger(value) {
835
+ const parsed = Number.parseInt(value, 10);
836
+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || String(parsed) !== value.trim()) {
837
+ throw new Error(`Expected a positive integer, got ${value}`);
838
+ }
839
+ return parsed;
840
+ }
841
+ function parseSearchQueryMode(value) {
842
+ if (value === "auto" || value === "keyword" || value === "semantic") {
843
+ return value;
844
+ }
845
+ throw new Error(`Expected query mode to be one of auto, keyword, or semantic; got ${value}`);
846
+ }
847
+ function doctorIssueCount(summary) {
848
+ return Object.entries(summary)
849
+ .filter(([key]) => key !== "documents")
850
+ .reduce((total, [, value]) => total + Number(value), 0);
851
+ }
852
+ function parseDoctorSeverity(value) {
853
+ if (value === undefined) {
854
+ return undefined;
855
+ }
856
+ if (value === "error" || value === "warn" || value === "info") {
857
+ return value;
858
+ }
859
+ throw new Error(`Expected --fail-on to be one of error, warn, or info; got ${value}`);
860
+ }
861
+ function doctorWarningsAtOrAbove(warnings, severity) {
862
+ const threshold = doctorSeverityRank(severity);
863
+ return warnings.some((warning) => doctorSeverityRank(warning.severity) <= threshold);
864
+ }
865
+ function doctorSeverityRank(severity) {
866
+ return severity === "error" ? 0 : severity === "warn" ? 1 : 2;
867
+ }
868
+ function validateProjectRoot(projectRoot) {
869
+ const resolved = path.resolve(projectRoot);
870
+ if (!fs.existsSync(resolved)) {
871
+ throw new Error(`Project root does not exist: ${resolved}`);
872
+ }
873
+ if (!fs.statSync(resolved).isDirectory()) {
874
+ throw new Error(`Project root is not a directory: ${resolved}`);
875
+ }
876
+ return resolved;
877
+ }