@daogee/mdgraph 1.0.0 → 1.2.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.
- package/CHANGELOG.md +51 -0
- package/README-ZH.md +66 -4
- package/README.md +84 -22
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +3 -1
- package/agent-pack/prompts/wiki-authoring.md +12 -0
- package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
- package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
- package/dist/analysis/status-freshness.d.ts +8 -1
- package/dist/analysis/status-freshness.js +19 -6
- package/dist/bin/mdgraph.js +260 -25
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +55 -4
- package/dist/db/repositories.js +458 -11
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +25 -5
- package/dist/evaluation/retrieval-eval.js +79 -7
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -4
- package/dist/indexer.js +80 -4
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +21 -11
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +116 -18
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +32 -2
- package/dist/query/context-builder.js +191 -12
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +85 -16
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +136 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +151 -17
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/dist/wiki/wiki-dependencies.d.ts +20 -0
- package/dist/wiki/wiki-dependencies.js +45 -0
- package/dist/wiki/wiki-domains.d.ts +13 -0
- package/dist/wiki/wiki-domains.js +55 -0
- package/dist/wiki/wiki-evidence.d.ts +27 -0
- package/dist/wiki/wiki-evidence.js +112 -0
- package/dist/wiki/wiki-plan.d.ts +121 -0
- package/dist/wiki/wiki-plan.js +616 -0
- package/dist/wiki/wiki-status.d.ts +67 -0
- package/dist/wiki/wiki-status.js +451 -0
- package/docs/EN/Agent_Integration.md +15 -5
- package/docs/EN/Architecture.md +52 -16
- package/docs/EN/Evaluation_Questions.md +35 -5
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +111 -0
- package/docs/EN/Output_Contracts.md +83 -10
- package/docs/EN/Public_Contracts.md +25 -16
- package/docs/EN/Public_Contracts_1.0.md +32 -18
- package/docs/EN/README.md +24 -0
- package/docs/EN/Release_Checklist.md +27 -13
- package/docs/EN/Retrieval_and_Context.md +118 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +15 -5
- package/docs/ZH/Architecture.md +52 -21
- package/docs/ZH/Evaluation_Questions.md +36 -6
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +111 -0
- package/docs/ZH/Output_Contracts.md +83 -10
- package/docs/ZH/Public_Contracts.md +24 -15
- package/docs/ZH/Public_Contracts_1.0.md +31 -17
- package/docs/ZH/README.md +24 -0
- package/docs/ZH/Release_Checklist.md +27 -13
- package/docs/ZH/Retrieval_and_Context.md +118 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +50 -19
package/dist/bin/mdgraph.js
CHANGED
|
@@ -10,20 +10,25 @@ import { databasePath, initProjectConfig, loadConfig } from "../config/load-conf
|
|
|
10
10
|
import { openExistingDatabase } from "../db/connection.js";
|
|
11
11
|
import { GraphRepository } from "../db/repositories.js";
|
|
12
12
|
import { formatGraphDiff, generateGraphDiff } from "../diff/graph-diff.js";
|
|
13
|
-
import { EVALUATION_QUERY_SET_NAMES,
|
|
13
|
+
import { EVALUATION_QUERY_SET_NAMES, evaluateRetrievalAsync } from "../evaluation/retrieval-eval.js";
|
|
14
14
|
import { buildMermaidTraceExport } from "../export/diagram.js";
|
|
15
15
|
import { buildGraphJsonExport, formatGraphJsonVerification, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "../export/graphjson.js";
|
|
16
16
|
import { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "../export/markdown-index.js";
|
|
17
17
|
import { buildSourceBridgeReport } from "../export/source-bridge.js";
|
|
18
18
|
import { indexProject } from "../indexer.js";
|
|
19
19
|
import { startStdioMcpServer } from "../mcp/server.js";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
20
|
+
import { CONTEXT_PACKING_STRATEGIES, buildContextAsync } from "../query/context-builder.js";
|
|
21
|
+
import { explainSearchGraphAsync } from "../query/search.js";
|
|
22
|
+
import { buildKnowledgeCard, formatKnowledgeCard } from "../query/knowledge-card.js";
|
|
22
23
|
import { traceNodes } from "../query/trace.js";
|
|
24
|
+
import { executeStructuredQuery } from "../query/structured-query-executor.js";
|
|
25
|
+
import { deriveRelatedRelationships } from "../relationships/derive-related.js";
|
|
23
26
|
import { formatReport, generateReport } from "../reporting/report.js";
|
|
24
|
-
import {
|
|
27
|
+
import { semanticStatusReportAsync } from "../semantic/status.js";
|
|
25
28
|
import { packageVersion } from "../version.js";
|
|
26
29
|
import { watchProject } from "../watcher/file-watcher.js";
|
|
30
|
+
import { buildWikiPageBrief, buildWikiPlan, formatWikiPageBrief, formatWikiPlan, readWikiPlan, writeWikiPlan } from "../wiki/wiki-plan.js";
|
|
31
|
+
import { buildWikiStatus, formatWikiStatus, formatWikiVerification, verifyWiki } from "../wiki/wiki-status.js";
|
|
27
32
|
const program = new Command();
|
|
28
33
|
program
|
|
29
34
|
.name("mdgraph")
|
|
@@ -111,18 +116,18 @@ program
|
|
|
111
116
|
.option("--semantic", "Include local semantic vector matches when vectors are indexed")
|
|
112
117
|
.option("--explain", "Include query parsing and ranking explanation details")
|
|
113
118
|
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
114
|
-
.action((query, options) => {
|
|
119
|
+
.action(async (query, options) => {
|
|
115
120
|
const projectRoot = projectRootFromOption(options.path);
|
|
116
121
|
const config = loadConfig(projectRoot);
|
|
117
122
|
const repository = openRepository(projectRoot);
|
|
118
123
|
try {
|
|
124
|
+
const explanation = await explainSearchGraphAsync(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
|
|
125
|
+
printSemanticDiagnostic(explanation.semanticDiagnostic);
|
|
119
126
|
if (options.explain) {
|
|
120
|
-
const explanation = explainSearchGraph(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
|
|
121
127
|
printResult(options.json, explanation, formatSearchExplanation(explanation));
|
|
122
128
|
return;
|
|
123
129
|
}
|
|
124
|
-
|
|
125
|
-
printResult(options.json, results, formatSearchResults(results));
|
|
130
|
+
printResult(options.json, explanation.results, formatSearchResults(explanation.results));
|
|
126
131
|
}
|
|
127
132
|
finally {
|
|
128
133
|
closeRepository(repository);
|
|
@@ -134,19 +139,43 @@ program
|
|
|
134
139
|
.argument("<query>")
|
|
135
140
|
.option("--json", "Print JSON output")
|
|
136
141
|
.option("--debug", "Include context packing and graph expansion debug details")
|
|
142
|
+
.option("--packing <strategy>", `Context packing strategy: ${CONTEXT_PACKING_STRATEGIES.join(" | ")}`, parseContextPackingStrategy)
|
|
143
|
+
.option("--mmr-lambda <number>", "MMR query-relevance weight from 0 to 1", parseUnitInterval)
|
|
137
144
|
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
138
|
-
.action((query, options) => {
|
|
145
|
+
.action(async (query, options) => {
|
|
139
146
|
const projectRoot = projectRootFromOption(options.path);
|
|
140
147
|
const config = loadConfig(projectRoot);
|
|
141
148
|
const repository = openRepository(projectRoot);
|
|
142
149
|
try {
|
|
143
|
-
const context =
|
|
150
|
+
const context = await buildContextAsync(repository, config, query, {
|
|
151
|
+
debug: options.debug,
|
|
152
|
+
packingStrategy: options.packing,
|
|
153
|
+
mmrLambda: options.mmrLambda
|
|
154
|
+
});
|
|
155
|
+
printSemanticDiagnostic(context.semanticDiagnostic);
|
|
144
156
|
printResult(options.json, context, formatContext(context));
|
|
145
157
|
}
|
|
146
158
|
finally {
|
|
147
159
|
closeRepository(repository);
|
|
148
160
|
}
|
|
149
161
|
});
|
|
162
|
+
program
|
|
163
|
+
.command("query")
|
|
164
|
+
.description("Run an experimental deterministic structured document query")
|
|
165
|
+
.argument("<expression>", "Structured expression, for example: type:adr AND status:accepted")
|
|
166
|
+
.option("--json", "Print JSON output")
|
|
167
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
168
|
+
.action(async (expression, options) => {
|
|
169
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
170
|
+
const repository = openRepository(projectRoot);
|
|
171
|
+
try {
|
|
172
|
+
const result = await executeStructuredQuery(repository, projectRoot, expression);
|
|
173
|
+
printResult(options.json, result, formatStructuredQueryResult(result));
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
closeRepository(repository);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
150
179
|
program
|
|
151
180
|
.command("node")
|
|
152
181
|
.description("Show a document, entity, source ref, section, or chunk")
|
|
@@ -157,7 +186,8 @@ program
|
|
|
157
186
|
const repository = openRepository(projectRootFromOption(options.path));
|
|
158
187
|
try {
|
|
159
188
|
const resolution = repository.resolveNodeDetailed(query);
|
|
160
|
-
|
|
189
|
+
const card = resolution.status === "found" ? buildKnowledgeCard(repository, resolution.node) : undefined;
|
|
190
|
+
printResult(options.json, nodeResolutionJson(resolution, card), formatNodeResolution(resolution, card));
|
|
161
191
|
}
|
|
162
192
|
finally {
|
|
163
193
|
closeRepository(repository);
|
|
@@ -189,12 +219,15 @@ program
|
|
|
189
219
|
.option("--limit <number>", "Search results per evaluation case", parseInteger)
|
|
190
220
|
.option("--query-set <name>", `Evaluation query set (${EVALUATION_QUERY_SET_NAMES.join(", ")})`, "alpha")
|
|
191
221
|
.option("--query-mode <mode>", "Search query mode for evaluation (auto, keyword, semantic)", parseSearchQueryMode, "auto")
|
|
192
|
-
.action((options) => {
|
|
222
|
+
.action(async (options) => {
|
|
193
223
|
const projectRoot = validateProjectRoot(options.path);
|
|
194
224
|
const config = loadConfig(projectRoot);
|
|
195
225
|
const repository = openRepository(projectRoot);
|
|
196
226
|
try {
|
|
197
|
-
const report =
|
|
227
|
+
const report = await evaluateRetrievalAsync(repository, config, { limit: options.limit, querySet: options.querySet, queryMode: options.queryMode });
|
|
228
|
+
for (const diagnostic of report.ranking.semanticDiagnostics ?? []) {
|
|
229
|
+
printSemanticDiagnostic(diagnostic);
|
|
230
|
+
}
|
|
198
231
|
printResult(options.json, report, formatEvaluationReport(report));
|
|
199
232
|
}
|
|
200
233
|
finally {
|
|
@@ -209,23 +242,146 @@ semanticCommand
|
|
|
209
242
|
.description("Show semantic provider, vector coverage, and reindex guidance")
|
|
210
243
|
.option("--json", "Print JSON output")
|
|
211
244
|
.option("--path <path>", "Project root to inspect", process.cwd())
|
|
212
|
-
.action((options) => {
|
|
245
|
+
.action(async (options) => {
|
|
213
246
|
const projectRoot = validateProjectRoot(options.path);
|
|
214
247
|
const config = loadConfig(projectRoot);
|
|
215
248
|
if (!fs.existsSync(databasePath(projectRoot))) {
|
|
216
|
-
const report =
|
|
249
|
+
const report = await semanticStatusReportAsync(config, undefined, undefined);
|
|
217
250
|
printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
|
|
218
251
|
return;
|
|
219
252
|
}
|
|
220
253
|
const repository = openRepository(projectRoot);
|
|
221
254
|
try {
|
|
222
|
-
const report =
|
|
255
|
+
const report = await semanticStatusReportAsync(config, repository.counts(), repository.storageDiagnostics());
|
|
223
256
|
printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
|
|
224
257
|
}
|
|
225
258
|
finally {
|
|
226
259
|
closeRepository(repository);
|
|
227
260
|
}
|
|
228
261
|
});
|
|
262
|
+
const relationshipsCommand = program
|
|
263
|
+
.command("relationships")
|
|
264
|
+
.description("Manage opt-in derived graph relationships");
|
|
265
|
+
relationshipsCommand
|
|
266
|
+
.command("derive")
|
|
267
|
+
.description("Derive provider-gated RELATED_TO edges from indexed semantic vectors")
|
|
268
|
+
.option("--json", "Print JSON output")
|
|
269
|
+
.option("--threshold <number>", "Minimum independent chunk similarity from 0.75 to 1", parseUnitInterval)
|
|
270
|
+
.option("--max-neighbors <number>", "Maximum reciprocal neighbors per document from 1 to 10", parseInteger)
|
|
271
|
+
.option("--min-evidence <number>", "Independent section-pair evidence required from 2 to 4", parseInteger)
|
|
272
|
+
.option("--dry-run", "Evaluate relationships without replacing stored derived edges")
|
|
273
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
274
|
+
.action(async (options) => {
|
|
275
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
276
|
+
const config = loadConfig(projectRoot);
|
|
277
|
+
const repository = openRepository(projectRoot);
|
|
278
|
+
try {
|
|
279
|
+
const report = await deriveRelatedRelationships(repository, projectRoot, config, {
|
|
280
|
+
threshold: options.threshold,
|
|
281
|
+
maxNeighbors: options.maxNeighbors,
|
|
282
|
+
minEvidence: options.minEvidence,
|
|
283
|
+
dryRun: options.dryRun
|
|
284
|
+
});
|
|
285
|
+
printResult(options.json, report, formatDerivedRelationships(report));
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
closeRepository(repository);
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
const wikiCommand = program
|
|
292
|
+
.command("wiki")
|
|
293
|
+
.description("Plan, brief, inspect, and verify a user-maintained project Wiki");
|
|
294
|
+
wikiCommand
|
|
295
|
+
.command("plan")
|
|
296
|
+
.description("Create a deterministic WikiPlan without generating page prose")
|
|
297
|
+
.requiredOption("--out <file>", "WikiPlan JSON output path")
|
|
298
|
+
.option("--from <file>", "Preserve authored pages from an existing plan and suggest new evidence")
|
|
299
|
+
.option("--wiki-dir <dir>", "Project-relative Wiki output directory (required when migrating a v1 plan)")
|
|
300
|
+
.option("--json", "Print JSON output")
|
|
301
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
302
|
+
.action((options) => {
|
|
303
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
304
|
+
const out = resolveProjectArtifactPath(projectRoot, options.out);
|
|
305
|
+
const fromPath = options.from ? resolveProjectArtifactPath(projectRoot, options.from) : undefined;
|
|
306
|
+
if (fromPath && out === fromPath) {
|
|
307
|
+
throw new Error("Choose a different --out path when updating a plan with --from; review the new plan before replacing the original.");
|
|
308
|
+
}
|
|
309
|
+
const from = fromPath ? readWikiPlan(fromPath) : undefined;
|
|
310
|
+
const repository = openRepository(projectRoot);
|
|
311
|
+
try {
|
|
312
|
+
const plan = buildWikiPlan(projectRoot, repository, { from, wikiDir: options.wikiDir });
|
|
313
|
+
writeWikiPlan(out, plan);
|
|
314
|
+
printResult(options.json, { out, plan }, [`Wrote Wiki plan: ${out}`, formatWikiPlan(plan)].join("\n"));
|
|
315
|
+
}
|
|
316
|
+
finally {
|
|
317
|
+
closeRepository(repository);
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
wikiCommand
|
|
321
|
+
.command("brief")
|
|
322
|
+
.description("Build an evidence-bounded brief for one planned Wiki page")
|
|
323
|
+
.argument("<page-id>")
|
|
324
|
+
.requiredOption("--plan <file>", "WikiPlan JSON path")
|
|
325
|
+
.option("--json", "Print JSON output")
|
|
326
|
+
.option("--max-chars <number>", "Maximum context and Knowledge Card characters", parseInteger)
|
|
327
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
328
|
+
.action((pageId, options) => {
|
|
329
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
330
|
+
const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
|
|
331
|
+
const plan = readWikiPlan(planPath);
|
|
332
|
+
const config = loadConfig(projectRoot);
|
|
333
|
+
const repository = openRepository(projectRoot);
|
|
334
|
+
try {
|
|
335
|
+
const brief = buildWikiPageBrief(projectRoot, repository, config, plan, pageId, { maxChars: options.maxChars });
|
|
336
|
+
printResult(options.json, brief, formatWikiPageBrief(brief));
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
closeRepository(repository);
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
wikiCommand
|
|
343
|
+
.command("status")
|
|
344
|
+
.description("Report current, needs-update, missing, and orphaned Wiki pages without modifying them")
|
|
345
|
+
.argument("<wiki-dir>")
|
|
346
|
+
.requiredOption("--plan <file>", "WikiPlan JSON path")
|
|
347
|
+
.option("--json", "Print JSON output")
|
|
348
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
349
|
+
.action((wikiDir, options) => {
|
|
350
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
351
|
+
const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
|
|
352
|
+
const plan = readWikiPlan(planPath);
|
|
353
|
+
const repository = openRepository(projectRoot);
|
|
354
|
+
try {
|
|
355
|
+
const status = buildWikiStatus(projectRoot, repository, resolveProjectArtifactPath(projectRoot, wikiDir), plan, { planPath });
|
|
356
|
+
printResult(options.json, status, formatWikiStatus(status));
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
closeRepository(repository);
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
wikiCommand
|
|
363
|
+
.command("verify")
|
|
364
|
+
.description("Verify Wiki plan, maintenance fields, source paths, evidence freshness, and relative links")
|
|
365
|
+
.argument("<wiki-dir>")
|
|
366
|
+
.requiredOption("--plan <file>", "WikiPlan JSON path")
|
|
367
|
+
.option("--json", "Print JSON output")
|
|
368
|
+
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
369
|
+
.action((wikiDir, options) => {
|
|
370
|
+
const projectRoot = projectRootFromOption(options.path);
|
|
371
|
+
const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
|
|
372
|
+
const plan = readWikiPlan(planPath);
|
|
373
|
+
const repository = openRepository(projectRoot);
|
|
374
|
+
try {
|
|
375
|
+
const verification = verifyWiki(projectRoot, repository, resolveProjectArtifactPath(projectRoot, wikiDir), plan, { planPath });
|
|
376
|
+
printResult(options.json, verification, formatWikiVerification(verification));
|
|
377
|
+
if (!verification.valid) {
|
|
378
|
+
process.exitCode = 1;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
finally {
|
|
382
|
+
closeRepository(repository);
|
|
383
|
+
}
|
|
384
|
+
});
|
|
229
385
|
const bundleCommand = program
|
|
230
386
|
.command("bundle")
|
|
231
387
|
.description("Create and verify reusable local graph bundle artifacts");
|
|
@@ -424,6 +580,7 @@ program
|
|
|
424
580
|
.option("--no-watch", "Disable automatic index updates while serving MCP requests")
|
|
425
581
|
.option("--semantic", "Build local semantic vectors during watch indexing")
|
|
426
582
|
.option("--debounce <ms>", "Debounce delay in milliseconds for serve watch mode", parseInteger)
|
|
583
|
+
.option("--watch-poll", "Use explicit polling instead of native file-system events")
|
|
427
584
|
.option("--path <path>", "Project root to serve", process.cwd())
|
|
428
585
|
.action((options) => {
|
|
429
586
|
if (!options.mcp) {
|
|
@@ -434,7 +591,8 @@ program
|
|
|
434
591
|
projectRoot: validateProjectRoot(options.path),
|
|
435
592
|
watch,
|
|
436
593
|
semantic: watch ? options.semantic : undefined,
|
|
437
|
-
debounceMs: watch ? options.debounce : undefined
|
|
594
|
+
debounceMs: watch ? options.debounce : undefined,
|
|
595
|
+
usePolling: watch ? options.watchPoll : undefined
|
|
438
596
|
});
|
|
439
597
|
});
|
|
440
598
|
program
|
|
@@ -442,18 +600,29 @@ program
|
|
|
442
600
|
.description("Watch Markdown files and incrementally update the graph index")
|
|
443
601
|
.option("--semantic", "Build local semantic vectors during watch indexing")
|
|
444
602
|
.option("--debounce <ms>", "Debounce delay in milliseconds", parseInteger)
|
|
603
|
+
.option("--poll", "Use explicit polling instead of native file-system events")
|
|
445
604
|
.option("--path <path>", "Project root. Defaults to the current working directory")
|
|
446
605
|
.action(async (options) => {
|
|
447
606
|
const projectRoot = projectRootFromOption(options.path);
|
|
448
607
|
console.error("MDGraph watch started. Press Ctrl+C to stop.");
|
|
608
|
+
let lastHealthState;
|
|
449
609
|
const handle = await watchProject(projectRoot, {
|
|
450
610
|
semantic: options.semantic,
|
|
451
611
|
debounceMs: options.debounce,
|
|
612
|
+
usePolling: options.poll,
|
|
452
613
|
onIndexed: (result) => {
|
|
453
614
|
console.error(`Indexed ${result.changed} changed, ${result.deleted} deleted, ${result.unchanged} unchanged, ${result.skipped} skipped document(s).`);
|
|
454
615
|
},
|
|
455
616
|
onError: (error) => {
|
|
456
|
-
console.error(`Watch
|
|
617
|
+
console.error(`Watch error: ${error.message}`);
|
|
618
|
+
},
|
|
619
|
+
onHealthChanged: (health) => {
|
|
620
|
+
if (health.state === lastHealthState) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
lastHealthState = health.state;
|
|
624
|
+
const error = health.lastError ? ` (${health.lastError.code}/${health.lastError.phase}: ${health.lastError.message})` : "";
|
|
625
|
+
console.error(`Watch health: ${health.state}${health.polling ? " [polling]" : ""}${error}`);
|
|
457
626
|
}
|
|
458
627
|
});
|
|
459
628
|
await new Promise((resolve) => {
|
|
@@ -558,6 +727,17 @@ function buildUsageGuide(projectRoot) {
|
|
|
558
727
|
`mdgraph trace "Architecture.md" "src/indexer.ts" --path ${project}`
|
|
559
728
|
]
|
|
560
729
|
},
|
|
730
|
+
{
|
|
731
|
+
name: "Wiki Maintenance",
|
|
732
|
+
purpose: "Plan and maintain a user-authored project Wiki from deterministic evidence without generating prose inside MDGraph.",
|
|
733
|
+
commands: [
|
|
734
|
+
`mdgraph wiki plan --out .mdgraph/wiki-plan.json --path ${project}`,
|
|
735
|
+
`mdgraph wiki brief architecture --plan .mdgraph/wiki-plan.json --json --path ${project}`,
|
|
736
|
+
`mdgraph wiki status wiki --plan .mdgraph/wiki-plan.json --json --path ${project}`,
|
|
737
|
+
`mdgraph wiki verify wiki --plan .mdgraph/wiki-plan.json --json --path ${project}`
|
|
738
|
+
],
|
|
739
|
+
notes: ["Status and verify are read-only; the host agent writes pages and preserves user-authored prose."]
|
|
740
|
+
},
|
|
561
741
|
{
|
|
562
742
|
name: "CI And Artifacts",
|
|
563
743
|
purpose: "Produce reproducible graph reports and interoperability artifacts.",
|
|
@@ -571,7 +751,7 @@ function buildUsageGuide(projectRoot) {
|
|
|
571
751
|
{
|
|
572
752
|
name: "Help",
|
|
573
753
|
purpose: "Inspect syntax for all commands or a specific command.",
|
|
574
|
-
commands: ["mdgraph help", "mdgraph help search", "mdgraph usage --json"]
|
|
754
|
+
commands: ["mdgraph help", "mdgraph help search", "mdgraph help query", "mdgraph usage --json"]
|
|
575
755
|
},
|
|
576
756
|
{
|
|
577
757
|
name: "Agent MCP",
|
|
@@ -612,6 +792,9 @@ function shellPath(value) {
|
|
|
612
792
|
function projectRootFromOption(projectRoot) {
|
|
613
793
|
return validateProjectRoot(projectRoot ?? process.cwd());
|
|
614
794
|
}
|
|
795
|
+
function resolveProjectArtifactPath(projectRoot, artifactPath) {
|
|
796
|
+
return path.isAbsolute(artifactPath) ? path.resolve(artifactPath) : path.resolve(projectRoot, artifactPath);
|
|
797
|
+
}
|
|
615
798
|
function formatIndexResult(result) {
|
|
616
799
|
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
800
|
}
|
|
@@ -695,7 +878,8 @@ function formatContext(context) {
|
|
|
695
878
|
.map((item, index) => {
|
|
696
879
|
const heading = item.heading ? `# ${item.heading}` : item.title;
|
|
697
880
|
const lines = item.lines ? `:${item.lines.start}` : "";
|
|
698
|
-
|
|
881
|
+
const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
|
|
882
|
+
return `## ${index + 1}. ${item.path}${lines}\nReason: ${item.reason}${cardSummary}\n${heading}\n${item.content}`;
|
|
699
883
|
})
|
|
700
884
|
.join("\n\n");
|
|
701
885
|
if (!context.debug) {
|
|
@@ -710,9 +894,35 @@ function formatContext(context) {
|
|
|
710
894
|
`Expanded edges: ${context.debug.expandedEdges}`,
|
|
711
895
|
`Candidates: ${context.debug.candidateCount} (${context.debug.directCandidates} direct, ${context.debug.expandedCandidates} expanded)`,
|
|
712
896
|
`Packing: ${context.debug.packingStrategy}, items: ${context.debug.packedItems}, unique documents: ${context.debug.packedUniqueDocuments}, diversity: ${context.debug.packingDiversityRatio.toFixed(2)}`,
|
|
897
|
+
context.debug.mmrLambda !== undefined
|
|
898
|
+
? `MMR: lambda ${context.debug.mmrLambda.toFixed(2)}, similarity: ${context.debug.packingSimilarity}, redundancy skipped: ${context.debug.redundancySkippedItems ?? 0}`
|
|
899
|
+
: "",
|
|
713
900
|
`Skipped visited: ${context.debug.skippedVisitedNodes}, node-limit: ${context.debug.skippedByNodeLimit}, depth: ${context.debug.skippedByDepth}`,
|
|
714
901
|
`Budget truncated items: ${context.debug.budgetTruncatedItems}, skipped items: ${context.debug.budgetSkippedItems}`
|
|
715
|
-
].join("\n");
|
|
902
|
+
].filter(Boolean).join("\n");
|
|
903
|
+
}
|
|
904
|
+
function formatStructuredQueryResult(result) {
|
|
905
|
+
const header = [
|
|
906
|
+
"MDGraph structured query",
|
|
907
|
+
`Query: ${result.query}`,
|
|
908
|
+
`Execution: ${result.execution.strategy} (${result.execution.stages.join(", ")}; ${result.execution.parameterCount} SQL parameter(s))`,
|
|
909
|
+
`Matches: ${result.total}; returned: ${result.returned}${result.truncated ? " (truncated)" : ""}`
|
|
910
|
+
];
|
|
911
|
+
const items = result.items.map((item) => (`- ${item.document.path} [${item.document.type}/${item.document.status}; ${item.document.trustTier}]`));
|
|
912
|
+
return [...header, ...(items.length ? ["Results:", ...items] : ["No documents matched."])].join("\n");
|
|
913
|
+
}
|
|
914
|
+
function formatDerivedRelationships(report) {
|
|
915
|
+
const lines = [
|
|
916
|
+
"MDGraph derived relationships",
|
|
917
|
+
`Provider: ${report.provider}/${report.model} (${report.dimensions} dimensions)`,
|
|
918
|
+
`Gate: ${report.qualityGate.id} passed`,
|
|
919
|
+
`Corpus: ${report.corpus.eligibleDocuments}/${report.corpus.documents} eligible documents, ${report.corpus.vectors}/${report.corpus.chunks} vectors`,
|
|
920
|
+
`Relationships: ${report.relationshipPairs} pair(s), ${report.directedEdges} directed edge(s)${report.options.dryRun ? " [dry run]" : ""}`
|
|
921
|
+
];
|
|
922
|
+
if (report.relationships.length) {
|
|
923
|
+
lines.push("Matches:", ...report.relationships.map((relationship) => (`- ${relationship.fromPath} <-> ${relationship.toPath} (${relationship.confidence.toFixed(4)}, ${relationship.evidenceSections.length} evidence section pair(s))`)));
|
|
924
|
+
}
|
|
925
|
+
return lines.join("\n");
|
|
716
926
|
}
|
|
717
927
|
function formatTrace(trace) {
|
|
718
928
|
if (!trace.found) {
|
|
@@ -739,6 +949,8 @@ function formatEvaluationReport(report) {
|
|
|
739
949
|
`${result.id}: ${status}`,
|
|
740
950
|
` query: ${result.query}`,
|
|
741
951
|
` topKDocumentRecall=${formatMetric(result.metrics.topKDocumentRecall)}, expectedSectionRecall=${formatMetric(result.metrics.expectedSectionRecall)}, contextPrecision=${formatMetric(result.metrics.contextPrecision)}, contextDiversity=${formatMetric(result.metrics.contextDiversity)}`,
|
|
952
|
+
` retrievedEntityRecall=${formatMetric(result.metrics.retrievedEntityRecall)}, retrievedSourceRefRecall=${formatMetric(result.metrics.retrievedSourceRefRecall)}, retrievedEdgeKindCoverage=${formatMetric(result.metrics.retrievedEdgeKindCoverage)}, evidencePassed=${result.retrievalEvidencePassed}`,
|
|
953
|
+
` contextIrrelevantRatio=${formatMetric(result.metrics.contextIrrelevantRatio)}`,
|
|
742
954
|
` traceSuccess=${result.metrics.traceSuccess ?? "n/a"}, returnedChars=${result.metrics.returnedChars}, budgetFit=${result.metrics.budgetFit}`
|
|
743
955
|
].join("\n");
|
|
744
956
|
})
|
|
@@ -752,6 +964,8 @@ function formatSemanticStatus(projectRoot, report) {
|
|
|
752
964
|
`State: ${report.state}`,
|
|
753
965
|
`Configured provider: ${report.provider}/${report.model} (${report.dimensions} dimensions, enabled: ${report.enabled})`,
|
|
754
966
|
`Provider supported: ${report.providerSupported}`,
|
|
967
|
+
`Provider capability: ${report.capability}`,
|
|
968
|
+
`Provider runtime: ${report.runtimeStatus}${report.runtimeReason ? ` - ${report.runtimeReason}` : ""}`,
|
|
755
969
|
`Indexed: ${report.indexed}`,
|
|
756
970
|
`Vectors: ${report.vectors}/${report.chunks} chunks`,
|
|
757
971
|
`Vector storage: ${report.vectorStorageFormat}`,
|
|
@@ -759,6 +973,11 @@ function formatSemanticStatus(projectRoot, report) {
|
|
|
759
973
|
`Guidance: ${report.guidance.join(" ") || "none"}`
|
|
760
974
|
].join("\n");
|
|
761
975
|
}
|
|
976
|
+
function printSemanticDiagnostic(diagnostic) {
|
|
977
|
+
if (diagnostic) {
|
|
978
|
+
console.error(`MDGraph semantic fallback [${diagnostic.provider}/${diagnostic.code}]: ${diagnostic.message}`);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
762
981
|
function formatBundleCreate(result) {
|
|
763
982
|
return [
|
|
764
983
|
"Created MDGraph bundle",
|
|
@@ -804,18 +1023,21 @@ function formatSourceBridgeReport(report) {
|
|
|
804
1023
|
function formatMetric(value) {
|
|
805
1024
|
return value.toFixed(2);
|
|
806
1025
|
}
|
|
807
|
-
function nodeResolutionJson(resolution) {
|
|
1026
|
+
function nodeResolutionJson(resolution, card) {
|
|
808
1027
|
if (resolution.status === "found") {
|
|
809
|
-
return resolution.node;
|
|
1028
|
+
return card ? { ...resolution.node, card } : resolution.node;
|
|
810
1029
|
}
|
|
811
1030
|
if (resolution.status === "ambiguous") {
|
|
812
1031
|
return { error: resolution.error, query: resolution.query, candidates: resolution.candidates };
|
|
813
1032
|
}
|
|
814
1033
|
return { error: resolution.error, query: resolution.query };
|
|
815
1034
|
}
|
|
816
|
-
function formatNodeResolution(resolution) {
|
|
1035
|
+
function formatNodeResolution(resolution, card) {
|
|
817
1036
|
if (resolution.status === "found") {
|
|
818
|
-
return
|
|
1037
|
+
return [
|
|
1038
|
+
`${resolution.node.kind}: ${resolution.node.label}`,
|
|
1039
|
+
card ? formatKnowledgeCard(card) : ""
|
|
1040
|
+
].filter(Boolean).join("\n\n");
|
|
819
1041
|
}
|
|
820
1042
|
if (resolution.status === "ambiguous") {
|
|
821
1043
|
const candidates = resolution.candidates
|
|
@@ -844,6 +1066,19 @@ function parseSearchQueryMode(value) {
|
|
|
844
1066
|
}
|
|
845
1067
|
throw new Error(`Expected query mode to be one of auto, keyword, or semantic; got ${value}`);
|
|
846
1068
|
}
|
|
1069
|
+
function parseContextPackingStrategy(value) {
|
|
1070
|
+
if (CONTEXT_PACKING_STRATEGIES.includes(value)) {
|
|
1071
|
+
return value;
|
|
1072
|
+
}
|
|
1073
|
+
throw new Error(`Expected one of ${CONTEXT_PACKING_STRATEGIES.join(", ")}, got ${value}`);
|
|
1074
|
+
}
|
|
1075
|
+
function parseUnitInterval(value) {
|
|
1076
|
+
const parsed = Number(value);
|
|
1077
|
+
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1 || value.trim() === "") {
|
|
1078
|
+
throw new Error(`Expected a number from 0 to 1, got ${value}`);
|
|
1079
|
+
}
|
|
1080
|
+
return parsed;
|
|
1081
|
+
}
|
|
847
1082
|
function doctorIssueCount(summary) {
|
|
848
1083
|
return Object.entries(summary)
|
|
849
1084
|
.filter(([key]) => key !== "documents")
|
package/dist/config/limits.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ export declare const CONFIG_LIMITS: {
|
|
|
5
5
|
readonly searchMaxContextChars: 200000;
|
|
6
6
|
readonly searchHighFrequencyEntityThreshold: 100000;
|
|
7
7
|
readonly embeddingDimensions: 4096;
|
|
8
|
+
readonly embeddingTimeoutMs: 120000;
|
|
9
|
+
readonly embeddingBatchSize: 256;
|
|
8
10
|
};
|
|
9
11
|
export declare const MCP_LIMITS: {
|
|
10
12
|
readonly searchLimit: 100;
|
package/dist/config/limits.js
CHANGED
|
@@ -4,7 +4,9 @@ export const CONFIG_LIMITS = {
|
|
|
4
4
|
searchMaxDepth: 12,
|
|
5
5
|
searchMaxContextChars: 200_000,
|
|
6
6
|
searchHighFrequencyEntityThreshold: 100_000,
|
|
7
|
-
embeddingDimensions: 4096
|
|
7
|
+
embeddingDimensions: 4096,
|
|
8
|
+
embeddingTimeoutMs: 120_000,
|
|
9
|
+
embeddingBatchSize: 256
|
|
8
10
|
};
|
|
9
11
|
export const MCP_LIMITS = {
|
|
10
12
|
searchLimit: CONFIG_LIMITS.searchDefaultLimit,
|
|
@@ -57,7 +57,10 @@ export const DEFAULT_CONFIG = {
|
|
|
57
57
|
enabled: false,
|
|
58
58
|
provider: "local-hash",
|
|
59
59
|
model: "mdgraph-local-hash-v1",
|
|
60
|
-
dimensions: 128
|
|
60
|
+
dimensions: 128,
|
|
61
|
+
endpoint: "http://127.0.0.1:11434",
|
|
62
|
+
timeoutMs: 30_000,
|
|
63
|
+
batchSize: 16
|
|
61
64
|
}
|
|
62
65
|
};
|
|
63
66
|
export function configPath(projectRoot) {
|
|
@@ -143,7 +146,10 @@ function mergeConfig(base, override) {
|
|
|
143
146
|
enabled: boolOr(override.embedding?.enabled, base.embedding.enabled),
|
|
144
147
|
provider: stringOr(override.embedding?.provider, base.embedding.provider),
|
|
145
148
|
model: stringOr(override.embedding?.model, base.embedding.model),
|
|
146
|
-
dimensions: boundedPositiveInteger(override.embedding?.dimensions, base.embedding.dimensions, "embedding.dimensions", CONFIG_LIMITS.embeddingDimensions)
|
|
149
|
+
dimensions: boundedPositiveInteger(override.embedding?.dimensions, base.embedding.dimensions, "embedding.dimensions", CONFIG_LIMITS.embeddingDimensions),
|
|
150
|
+
endpoint: stringOr(override.embedding?.endpoint, base.embedding.endpoint ?? "http://127.0.0.1:11434"),
|
|
151
|
+
timeoutMs: boundedPositiveInteger(override.embedding?.timeoutMs, base.embedding.timeoutMs ?? 30_000, "embedding.timeoutMs", CONFIG_LIMITS.embeddingTimeoutMs),
|
|
152
|
+
batchSize: boundedPositiveInteger(override.embedding?.batchSize, base.embedding.batchSize ?? 16, "embedding.batchSize", CONFIG_LIMITS.embeddingBatchSize)
|
|
147
153
|
}
|
|
148
154
|
};
|
|
149
155
|
}
|
package/dist/db/connection.js
CHANGED
|
@@ -23,13 +23,14 @@ export function openDatabase(projectRoot, options = {}) {
|
|
|
23
23
|
}
|
|
24
24
|
catch (error) {
|
|
25
25
|
const message = error instanceof Error ? error.message : String(error);
|
|
26
|
-
throw new Error(`Failed to open MDGraph database at ${target}: ${message}.
|
|
26
|
+
throw new Error(`Failed to open MDGraph database at ${target}: ${message}. Use a Node.js build with node:sqlite and FTS5 (Node 22.23.2 or newer is verified), confirm the directory is writable, and run \`mdgraph index\` to rebuild the local index if the database is corrupt.`);
|
|
27
27
|
}
|
|
28
28
|
db.pragma("foreign_keys = ON");
|
|
29
29
|
db.pragma("busy_timeout = 5000");
|
|
30
30
|
if (applySchema) {
|
|
31
31
|
try {
|
|
32
32
|
assertCompatibleExistingSchema(db, target);
|
|
33
|
+
ensureFts5Available(db);
|
|
33
34
|
const hadMetadata = hasSchemaMetadata(db);
|
|
34
35
|
const schemaSql = readSchemaSql();
|
|
35
36
|
db.exec(schemaSql);
|
|
@@ -44,6 +45,21 @@ export function openDatabase(projectRoot, options = {}) {
|
|
|
44
45
|
}
|
|
45
46
|
return db;
|
|
46
47
|
}
|
|
48
|
+
function ensureFts5Available(db) {
|
|
49
|
+
const capability = db.prepare("SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled").get();
|
|
50
|
+
if (capability.enabled)
|
|
51
|
+
return;
|
|
52
|
+
try {
|
|
53
|
+
// A runtime can load FTS5 as an extension without the compile-time option.
|
|
54
|
+
// Confirm actual availability before declaring the capability absent.
|
|
55
|
+
db.exec("CREATE VIRTUAL TABLE temp.mdgraph_fts5_probe USING fts5(content); DROP TABLE temp.mdgraph_fts5_probe;");
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (!(error instanceof Error) || !error.message.includes("no such module: fts5"))
|
|
59
|
+
throw error;
|
|
60
|
+
throw Object.assign(new Error("SQLite FTS5 is unavailable in this Node.js build. Upgrade to a Node.js build with FTS5, such as the verified Node 22.23.2 runtime, then run `mdgraph index` again.", { cause: error }), { code: "sqlite_fts5_unavailable" });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
47
63
|
export function openExistingDatabase(projectRoot) {
|
|
48
64
|
return openDatabase(projectRoot, { createIfMissing: false, applySchema: true });
|
|
49
65
|
}
|