@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.
Files changed (106) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README-ZH.md +66 -4
  3. package/README.md +84 -22
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +3 -1
  6. package/agent-pack/prompts/wiki-authoring.md +12 -0
  7. package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
  8. package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
  9. package/dist/analysis/status-freshness.d.ts +8 -1
  10. package/dist/analysis/status-freshness.js +19 -6
  11. package/dist/bin/mdgraph.js +260 -25
  12. package/dist/config/limits.d.ts +2 -0
  13. package/dist/config/limits.js +3 -1
  14. package/dist/config/load-config.js +8 -2
  15. package/dist/db/connection.js +17 -1
  16. package/dist/db/repositories.d.ts +55 -4
  17. package/dist/db/repositories.js +458 -11
  18. package/dist/db/sqlite-adapter.js +8 -2
  19. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  20. package/dist/evaluation/context-packing-evaluation.js +134 -0
  21. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  22. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  23. package/dist/evaluation/historical-baseline.d.ts +70 -0
  24. package/dist/evaluation/historical-baseline.js +278 -0
  25. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  26. package/dist/evaluation/related-documents-evaluation.js +163 -0
  27. package/dist/evaluation/retrieval-eval.d.ts +25 -5
  28. package/dist/evaluation/retrieval-eval.js +79 -7
  29. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  30. package/dist/evaluation/structured-query-evaluation.js +156 -0
  31. package/dist/extraction/entity-extractor.js +42 -22
  32. package/dist/extraction/graph-builder.js +2 -18
  33. package/dist/index.d.ts +24 -4
  34. package/dist/index.js +12 -4
  35. package/dist/indexer.js +80 -4
  36. package/dist/mcp/server.d.ts +4 -0
  37. package/dist/mcp/server.js +21 -11
  38. package/dist/mcp/tools.d.ts +5 -1
  39. package/dist/mcp/tools.js +116 -18
  40. package/dist/parser/markdown-parser.js +2 -0
  41. package/dist/query/context-builder.d.ts +32 -2
  42. package/dist/query/context-builder.js +191 -12
  43. package/dist/query/knowledge-card.d.ts +90 -0
  44. package/dist/query/knowledge-card.js +676 -0
  45. package/dist/query/search.d.ts +5 -1
  46. package/dist/query/search.js +85 -16
  47. package/dist/query/structured-query-executor.d.ts +28 -0
  48. package/dist/query/structured-query-executor.js +138 -0
  49. package/dist/query/structured-query.d.ts +50 -0
  50. package/dist/query/structured-query.js +390 -0
  51. package/dist/relationships/derive-related.d.ts +86 -0
  52. package/dist/relationships/derive-related.js +322 -0
  53. package/dist/reporting/report.js +2 -2
  54. package/dist/semantic/embed-chunks.d.ts +2 -0
  55. package/dist/semantic/embed-chunks.js +31 -0
  56. package/dist/semantic/ollama-provider.d.ts +6 -0
  57. package/dist/semantic/ollama-provider.js +136 -0
  58. package/dist/semantic/provider-registry.d.ts +8 -0
  59. package/dist/semantic/provider-registry.js +66 -0
  60. package/dist/semantic/provider.d.ts +35 -0
  61. package/dist/semantic/provider.js +29 -0
  62. package/dist/semantic/status.d.ts +6 -1
  63. package/dist/semantic/status.js +49 -3
  64. package/dist/types.d.ts +7 -2
  65. package/dist/types.js +2 -1
  66. package/dist/utils/path-safety.d.ts +3 -0
  67. package/dist/utils/path-safety.js +27 -0
  68. package/dist/watcher/file-watcher.d.ts +4 -0
  69. package/dist/watcher/file-watcher.js +151 -17
  70. package/dist/watcher/watch-health.d.ts +34 -0
  71. package/dist/watcher/watch-health.js +75 -0
  72. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  73. package/dist/wiki/wiki-dependencies.js +45 -0
  74. package/dist/wiki/wiki-domains.d.ts +13 -0
  75. package/dist/wiki/wiki-domains.js +55 -0
  76. package/dist/wiki/wiki-evidence.d.ts +27 -0
  77. package/dist/wiki/wiki-evidence.js +112 -0
  78. package/dist/wiki/wiki-plan.d.ts +121 -0
  79. package/dist/wiki/wiki-plan.js +616 -0
  80. package/dist/wiki/wiki-status.d.ts +67 -0
  81. package/dist/wiki/wiki-status.js +451 -0
  82. package/docs/EN/Agent_Integration.md +15 -5
  83. package/docs/EN/Architecture.md +52 -16
  84. package/docs/EN/Evaluation_Questions.md +35 -5
  85. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  86. package/docs/EN/Operations.md +111 -0
  87. package/docs/EN/Output_Contracts.md +83 -10
  88. package/docs/EN/Public_Contracts.md +25 -16
  89. package/docs/EN/Public_Contracts_1.0.md +32 -18
  90. package/docs/EN/README.md +24 -0
  91. package/docs/EN/Release_Checklist.md +27 -13
  92. package/docs/EN/Retrieval_and_Context.md +118 -0
  93. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  94. package/docs/ZH/Agent_Integration.md +15 -5
  95. package/docs/ZH/Architecture.md +52 -21
  96. package/docs/ZH/Evaluation_Questions.md +36 -6
  97. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  98. package/docs/ZH/Operations.md +111 -0
  99. package/docs/ZH/Output_Contracts.md +83 -10
  100. package/docs/ZH/Public_Contracts.md +24 -15
  101. package/docs/ZH/Public_Contracts_1.0.md +31 -17
  102. package/docs/ZH/README.md +24 -0
  103. package/docs/ZH/Release_Checklist.md +27 -13
  104. package/docs/ZH/Retrieval_and_Context.md +118 -0
  105. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  106. package/package.json +50 -19
package/dist/indexer.js CHANGED
@@ -1,20 +1,57 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { loadConfig } from "./config/load-config.js";
2
3
  import { openDatabase } from "./db/connection.js";
3
- import { GraphRepository } from "./db/repositories.js";
4
+ import { GraphRepository, IndexGenerationConflict } from "./db/repositories.js";
4
5
  import { buildGraphRecords } from "./extraction/graph-builder.js";
5
6
  import { parseMarkdownDocument } from "./parser/markdown-parser.js";
6
7
  import { scanMarkdownFiles } from "./scanner/file-scanner.js";
8
+ import { embedChunks } from "./semantic/embed-chunks.js";
7
9
  import { relativePathInsideRoot } from "./utils/path-safety.js";
8
10
  export async function indexProject(projectRoot, options = {}) {
11
+ for (let attempt = 0; attempt < 2; attempt += 1) {
12
+ try {
13
+ return await indexProjectAttempt(projectRoot, options);
14
+ }
15
+ catch (error) {
16
+ if (!(error instanceof IndexGenerationConflict) || attempt === 1)
17
+ throw error;
18
+ }
19
+ }
20
+ throw new Error("Unreachable index retry state.");
21
+ }
22
+ async function indexProjectAttempt(projectRoot, options) {
9
23
  const config = effectiveConfig(loadConfig(projectRoot), options);
24
+ const fingerprint = extractionFingerprint(config);
25
+ // Capture generation before asynchronous scan/parse/embed work. The write CAS
26
+ // below rejects this candidate if another index finishes while it is prepared.
27
+ const preflightDb = openDatabase(projectRoot);
28
+ let expectedGeneration;
29
+ try {
30
+ expectedGeneration = new GraphRepository(preflightDb).indexWriteState().generation;
31
+ }
32
+ finally {
33
+ preflightDb.close();
34
+ }
10
35
  const files = await scanMarkdownFiles(projectRoot, config);
11
36
  const { parsed, skippedFiles } = parseScannedFiles(projectRoot, files);
12
37
  const records = buildGraphRecords(parsed, config);
13
38
  const db = openDatabase(projectRoot);
14
39
  try {
15
40
  const repository = new GraphRepository(db);
16
- if (options.full || repository.counts().documents === 0) {
17
- repository.replaceAll(records);
41
+ const existingCounts = repository.counts();
42
+ const writeState = repository.indexWriteState();
43
+ const requiresCompleteEmbedding = config.embedding.enabled && !hasMatchingVectorCoverage(repository, config, existingCounts);
44
+ const vectorProfileChanged = existingCounts.vectors > 0 && requiresCompleteEmbedding;
45
+ const requiresRebuild = options.full || existingCounts.documents === 0 || requiresCompleteEmbedding || writeState.extractionFingerprint !== fingerprint;
46
+ // A parser failure is a non-destructive condition: retain that document's last
47
+ // known graph until it can be parsed again, rather than turning a transient edit
48
+ // into a deletion during a requested rebuild.
49
+ if (requiresRebuild && skippedFiles.length === 0) {
50
+ records.vectors = await vectorsForChunks(repository, records.chunks, config);
51
+ if (!options.full && !vectorProfileChanged) {
52
+ records.edges.push(...repository.preservedDerivedEdges(records));
53
+ }
54
+ repository.replaceAll(records, { expectedGeneration, extractionFingerprint: fingerprint });
18
55
  return {
19
56
  files: files.length,
20
57
  changed: parsed.length,
@@ -37,7 +74,14 @@ export async function indexProject(projectRoot, options = {}) {
37
74
  const replacedDocumentIds = changedDocuments
38
75
  .map((document) => existing.get(document.relativePath)?.id)
39
76
  .filter((existingId) => typeof existingId === "string" && !changedIds.has(existingId));
40
- repository.replaceDocuments(filterRecordsForDocuments(records, changedIds), [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds]);
77
+ const changedRecords = filterRecordsForDocuments(records, changedIds);
78
+ changedRecords.vectors = await vectorsForChunks(repository, changedRecords.chunks, config);
79
+ repository.replaceDocuments(changedRecords, [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds], skippedFiles.length === 0 ? records : undefined, {
80
+ expectedGeneration,
81
+ // Do not mark a partial, parser-skipped candidate as a completed
82
+ // extraction-config rebuild. The next successful scan must retry it.
83
+ extractionFingerprint: requiresRebuild ? writeState.extractionFingerprint : fingerprint
84
+ });
41
85
  }
42
86
  return {
43
87
  files: files.length,
@@ -54,6 +98,38 @@ export async function indexProject(projectRoot, options = {}) {
54
98
  db.close();
55
99
  }
56
100
  }
101
+ async function vectorsForChunks(repository, chunks, config) {
102
+ if (!config.embedding.enabled)
103
+ return [];
104
+ const profile = { provider: config.embedding.provider, model: config.embedding.model, dimensions: config.embedding.dimensions };
105
+ const reusable = repository.reusableVectors(chunks, profile);
106
+ const present = new Set(reusable.map((vector) => vector.chunkId));
107
+ const embedded = await embedChunks(chunks.filter((chunk) => !present.has(chunk.id)), config);
108
+ return [...reusable, ...embedded];
109
+ }
110
+ function extractionFingerprint(config) {
111
+ const extraction = {
112
+ docs: config.docs,
113
+ index: config.index,
114
+ entities: {
115
+ enabledKinds: [...config.entities.enabledKinds].sort(),
116
+ stopEntities: [...config.entities.stopEntities].sort()
117
+ }
118
+ };
119
+ return createHash("sha256").update(JSON.stringify(extraction)).digest("hex");
120
+ }
121
+ function hasMatchingVectorCoverage(repository, config, counts) {
122
+ if (counts.vectors !== counts.chunks) {
123
+ return false;
124
+ }
125
+ if (counts.chunks === 0) {
126
+ return true;
127
+ }
128
+ return repository.storageDiagnostics().vectors.providers.some((provider) => (provider.provider === config.embedding.provider
129
+ && provider.model === config.embedding.model
130
+ && provider.dimensions === config.embedding.dimensions
131
+ && provider.vectors === counts.chunks));
132
+ }
57
133
  function parseScannedFiles(projectRoot, files) {
58
134
  const parsed = [];
59
135
  const skippedFiles = [];
@@ -5,6 +5,7 @@ export interface MCPServerOptions {
5
5
  watch?: boolean;
6
6
  semantic?: boolean;
7
7
  debounceMs?: number;
8
+ usePolling?: boolean;
8
9
  }
9
10
  export declare class MCPServer {
10
11
  private readonly transport;
@@ -14,7 +15,9 @@ export declare class MCPServer {
14
15
  private readonly watchEnabled;
15
16
  private readonly watchSemantic;
16
17
  private readonly watchDebounceMs;
18
+ private readonly watchUsePolling;
17
19
  private watchHandle;
20
+ private resolvedWatchHandle;
18
21
  private watchRoot;
19
22
  constructor(transport: JsonRpcTransport, options?: MCPServerOptions);
20
23
  start(): void;
@@ -24,5 +27,6 @@ export declare class MCPServer {
24
27
  private handleToolsCall;
25
28
  private ensureWatch;
26
29
  private stopWatch;
30
+ private createToolHandler;
27
31
  }
28
32
  export declare function startStdioMcpServer(options?: MCPServerOptions): MCPServer;
@@ -6,7 +6,7 @@ import { errorMessage, initializeErrorMessage, internalToolErrorMessage, mcpDebu
6
6
  import { SERVER_INSTRUCTIONS, SERVER_INSTRUCTIONS_UNINDEXED } from "./server-instructions.js";
7
7
  import { McpInputError, ToolHandler, hasIndex, tools } from "./tools.js";
8
8
  import { packageVersion } from "../version.js";
9
- import { isPathInsideOrEqual } from "../utils/path-safety.js";
9
+ import { assertProjectFilesInsideRoot, isPathInsideOrEqual } from "../utils/path-safety.js";
10
10
  import { watchProject } from "../watcher/file-watcher.js";
11
11
  export const PROTOCOL_VERSION = "2024-11-05";
12
12
  export class MCPServer {
@@ -17,16 +17,19 @@ export class MCPServer {
17
17
  watchEnabled;
18
18
  watchSemantic;
19
19
  watchDebounceMs;
20
+ watchUsePolling;
20
21
  watchHandle;
22
+ resolvedWatchHandle;
21
23
  watchRoot;
22
24
  constructor(transport, options = {}) {
23
25
  this.transport = transport;
24
- this.boundProjectRoot = validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd()));
25
- this.projectRoot = this.boundProjectRoot;
26
- this.toolHandler = new ToolHandler(this.projectRoot, this.boundProjectRoot);
26
+ this.boundProjectRoot = fs.realpathSync(validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd())));
27
+ this.projectRoot = validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd()));
28
+ this.toolHandler = this.createToolHandler(this.projectRoot);
27
29
  this.watchEnabled = options.watch ?? true;
28
30
  this.watchSemantic = options.semantic;
29
31
  this.watchDebounceMs = options.debounceMs;
32
+ this.watchUsePolling = options.usePolling ?? false;
30
33
  }
31
34
  start() {
32
35
  mcpDebug("server start", {
@@ -67,7 +70,7 @@ export class MCPServer {
67
70
  case "tools/call":
68
71
  if (isRequest) {
69
72
  mcpDebug("tools/call request", { id: message.id });
70
- this.handleToolsCall(message);
73
+ await this.handleToolsCall(message);
71
74
  }
72
75
  return;
73
76
  case "resources/list":
@@ -95,7 +98,8 @@ export class MCPServer {
95
98
  let projectRoot;
96
99
  try {
97
100
  projectRoot = validatedProjectRoot(projectRootFromInitialize(request.params) ?? this.projectRoot);
98
- if (!isPathInsideOrEqual(this.boundProjectRoot, projectRoot)) {
101
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
102
+ if (!isPathInsideOrEqual(this.boundProjectRoot, fs.realpathSync(projectRoot))) {
99
103
  throw new Error(`Initialize root must stay inside served project root: ${this.boundProjectRoot}`);
100
104
  }
101
105
  }
@@ -113,7 +117,7 @@ export class MCPServer {
113
117
  return;
114
118
  }
115
119
  this.projectRoot = projectRoot;
116
- this.toolHandler = new ToolHandler(projectRoot, this.boundProjectRoot);
120
+ this.toolHandler = this.createToolHandler(projectRoot);
117
121
  mcpDebug("initialize resolved", { id: request.id, projectRoot, indexed: hasIndex(projectRoot) });
118
122
  this.transport.sendResult(request.id, {
119
123
  protocolVersion: PROTOCOL_VERSION,
@@ -122,7 +126,7 @@ export class MCPServer {
122
126
  instructions: hasIndex(projectRoot) ? SERVER_INSTRUCTIONS : SERVER_INSTRUCTIONS_UNINDEXED
123
127
  });
124
128
  }
125
- handleToolsCall(request) {
129
+ async handleToolsCall(request) {
126
130
  const params = request.params;
127
131
  if (!params || typeof params.name !== "string") {
128
132
  this.transport.sendError(request.id, ErrorCodes.InvalidParams, "Missing tool name", mcpErrorData("tools.call.params"));
@@ -135,7 +139,7 @@ export class MCPServer {
135
139
  }
136
140
  try {
137
141
  const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {};
138
- const result = this.toolHandler.execute(params.name, args);
142
+ const result = await this.toolHandler.executeAsync(params.name, args);
139
143
  mcpDebug("tools/call result", {
140
144
  id: request.id,
141
145
  tool: params.name,
@@ -165,24 +169,26 @@ export class MCPServer {
165
169
  const watchHandle = watchProject(projectRoot, {
166
170
  semantic: this.watchSemantic,
167
171
  debounceMs: this.watchDebounceMs,
172
+ usePolling: this.watchUsePolling,
168
173
  onIndexed: (result) => {
169
174
  if (result.changed > 0 || result.deleted > 0 || result.skipped > 0) {
170
175
  console.error(`MDGraph MCP watch indexed ${result.changed} changed, ${result.deleted} deleted, ${result.unchanged} unchanged, ${result.skipped} skipped document(s).`);
171
176
  }
172
177
  },
173
178
  onError: (error) => {
174
- console.error(`MDGraph MCP watch failed: ${error.message}`);
179
+ console.error(`MDGraph MCP watch error: ${error.message}`);
175
180
  }
176
181
  });
177
182
  this.watchHandle = watchHandle;
178
183
  try {
179
- await watchHandle;
184
+ this.resolvedWatchHandle = await watchHandle;
180
185
  mcpDebug("watch ready", { projectRoot });
181
186
  }
182
187
  catch (error) {
183
188
  if (this.watchHandle === watchHandle) {
184
189
  this.watchHandle = undefined;
185
190
  this.watchRoot = undefined;
191
+ this.resolvedWatchHandle = undefined;
186
192
  }
187
193
  mcpDebug("watch startup failure", { projectRoot, error: errorMessage(error) });
188
194
  throw error;
@@ -195,11 +201,15 @@ export class MCPServer {
195
201
  }
196
202
  const watchHandle = this.watchHandle;
197
203
  this.watchHandle = undefined;
204
+ this.resolvedWatchHandle = undefined;
198
205
  this.watchRoot = undefined;
199
206
  const handle = await watchHandle;
200
207
  mcpDebug("watch stop", { projectRoot: this.projectRoot });
201
208
  await handle.close();
202
209
  }
210
+ createToolHandler(projectRoot) {
211
+ return new ToolHandler(projectRoot, this.boundProjectRoot, (requestedRoot) => (requestedRoot === this.watchRoot ? this.resolvedWatchHandle?.getHealth() : undefined));
212
+ }
203
213
  }
204
214
  export function startStdioMcpServer(options = {}) {
205
215
  const server = new MCPServer(new StdioTransport(), options);
@@ -1,3 +1,4 @@
1
+ import type { WatchHealthSnapshot } from "../watcher/watch-health.js";
1
2
  export interface McpToolDefinition {
2
3
  name: string;
3
4
  description: string;
@@ -21,11 +22,14 @@ export declare class McpInputError extends Error {
21
22
  }
22
23
  export declare const tools: McpToolDefinition[];
23
24
  export declare class ToolHandler {
25
+ private readonly watchHealthProvider?;
24
26
  private readonly defaultProjectRoot;
25
27
  private readonly boundProjectRoot;
26
- constructor(defaultProjectRoot?: string, boundProjectRoot?: string);
28
+ constructor(defaultProjectRoot?: string, boundProjectRoot?: string, watchHealthProvider?: ((projectRoot: string) => WatchHealthSnapshot | undefined) | undefined);
27
29
  getTools(): McpToolDefinition[];
28
30
  execute(name: string, args?: Record<string, unknown>): McpToolResult;
31
+ executeAsync(name: string, args?: Record<string, unknown>): Promise<McpToolResult>;
29
32
  private withRepository;
33
+ private withRepositoryAsync;
30
34
  }
31
35
  export declare function hasIndex(projectRoot: string): boolean;
package/dist/mcp/tools.js CHANGED
@@ -5,10 +5,11 @@ import { MCP_LIMITS } from "../config/limits.js";
5
5
  import { databasePath, loadConfig } from "../config/load-config.js";
6
6
  import { openExistingDatabase } from "../db/connection.js";
7
7
  import { GraphRepository } from "../db/repositories.js";
8
- import { buildContext } from "../query/context-builder.js";
9
- import { searchGraph } from "../query/search.js";
8
+ import { CONTEXT_PACKING_STRATEGIES, buildContext, buildContextAsync } from "../query/context-builder.js";
9
+ import { buildKnowledgeCard, formatKnowledgeCard } from "../query/knowledge-card.js";
10
+ import { explainSearchGraphAsync, searchGraph } from "../query/search.js";
10
11
  import { traceNodes } from "../query/trace.js";
11
- import { isPathInsideOrEqual } from "../utils/path-safety.js";
12
+ import { assertProjectFilesInsideRoot, isPathInsideOrEqual } from "../utils/path-safety.js";
12
13
  export class McpInputError extends Error {
13
14
  name = "McpInputError";
14
15
  }
@@ -42,6 +43,11 @@ export const tools = [
42
43
  description: "Optional known project-relative document or source paths to seed the task-start brief."
43
44
  },
44
45
  maxChars: { type: "number", description: "Optional character budget for the returned context package." },
46
+ packingStrategy: {
47
+ type: "string",
48
+ enum: [...CONTEXT_PACKING_STRATEGIES],
49
+ description: "Optional context packing strategy. Defaults to the compatibility document round-robin strategy."
50
+ },
45
51
  projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
46
52
  }
47
53
  }
@@ -87,12 +93,15 @@ export const tools = [
87
93
  }
88
94
  ];
89
95
  export class ToolHandler {
96
+ watchHealthProvider;
90
97
  defaultProjectRoot;
91
98
  boundProjectRoot;
92
- constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot) {
93
- this.boundProjectRoot = validatedProjectRoot(path.resolve(boundProjectRoot));
99
+ constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot, watchHealthProvider) {
100
+ this.watchHealthProvider = watchHealthProvider;
101
+ this.boundProjectRoot = fs.realpathSync(validatedProjectRoot(path.resolve(boundProjectRoot)));
94
102
  this.defaultProjectRoot = validatedProjectRoot(path.resolve(defaultProjectRoot));
95
- if (!isPathInsideOrEqual(this.boundProjectRoot, this.defaultProjectRoot)) {
103
+ assertProjectFilesInsideRoot(this.boundProjectRoot, this.defaultProjectRoot);
104
+ if (!isPathInsideOrEqual(this.boundProjectRoot, fs.realpathSync(this.defaultProjectRoot))) {
96
105
  throw new McpInputError(`Default project root must stay inside served root: ${this.boundProjectRoot}`);
97
106
  }
98
107
  }
@@ -102,13 +111,14 @@ export class ToolHandler {
102
111
  execute(name, args = {}) {
103
112
  const projectRoot = resolveProjectRoot(args.projectPath, this.defaultProjectRoot, this.boundProjectRoot);
104
113
  if (name === "mdgraph_status") {
114
+ const watchHealth = this.watchHealthProvider?.(projectRoot);
105
115
  if (!hasIndex(projectRoot)) {
106
- return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
116
+ return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false, ...(watchHealth ? { watchHealth } : {}) });
107
117
  }
108
118
  return this.withRepository(projectRoot, (repository) => {
109
119
  const counts = repository.counts();
110
120
  const freshness = safeFreshness(projectRoot, repository);
111
- return textResult(formatStatus(projectRoot, counts, freshness), { projectRoot, indexed: true, counts, freshness });
121
+ return textResult(formatStatus(projectRoot, counts, freshness, watchHealth), { projectRoot, indexed: true, counts, freshness, ...(watchHealth ? { watchHealth } : {}) });
112
122
  });
113
123
  }
114
124
  if (!hasIndex(projectRoot)) {
@@ -135,13 +145,15 @@ export class ToolHandler {
135
145
  const knownFiles = optionalStringArray(args.knownFiles, "knownFiles");
136
146
  const hasManualMaxChars = args.maxChars !== undefined && args.maxChars !== null;
137
147
  const requestedMaxChars = optionalBoundedPositiveInteger(args.maxChars, config.search.maxContextChars, "maxChars", MCP_LIMITS.contextMaxChars);
148
+ const packingStrategy = optionalContextPackingStrategy(args.packingStrategy);
138
149
  const mode = agentContextMode(config, repository.counts(), query, knownFiles, hasManualMaxChars ? requestedMaxChars : undefined);
139
150
  const context = buildContext(repository, config, query, {
140
151
  knownFiles,
141
152
  maxChars: mode.maxChars,
142
153
  searchLimit: mode.searchLimit,
143
154
  maxDepth: mode.maxDepth,
144
- mode
155
+ mode,
156
+ packingStrategy
145
157
  });
146
158
  const freshness = safeFreshness(projectRoot, repository, config);
147
159
  return withFreshnessNotice(textResult(formatContext(context), { projectRoot, context }), freshness);
@@ -157,7 +169,9 @@ export class ToolHandler {
157
169
  if (resolution.status === "ambiguous") {
158
170
  return withFreshnessNotice(textResult(formatAmbiguousNodeQuery(resolution), { projectRoot, query, error: resolution.error, candidates: resolution.candidates, node: null }), freshness);
159
171
  }
160
- return withFreshnessNotice(textResult(formatNode(resolution.node, repository), { projectRoot, node: resolution.node }), freshness);
172
+ const card = buildKnowledgeCard(repository, resolution.node);
173
+ const node = card ? { ...resolution.node, card } : resolution.node;
174
+ return withFreshnessNotice(textResult(formatNode(resolution.node, repository, card), { projectRoot, node }), freshness);
161
175
  });
162
176
  case "mdgraph_trace":
163
177
  return this.withRepository(projectRoot, (repository) => {
@@ -172,7 +186,57 @@ export class ToolHandler {
172
186
  return { ...textResult(`Unknown MDGraph tool: ${name}`, { name }), isError: true };
173
187
  }
174
188
  }
189
+ async executeAsync(name, args = {}) {
190
+ if (name !== "mdgraph_search" && name !== "mdgraph_context") {
191
+ return this.execute(name, args);
192
+ }
193
+ const projectRoot = resolveProjectRoot(args.projectPath, this.defaultProjectRoot, this.boundProjectRoot);
194
+ if (!hasIndex(projectRoot)) {
195
+ return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
196
+ }
197
+ if (name === "mdgraph_search") {
198
+ return this.withRepositoryAsync(projectRoot, async (repository) => {
199
+ const config = loadConfig(projectRoot);
200
+ const query = requiredString(args.query, "query");
201
+ const counts = repository.counts();
202
+ const hasManualLimit = args.limit !== undefined && args.limit !== null;
203
+ const autoMode = agentSearchMode(config, counts, query);
204
+ const limit = hasManualLimit ? optionalBoundedPositiveInteger(args.limit, config.search.defaultLimit, "limit", MCP_LIMITS.searchLimit) : autoMode.limit;
205
+ const explanation = await explainSearchGraphAsync(repository, config, query, limit);
206
+ const mode = hasManualLimit ? { name: "manual", limit, reason: "explicit limit argument" } : autoMode;
207
+ const freshness = safeFreshness(projectRoot, repository, config);
208
+ const structuredContent = {
209
+ projectRoot,
210
+ query,
211
+ mode,
212
+ results: explanation.results,
213
+ ...(explanation.semanticDiagnostic ? { semanticDiagnostic: explanation.semanticDiagnostic } : {})
214
+ };
215
+ return withFreshnessNotice(textResult(withSemanticNotice(formatSearch(explanation.results), explanation.semanticDiagnostic), structuredContent), freshness);
216
+ });
217
+ }
218
+ return this.withRepositoryAsync(projectRoot, async (repository) => {
219
+ const config = loadConfig(projectRoot);
220
+ const query = requiredString(args.query, "query");
221
+ const knownFiles = optionalStringArray(args.knownFiles, "knownFiles");
222
+ const hasManualMaxChars = args.maxChars !== undefined && args.maxChars !== null;
223
+ const requestedMaxChars = optionalBoundedPositiveInteger(args.maxChars, config.search.maxContextChars, "maxChars", MCP_LIMITS.contextMaxChars);
224
+ const packingStrategy = optionalContextPackingStrategy(args.packingStrategy);
225
+ const mode = agentContextMode(config, repository.counts(), query, knownFiles, hasManualMaxChars ? requestedMaxChars : undefined);
226
+ const context = await buildContextAsync(repository, config, query, {
227
+ knownFiles,
228
+ maxChars: mode.maxChars,
229
+ searchLimit: mode.searchLimit,
230
+ maxDepth: mode.maxDepth,
231
+ mode,
232
+ packingStrategy
233
+ });
234
+ const freshness = safeFreshness(projectRoot, repository, config);
235
+ return withFreshnessNotice(textResult(withSemanticNotice(formatContext(context), context.semanticDiagnostic), { projectRoot, context }), freshness);
236
+ });
237
+ }
175
238
  withRepository(projectRoot, fn) {
239
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
176
240
  const repository = new GraphRepository(openExistingDatabase(projectRoot));
177
241
  try {
178
242
  return fn(repository);
@@ -181,6 +245,16 @@ export class ToolHandler {
181
245
  repository.close();
182
246
  }
183
247
  }
248
+ async withRepositoryAsync(projectRoot, fn) {
249
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
250
+ const repository = new GraphRepository(openExistingDatabase(projectRoot));
251
+ try {
252
+ return await fn(repository);
253
+ }
254
+ finally {
255
+ repository.close();
256
+ }
257
+ }
184
258
  }
185
259
  export function hasIndex(projectRoot) {
186
260
  return fs.existsSync(databasePath(projectRoot));
@@ -191,9 +265,12 @@ function textResult(text, structuredContent) {
191
265
  structuredContent
192
266
  };
193
267
  }
194
- function formatStatus(projectRoot, counts, freshness) {
268
+ function withSemanticNotice(text, diagnostic) {
269
+ return diagnostic ? `Semantic search degraded: ${diagnostic.message}\n\n${text}` : text;
270
+ }
271
+ function formatStatus(projectRoot, counts, freshness, watchHealth) {
195
272
  const database = databasePath(projectRoot);
196
- return [
273
+ const lines = [
197
274
  "MDGraph index status: active",
198
275
  `Project: ${projectRoot}`,
199
276
  `Database: ${database}`,
@@ -207,7 +284,11 @@ function formatStatus(projectRoot, counts, freshness) {
207
284
  `Edges: ${counts.edges}`,
208
285
  `Chunks: ${counts.chunks}`,
209
286
  `Vectors: ${counts.vectors}`
210
- ].join("\n");
287
+ ];
288
+ if (watchHealth) {
289
+ lines.push(`Watch health: ${watchHealth.state}${watchHealth.polling ? " (polling)" : ""}`, watchHealth.lastSuccessfulIndexAt ? `Watch last successful index: ${watchHealth.lastSuccessfulIndexAt}` : "Watch last successful index: unavailable", watchHealth.lastError ? `Watch last error: ${watchHealth.lastError.code}/${watchHealth.lastError.phase} - ${watchHealth.lastError.message}` : "Watch last error: none");
290
+ }
291
+ return lines.join("\n");
211
292
  }
212
293
  function safeFreshness(projectRoot, repository, config = tryLoadConfig(projectRoot)) {
213
294
  if (!config) {
@@ -369,7 +450,8 @@ function formatContext(context) {
369
450
  const entities = item.matchedEntities.length ? `\nMatched entities: ${item.matchedEntities.join(", ")}` : "";
370
451
  const sourceRefs = item.sourceRefs?.length ? `\nSource refs: ${item.sourceRefs.map((sourceRef) => `${sourceRef.path} (${sourceRef.edgeKind}/${sourceRef.provenance}, confidence ${sourceRef.confidence})`).join(", ")}` : "";
371
452
  const riskNotes = item.riskNotes?.length ? `\nRisk notes: ${item.riskNotes.join("; ")}` : "";
372
- return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}\n${heading}\n${item.content}`;
453
+ const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
454
+ return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}${cardSummary}\n${heading}\n${item.content}`;
373
455
  });
374
456
  const hints = [
375
457
  context.mode ? `Mode: ${context.mode.name} (searchLimit ${context.mode.searchLimit}, maxDepth ${context.mode.maxDepth}; ${context.mode.reason})` : "",
@@ -378,7 +460,7 @@ function formatContext(context) {
378
460
  ].filter(Boolean);
379
461
  return [header, ...hints, ...items].join("\n\n");
380
462
  }
381
- function formatNode(node, repository) {
463
+ function formatNode(node, repository, card) {
382
464
  const edges = repository.edgesForNode(node.id).slice(0, 12);
383
465
  const related = edges.map((edge) => {
384
466
  const otherId = edge.fromId === node.id ? edge.toId : edge.fromId;
@@ -388,8 +470,9 @@ function formatNode(node, repository) {
388
470
  return [
389
471
  `${node.kind}: ${node.label}`,
390
472
  JSON.stringify(node.data, null, 2),
391
- related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none"
392
- ].join("\n\n");
473
+ related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none",
474
+ card ? formatKnowledgeCard(card) : ""
475
+ ].filter(Boolean).join("\n\n");
393
476
  }
394
477
  function formatAmbiguousNodeQuery(resolution) {
395
478
  const candidates = resolution.candidates
@@ -434,7 +517,13 @@ function validatedProjectRoot(projectRoot) {
434
517
  }
435
518
  function validatedBoundProjectRoot(projectRoot, boundProjectRoot) {
436
519
  const resolved = validatedProjectRoot(projectRoot);
437
- if (!isPathInsideOrEqual(boundProjectRoot, resolved)) {
520
+ try {
521
+ assertProjectFilesInsideRoot(boundProjectRoot, resolved);
522
+ }
523
+ catch (error) {
524
+ throw new McpInputError(error instanceof Error ? error.message : String(error));
525
+ }
526
+ if (!isPathInsideOrEqual(boundProjectRoot, fs.realpathSync(resolved))) {
438
527
  throw new McpInputError(`projectPath must stay inside served project root: ${boundProjectRoot}`);
439
528
  }
440
529
  return resolved;
@@ -490,6 +579,15 @@ function optionalStringArray(value, field) {
490
579
  }
491
580
  return [...new Set(result)];
492
581
  }
582
+ function optionalContextPackingStrategy(value) {
583
+ if (value === undefined || value === null) {
584
+ return undefined;
585
+ }
586
+ if (typeof value === "string" && CONTEXT_PACKING_STRATEGIES.includes(value)) {
587
+ return value;
588
+ }
589
+ throw new McpInputError(`packingStrategy must be one of ${CONTEXT_PACKING_STRATEGIES.join(", ")}`);
590
+ }
493
591
  function trimBlock(content, maxChars) {
494
592
  if (content.length <= maxChars) {
495
593
  return content;
@@ -11,6 +11,7 @@ import { normalizeFrontmatter, parseFrontmatterBlock } from "./frontmatter.js";
11
11
  import { parseWikiLinkTarget } from "./links.js";
12
12
  export function parseMarkdownDocument(projectRoot, absolutePath) {
13
13
  assertInsideRoot(projectRoot, absolutePath, "Markdown file path");
14
+ const updatedAt = fs.statSync(absolutePath).mtime.toISOString();
14
15
  const raw = fs.readFileSync(absolutePath, "utf8");
15
16
  const parsed = parseFrontmatter(raw);
16
17
  const body = parsed.content;
@@ -36,6 +37,7 @@ export function parseMarkdownDocument(projectRoot, absolutePath) {
36
37
  relativePath,
37
38
  title,
38
39
  hash: contentHash(raw),
40
+ updatedAt,
39
41
  frontmatter,
40
42
  frontmatterDiagnostics,
41
43
  body,
@@ -1,7 +1,11 @@
1
- import type { EdgeKind, MDGraphConfig, Provenance } from "../types.js";
1
+ import type { EdgeKind, MDGraphConfig, Provenance, SearchResult } from "../types.js";
2
2
  import { GraphRepository } from "../db/repositories.js";
3
3
  import { type SearchOptions } from "./search.js";
4
+ import type { EmbeddingDiagnostic } from "../semantic/provider.js";
4
5
  export declare const CONTEXT_PACKING_STRATEGY: "mmr-style-document-round-robin";
6
+ export declare const CONTEXT_PACKING_STRATEGIES: readonly ["mmr-style-document-round-robin", "mmr"];
7
+ export type ContextPackingStrategy = typeof CONTEXT_PACKING_STRATEGIES[number];
8
+ export declare const DEFAULT_MMR_LAMBDA = 0.65;
5
9
  export interface ContextItem {
6
10
  nodeId: string;
7
11
  documentId: string;
@@ -19,6 +23,7 @@ export interface ContextItem {
19
23
  edgePath?: ContextEdgePathStep[];
20
24
  sourceRefs?: ContextSourceRef[];
21
25
  riskNotes?: string[];
26
+ cardSummary?: string;
22
27
  content: string;
23
28
  }
24
29
  export interface ContextEdgePathStep {
@@ -50,12 +55,20 @@ export interface ContextResult {
50
55
  query: string;
51
56
  maxChars: number;
52
57
  usedChars: number;
58
+ packing: ContextPackingInfo;
53
59
  knownFiles?: string[];
54
60
  suggestedNextQueries?: string[];
55
61
  mode?: ContextAutoMode;
62
+ semanticDiagnostic?: EmbeddingDiagnostic;
56
63
  items: ContextItem[];
57
64
  debug?: ContextDebug;
58
65
  }
66
+ export interface ContextPackingInfo {
67
+ strategy: ContextPackingStrategy;
68
+ similarity?: ContextPackingSimilarity;
69
+ mmrLambda?: number;
70
+ redundancySkippedItems?: number;
71
+ }
59
72
  export interface ContextDebug {
60
73
  seedNodes: number;
61
74
  visitedNodes: number;
@@ -66,12 +79,25 @@ export interface ContextDebug {
66
79
  candidateCount: number;
67
80
  directCandidates: number;
68
81
  expandedCandidates: number;
69
- packingStrategy: typeof CONTEXT_PACKING_STRATEGY;
82
+ packingStrategy: ContextPackingStrategy;
83
+ packingSimilarity?: ContextPackingSimilarity;
84
+ mmrLambda?: number;
85
+ packingSelections?: ContextPackingSelection[];
70
86
  packedItems: number;
71
87
  packedUniqueDocuments: number;
72
88
  packingDiversityRatio: number;
73
89
  budgetTruncatedItems: number;
74
90
  budgetSkippedItems: number;
91
+ redundancySkippedItems?: number;
92
+ }
93
+ export type ContextPackingSimilarity = "embedding-cosine" | "hybrid" | "lexical-jaccard";
94
+ export interface ContextPackingSelection {
95
+ nodeId: string;
96
+ path: string;
97
+ queryRelevance: number;
98
+ redundancyPenalty: number;
99
+ mmrScore: number;
100
+ similaritySource: "embedding-cosine" | "lexical-jaccard" | "none";
75
101
  }
76
102
  export interface ContextBuildOptions {
77
103
  debug?: boolean;
@@ -80,6 +106,10 @@ export interface ContextBuildOptions {
80
106
  searchLimit?: number;
81
107
  maxDepth?: number;
82
108
  mode?: ContextAutoMode;
109
+ packingStrategy?: ContextPackingStrategy;
110
+ mmrLambda?: number;
83
111
  searchOptions?: SearchOptions;
84
112
  }
85
113
  export declare function buildContext(repository: GraphRepository, config: MDGraphConfig, query: string, options?: ContextBuildOptions): ContextResult;
114
+ export declare function buildContextAsync(repository: GraphRepository, config: MDGraphConfig, query: string, options?: ContextBuildOptions): Promise<ContextResult>;
115
+ export declare function buildContextFromSearchResults(repository: GraphRepository, config: MDGraphConfig, query: string, results: SearchResult[], options: ContextBuildOptions, semanticDiagnostic?: EmbeddingDiagnostic): ContextResult;