@daogee/mdgraph 1.0.0 → 1.1.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 +22 -0
- package/README-ZH.md +54 -2
- package/README.md +73 -21
- package/dist/bin/mdgraph.js +136 -19
- 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/repositories.d.ts +27 -0
- package/dist/db/repositories.js +310 -6
- 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 +14 -5
- package/dist/evaluation/retrieval-eval.js +44 -6
- 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 +17 -4
- package/dist/index.js +9 -4
- package/dist/indexer.js +20 -2
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +16 -7
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +93 -9
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +31 -2
- package/dist/query/context-builder.js +162 -12
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +77 -13
- 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 +131 -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/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +75 -10
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/docs/EN/Agent_Integration.md +1 -1
- package/docs/EN/Architecture.md +39 -16
- package/docs/EN/Evaluation_Questions.md +21 -5
- package/docs/EN/Operations.md +91 -0
- package/docs/EN/Output_Contracts.md +41 -7
- package/docs/EN/Public_Contracts.md +23 -16
- package/docs/EN/Public_Contracts_1.0.md +28 -18
- package/docs/EN/README.md +23 -0
- package/docs/EN/Release_Checklist.md +26 -13
- package/docs/EN/Retrieval_and_Context.md +112 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +1 -1
- package/docs/ZH/Architecture.md +39 -19
- package/docs/ZH/Evaluation_Questions.md +22 -6
- package/docs/ZH/Operations.md +91 -0
- package/docs/ZH/Output_Contracts.md +41 -7
- package/docs/ZH/Public_Contracts.md +22 -15
- package/docs/ZH/Public_Contracts_1.0.md +27 -17
- package/docs/ZH/README.md +23 -0
- package/docs/ZH/Release_Checklist.md +26 -13
- package/docs/ZH/Retrieval_and_Context.md +112 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +44 -18
package/dist/mcp/server.d.ts
CHANGED
|
@@ -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;
|
package/dist/mcp/server.js
CHANGED
|
@@ -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
26
|
this.boundProjectRoot = validatedProjectRoot(path.resolve(options.projectRoot ?? process.cwd()));
|
|
25
27
|
this.projectRoot = this.boundProjectRoot;
|
|
26
|
-
this.toolHandler =
|
|
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":
|
|
@@ -113,7 +116,7 @@ export class MCPServer {
|
|
|
113
116
|
return;
|
|
114
117
|
}
|
|
115
118
|
this.projectRoot = projectRoot;
|
|
116
|
-
this.toolHandler =
|
|
119
|
+
this.toolHandler = this.createToolHandler(projectRoot);
|
|
117
120
|
mcpDebug("initialize resolved", { id: request.id, projectRoot, indexed: hasIndex(projectRoot) });
|
|
118
121
|
this.transport.sendResult(request.id, {
|
|
119
122
|
protocolVersion: PROTOCOL_VERSION,
|
|
@@ -122,7 +125,7 @@ export class MCPServer {
|
|
|
122
125
|
instructions: hasIndex(projectRoot) ? SERVER_INSTRUCTIONS : SERVER_INSTRUCTIONS_UNINDEXED
|
|
123
126
|
});
|
|
124
127
|
}
|
|
125
|
-
handleToolsCall(request) {
|
|
128
|
+
async handleToolsCall(request) {
|
|
126
129
|
const params = request.params;
|
|
127
130
|
if (!params || typeof params.name !== "string") {
|
|
128
131
|
this.transport.sendError(request.id, ErrorCodes.InvalidParams, "Missing tool name", mcpErrorData("tools.call.params"));
|
|
@@ -135,7 +138,7 @@ export class MCPServer {
|
|
|
135
138
|
}
|
|
136
139
|
try {
|
|
137
140
|
const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {};
|
|
138
|
-
const result = this.toolHandler.
|
|
141
|
+
const result = await this.toolHandler.executeAsync(params.name, args);
|
|
139
142
|
mcpDebug("tools/call result", {
|
|
140
143
|
id: request.id,
|
|
141
144
|
tool: params.name,
|
|
@@ -165,24 +168,26 @@ export class MCPServer {
|
|
|
165
168
|
const watchHandle = watchProject(projectRoot, {
|
|
166
169
|
semantic: this.watchSemantic,
|
|
167
170
|
debounceMs: this.watchDebounceMs,
|
|
171
|
+
usePolling: this.watchUsePolling,
|
|
168
172
|
onIndexed: (result) => {
|
|
169
173
|
if (result.changed > 0 || result.deleted > 0 || result.skipped > 0) {
|
|
170
174
|
console.error(`MDGraph MCP watch indexed ${result.changed} changed, ${result.deleted} deleted, ${result.unchanged} unchanged, ${result.skipped} skipped document(s).`);
|
|
171
175
|
}
|
|
172
176
|
},
|
|
173
177
|
onError: (error) => {
|
|
174
|
-
console.error(`MDGraph MCP watch
|
|
178
|
+
console.error(`MDGraph MCP watch error: ${error.message}`);
|
|
175
179
|
}
|
|
176
180
|
});
|
|
177
181
|
this.watchHandle = watchHandle;
|
|
178
182
|
try {
|
|
179
|
-
await watchHandle;
|
|
183
|
+
this.resolvedWatchHandle = await watchHandle;
|
|
180
184
|
mcpDebug("watch ready", { projectRoot });
|
|
181
185
|
}
|
|
182
186
|
catch (error) {
|
|
183
187
|
if (this.watchHandle === watchHandle) {
|
|
184
188
|
this.watchHandle = undefined;
|
|
185
189
|
this.watchRoot = undefined;
|
|
190
|
+
this.resolvedWatchHandle = undefined;
|
|
186
191
|
}
|
|
187
192
|
mcpDebug("watch startup failure", { projectRoot, error: errorMessage(error) });
|
|
188
193
|
throw error;
|
|
@@ -195,11 +200,15 @@ export class MCPServer {
|
|
|
195
200
|
}
|
|
196
201
|
const watchHandle = this.watchHandle;
|
|
197
202
|
this.watchHandle = undefined;
|
|
203
|
+
this.resolvedWatchHandle = undefined;
|
|
198
204
|
this.watchRoot = undefined;
|
|
199
205
|
const handle = await watchHandle;
|
|
200
206
|
mcpDebug("watch stop", { projectRoot: this.projectRoot });
|
|
201
207
|
await handle.close();
|
|
202
208
|
}
|
|
209
|
+
createToolHandler(projectRoot) {
|
|
210
|
+
return new ToolHandler(projectRoot, this.boundProjectRoot, (requestedRoot) => (requestedRoot === this.watchRoot ? this.resolvedWatchHandle?.getHealth() : undefined));
|
|
211
|
+
}
|
|
203
212
|
}
|
|
204
213
|
export function startStdioMcpServer(options = {}) {
|
|
205
214
|
const server = new MCPServer(new StdioTransport(), options);
|
package/dist/mcp/tools.d.ts
CHANGED
|
@@ -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,8 +5,8 @@ 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 { explainSearchGraphAsync, searchGraph } from "../query/search.js";
|
|
10
10
|
import { traceNodes } from "../query/trace.js";
|
|
11
11
|
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
12
12
|
export class McpInputError extends Error {
|
|
@@ -42,6 +42,11 @@ export const tools = [
|
|
|
42
42
|
description: "Optional known project-relative document or source paths to seed the task-start brief."
|
|
43
43
|
},
|
|
44
44
|
maxChars: { type: "number", description: "Optional character budget for the returned context package." },
|
|
45
|
+
packingStrategy: {
|
|
46
|
+
type: "string",
|
|
47
|
+
enum: [...CONTEXT_PACKING_STRATEGIES],
|
|
48
|
+
description: "Optional context packing strategy. Defaults to the compatibility document round-robin strategy."
|
|
49
|
+
},
|
|
45
50
|
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
46
51
|
}
|
|
47
52
|
}
|
|
@@ -87,9 +92,11 @@ export const tools = [
|
|
|
87
92
|
}
|
|
88
93
|
];
|
|
89
94
|
export class ToolHandler {
|
|
95
|
+
watchHealthProvider;
|
|
90
96
|
defaultProjectRoot;
|
|
91
97
|
boundProjectRoot;
|
|
92
|
-
constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot) {
|
|
98
|
+
constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot, watchHealthProvider) {
|
|
99
|
+
this.watchHealthProvider = watchHealthProvider;
|
|
93
100
|
this.boundProjectRoot = validatedProjectRoot(path.resolve(boundProjectRoot));
|
|
94
101
|
this.defaultProjectRoot = validatedProjectRoot(path.resolve(defaultProjectRoot));
|
|
95
102
|
if (!isPathInsideOrEqual(this.boundProjectRoot, this.defaultProjectRoot)) {
|
|
@@ -102,13 +109,14 @@ export class ToolHandler {
|
|
|
102
109
|
execute(name, args = {}) {
|
|
103
110
|
const projectRoot = resolveProjectRoot(args.projectPath, this.defaultProjectRoot, this.boundProjectRoot);
|
|
104
111
|
if (name === "mdgraph_status") {
|
|
112
|
+
const watchHealth = this.watchHealthProvider?.(projectRoot);
|
|
105
113
|
if (!hasIndex(projectRoot)) {
|
|
106
|
-
return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
|
|
114
|
+
return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false, ...(watchHealth ? { watchHealth } : {}) });
|
|
107
115
|
}
|
|
108
116
|
return this.withRepository(projectRoot, (repository) => {
|
|
109
117
|
const counts = repository.counts();
|
|
110
118
|
const freshness = safeFreshness(projectRoot, repository);
|
|
111
|
-
return textResult(formatStatus(projectRoot, counts, freshness), { projectRoot, indexed: true, counts, freshness });
|
|
119
|
+
return textResult(formatStatus(projectRoot, counts, freshness, watchHealth), { projectRoot, indexed: true, counts, freshness, ...(watchHealth ? { watchHealth } : {}) });
|
|
112
120
|
});
|
|
113
121
|
}
|
|
114
122
|
if (!hasIndex(projectRoot)) {
|
|
@@ -135,13 +143,15 @@ export class ToolHandler {
|
|
|
135
143
|
const knownFiles = optionalStringArray(args.knownFiles, "knownFiles");
|
|
136
144
|
const hasManualMaxChars = args.maxChars !== undefined && args.maxChars !== null;
|
|
137
145
|
const requestedMaxChars = optionalBoundedPositiveInteger(args.maxChars, config.search.maxContextChars, "maxChars", MCP_LIMITS.contextMaxChars);
|
|
146
|
+
const packingStrategy = optionalContextPackingStrategy(args.packingStrategy);
|
|
138
147
|
const mode = agentContextMode(config, repository.counts(), query, knownFiles, hasManualMaxChars ? requestedMaxChars : undefined);
|
|
139
148
|
const context = buildContext(repository, config, query, {
|
|
140
149
|
knownFiles,
|
|
141
150
|
maxChars: mode.maxChars,
|
|
142
151
|
searchLimit: mode.searchLimit,
|
|
143
152
|
maxDepth: mode.maxDepth,
|
|
144
|
-
mode
|
|
153
|
+
mode,
|
|
154
|
+
packingStrategy
|
|
145
155
|
});
|
|
146
156
|
const freshness = safeFreshness(projectRoot, repository, config);
|
|
147
157
|
return withFreshnessNotice(textResult(formatContext(context), { projectRoot, context }), freshness);
|
|
@@ -172,6 +182,55 @@ export class ToolHandler {
|
|
|
172
182
|
return { ...textResult(`Unknown MDGraph tool: ${name}`, { name }), isError: true };
|
|
173
183
|
}
|
|
174
184
|
}
|
|
185
|
+
async executeAsync(name, args = {}) {
|
|
186
|
+
if (name !== "mdgraph_search" && name !== "mdgraph_context") {
|
|
187
|
+
return this.execute(name, args);
|
|
188
|
+
}
|
|
189
|
+
const projectRoot = resolveProjectRoot(args.projectPath, this.defaultProjectRoot, this.boundProjectRoot);
|
|
190
|
+
if (!hasIndex(projectRoot)) {
|
|
191
|
+
return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
|
|
192
|
+
}
|
|
193
|
+
if (name === "mdgraph_search") {
|
|
194
|
+
return this.withRepositoryAsync(projectRoot, async (repository) => {
|
|
195
|
+
const config = loadConfig(projectRoot);
|
|
196
|
+
const query = requiredString(args.query, "query");
|
|
197
|
+
const counts = repository.counts();
|
|
198
|
+
const hasManualLimit = args.limit !== undefined && args.limit !== null;
|
|
199
|
+
const autoMode = agentSearchMode(config, counts, query);
|
|
200
|
+
const limit = hasManualLimit ? optionalBoundedPositiveInteger(args.limit, config.search.defaultLimit, "limit", MCP_LIMITS.searchLimit) : autoMode.limit;
|
|
201
|
+
const explanation = await explainSearchGraphAsync(repository, config, query, limit);
|
|
202
|
+
const mode = hasManualLimit ? { name: "manual", limit, reason: "explicit limit argument" } : autoMode;
|
|
203
|
+
const freshness = safeFreshness(projectRoot, repository, config);
|
|
204
|
+
const structuredContent = {
|
|
205
|
+
projectRoot,
|
|
206
|
+
query,
|
|
207
|
+
mode,
|
|
208
|
+
results: explanation.results,
|
|
209
|
+
...(explanation.semanticDiagnostic ? { semanticDiagnostic: explanation.semanticDiagnostic } : {})
|
|
210
|
+
};
|
|
211
|
+
return withFreshnessNotice(textResult(withSemanticNotice(formatSearch(explanation.results), explanation.semanticDiagnostic), structuredContent), freshness);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return this.withRepositoryAsync(projectRoot, async (repository) => {
|
|
215
|
+
const config = loadConfig(projectRoot);
|
|
216
|
+
const query = requiredString(args.query, "query");
|
|
217
|
+
const knownFiles = optionalStringArray(args.knownFiles, "knownFiles");
|
|
218
|
+
const hasManualMaxChars = args.maxChars !== undefined && args.maxChars !== null;
|
|
219
|
+
const requestedMaxChars = optionalBoundedPositiveInteger(args.maxChars, config.search.maxContextChars, "maxChars", MCP_LIMITS.contextMaxChars);
|
|
220
|
+
const packingStrategy = optionalContextPackingStrategy(args.packingStrategy);
|
|
221
|
+
const mode = agentContextMode(config, repository.counts(), query, knownFiles, hasManualMaxChars ? requestedMaxChars : undefined);
|
|
222
|
+
const context = await buildContextAsync(repository, config, query, {
|
|
223
|
+
knownFiles,
|
|
224
|
+
maxChars: mode.maxChars,
|
|
225
|
+
searchLimit: mode.searchLimit,
|
|
226
|
+
maxDepth: mode.maxDepth,
|
|
227
|
+
mode,
|
|
228
|
+
packingStrategy
|
|
229
|
+
});
|
|
230
|
+
const freshness = safeFreshness(projectRoot, repository, config);
|
|
231
|
+
return withFreshnessNotice(textResult(withSemanticNotice(formatContext(context), context.semanticDiagnostic), { projectRoot, context }), freshness);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
175
234
|
withRepository(projectRoot, fn) {
|
|
176
235
|
const repository = new GraphRepository(openExistingDatabase(projectRoot));
|
|
177
236
|
try {
|
|
@@ -181,6 +240,15 @@ export class ToolHandler {
|
|
|
181
240
|
repository.close();
|
|
182
241
|
}
|
|
183
242
|
}
|
|
243
|
+
async withRepositoryAsync(projectRoot, fn) {
|
|
244
|
+
const repository = new GraphRepository(openExistingDatabase(projectRoot));
|
|
245
|
+
try {
|
|
246
|
+
return await fn(repository);
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
repository.close();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
184
252
|
}
|
|
185
253
|
export function hasIndex(projectRoot) {
|
|
186
254
|
return fs.existsSync(databasePath(projectRoot));
|
|
@@ -191,9 +259,12 @@ function textResult(text, structuredContent) {
|
|
|
191
259
|
structuredContent
|
|
192
260
|
};
|
|
193
261
|
}
|
|
194
|
-
function
|
|
262
|
+
function withSemanticNotice(text, diagnostic) {
|
|
263
|
+
return diagnostic ? `Semantic search degraded: ${diagnostic.message}\n\n${text}` : text;
|
|
264
|
+
}
|
|
265
|
+
function formatStatus(projectRoot, counts, freshness, watchHealth) {
|
|
195
266
|
const database = databasePath(projectRoot);
|
|
196
|
-
|
|
267
|
+
const lines = [
|
|
197
268
|
"MDGraph index status: active",
|
|
198
269
|
`Project: ${projectRoot}`,
|
|
199
270
|
`Database: ${database}`,
|
|
@@ -207,7 +278,11 @@ function formatStatus(projectRoot, counts, freshness) {
|
|
|
207
278
|
`Edges: ${counts.edges}`,
|
|
208
279
|
`Chunks: ${counts.chunks}`,
|
|
209
280
|
`Vectors: ${counts.vectors}`
|
|
210
|
-
]
|
|
281
|
+
];
|
|
282
|
+
if (watchHealth) {
|
|
283
|
+
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");
|
|
284
|
+
}
|
|
285
|
+
return lines.join("\n");
|
|
211
286
|
}
|
|
212
287
|
function safeFreshness(projectRoot, repository, config = tryLoadConfig(projectRoot)) {
|
|
213
288
|
if (!config) {
|
|
@@ -490,6 +565,15 @@ function optionalStringArray(value, field) {
|
|
|
490
565
|
}
|
|
491
566
|
return [...new Set(result)];
|
|
492
567
|
}
|
|
568
|
+
function optionalContextPackingStrategy(value) {
|
|
569
|
+
if (value === undefined || value === null) {
|
|
570
|
+
return undefined;
|
|
571
|
+
}
|
|
572
|
+
if (typeof value === "string" && CONTEXT_PACKING_STRATEGIES.includes(value)) {
|
|
573
|
+
return value;
|
|
574
|
+
}
|
|
575
|
+
throw new McpInputError(`packingStrategy must be one of ${CONTEXT_PACKING_STRATEGIES.join(", ")}`);
|
|
576
|
+
}
|
|
493
577
|
function trimBlock(content, maxChars) {
|
|
494
578
|
if (content.length <= maxChars) {
|
|
495
579
|
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;
|
|
@@ -50,12 +54,20 @@ export interface ContextResult {
|
|
|
50
54
|
query: string;
|
|
51
55
|
maxChars: number;
|
|
52
56
|
usedChars: number;
|
|
57
|
+
packing: ContextPackingInfo;
|
|
53
58
|
knownFiles?: string[];
|
|
54
59
|
suggestedNextQueries?: string[];
|
|
55
60
|
mode?: ContextAutoMode;
|
|
61
|
+
semanticDiagnostic?: EmbeddingDiagnostic;
|
|
56
62
|
items: ContextItem[];
|
|
57
63
|
debug?: ContextDebug;
|
|
58
64
|
}
|
|
65
|
+
export interface ContextPackingInfo {
|
|
66
|
+
strategy: ContextPackingStrategy;
|
|
67
|
+
similarity?: ContextPackingSimilarity;
|
|
68
|
+
mmrLambda?: number;
|
|
69
|
+
redundancySkippedItems?: number;
|
|
70
|
+
}
|
|
59
71
|
export interface ContextDebug {
|
|
60
72
|
seedNodes: number;
|
|
61
73
|
visitedNodes: number;
|
|
@@ -66,12 +78,25 @@ export interface ContextDebug {
|
|
|
66
78
|
candidateCount: number;
|
|
67
79
|
directCandidates: number;
|
|
68
80
|
expandedCandidates: number;
|
|
69
|
-
packingStrategy:
|
|
81
|
+
packingStrategy: ContextPackingStrategy;
|
|
82
|
+
packingSimilarity?: ContextPackingSimilarity;
|
|
83
|
+
mmrLambda?: number;
|
|
84
|
+
packingSelections?: ContextPackingSelection[];
|
|
70
85
|
packedItems: number;
|
|
71
86
|
packedUniqueDocuments: number;
|
|
72
87
|
packingDiversityRatio: number;
|
|
73
88
|
budgetTruncatedItems: number;
|
|
74
89
|
budgetSkippedItems: number;
|
|
90
|
+
redundancySkippedItems?: number;
|
|
91
|
+
}
|
|
92
|
+
export type ContextPackingSimilarity = "embedding-cosine" | "hybrid" | "lexical-jaccard";
|
|
93
|
+
export interface ContextPackingSelection {
|
|
94
|
+
nodeId: string;
|
|
95
|
+
path: string;
|
|
96
|
+
queryRelevance: number;
|
|
97
|
+
redundancyPenalty: number;
|
|
98
|
+
mmrScore: number;
|
|
99
|
+
similaritySource: "embedding-cosine" | "lexical-jaccard" | "none";
|
|
75
100
|
}
|
|
76
101
|
export interface ContextBuildOptions {
|
|
77
102
|
debug?: boolean;
|
|
@@ -80,6 +105,10 @@ export interface ContextBuildOptions {
|
|
|
80
105
|
searchLimit?: number;
|
|
81
106
|
maxDepth?: number;
|
|
82
107
|
mode?: ContextAutoMode;
|
|
108
|
+
packingStrategy?: ContextPackingStrategy;
|
|
109
|
+
mmrLambda?: number;
|
|
83
110
|
searchOptions?: SearchOptions;
|
|
84
111
|
}
|
|
85
112
|
export declare function buildContext(repository: GraphRepository, config: MDGraphConfig, query: string, options?: ContextBuildOptions): ContextResult;
|
|
113
|
+
export declare function buildContextAsync(repository: GraphRepository, config: MDGraphConfig, query: string, options?: ContextBuildOptions): Promise<ContextResult>;
|
|
114
|
+
export declare function buildContextFromSearchResults(repository: GraphRepository, config: MDGraphConfig, query: string, results: SearchResult[], options: ContextBuildOptions, semanticDiagnostic?: EmbeddingDiagnostic): ContextResult;
|
|
@@ -1,20 +1,33 @@
|
|
|
1
|
-
import { searchGraph } from "./search.js";
|
|
1
|
+
import { explainSearchGraphAsync, searchGraph } from "./search.js";
|
|
2
2
|
import { scanContentRiskLines } from "../utils/content-risk.js";
|
|
3
3
|
import { normalizePath, uniqueStrings } from "../utils/text.js";
|
|
4
4
|
const DEFAULT_MAX_CONTEXT_NODES = 16;
|
|
5
5
|
export const CONTEXT_PACKING_STRATEGY = "mmr-style-document-round-robin";
|
|
6
|
+
export const CONTEXT_PACKING_STRATEGIES = [CONTEXT_PACKING_STRATEGY, "mmr"];
|
|
7
|
+
export const DEFAULT_MMR_LAMBDA = 0.65;
|
|
8
|
+
const MMR_SAME_DOCUMENT_REDUNDANCY_THRESHOLD = 0.8;
|
|
6
9
|
export function buildContext(repository, config, query, options = {}) {
|
|
10
|
+
const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
|
|
11
|
+
const results = searchGraph(repository, config, query, searchLimit, options.searchOptions);
|
|
12
|
+
return buildContextFromSearchResults(repository, config, query, results, options);
|
|
13
|
+
}
|
|
14
|
+
export async function buildContextAsync(repository, config, query, options = {}) {
|
|
15
|
+
const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
|
|
16
|
+
const explanation = await explainSearchGraphAsync(repository, config, query, searchLimit, options.searchOptions);
|
|
17
|
+
return buildContextFromSearchResults(repository, config, query, explanation.results, options, explanation.semanticDiagnostic);
|
|
18
|
+
}
|
|
19
|
+
export function buildContextFromSearchResults(repository, config, query, results, options, semanticDiagnostic) {
|
|
7
20
|
const knownFiles = normalizeKnownFiles(options.knownFiles ?? []);
|
|
8
21
|
const maxChars = positiveIntegerOr(options.maxChars, config.search.maxContextChars);
|
|
9
|
-
const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
|
|
10
22
|
const maxDepth = positiveIntegerOr(options.maxDepth, config.search.maxDepth);
|
|
11
|
-
const results = searchGraph(repository, config, query, searchLimit, options.searchOptions);
|
|
12
23
|
const collection = collectContextCandidates(repository, config, results, maxDepth);
|
|
13
24
|
const candidates = knownFiles.length
|
|
14
25
|
? mergeKnownFileCandidates(repository, collection.candidates, knownFiles)
|
|
15
26
|
: collection.candidates;
|
|
16
|
-
const
|
|
17
|
-
const
|
|
27
|
+
const packingStrategy = options.packingStrategy ?? CONTEXT_PACKING_STRATEGY;
|
|
28
|
+
const packed = packContext(repository, config, query, enrichContextCandidates(repository, candidates), maxChars, options.mode, packingStrategy, mmrLambdaOrDefault(options.mmrLambda));
|
|
29
|
+
const hinted = addAgentHints(packed.result, knownFiles);
|
|
30
|
+
const result = semanticDiagnostic ? { ...hinted, semanticDiagnostic } : hinted;
|
|
18
31
|
if (!options.debug) {
|
|
19
32
|
return result;
|
|
20
33
|
}
|
|
@@ -25,14 +38,18 @@ export function buildContext(repository, config, query, options = {}) {
|
|
|
25
38
|
candidateCount: candidates.length,
|
|
26
39
|
directCandidates: candidates.filter((candidate) => candidate.direct).length,
|
|
27
40
|
expandedCandidates: candidates.filter((candidate) => !candidate.direct).length,
|
|
28
|
-
packingStrategy:
|
|
41
|
+
packingStrategy: packed.packingStrategy,
|
|
42
|
+
packingSimilarity: packed.packingSimilarity,
|
|
43
|
+
mmrLambda: packed.mmrLambda,
|
|
44
|
+
packingSelections: packed.packingSelections,
|
|
29
45
|
packedItems: result.items.length,
|
|
30
46
|
packedUniqueDocuments: uniqueStrings(result.items.map((item) => item.path)).length,
|
|
31
47
|
packingDiversityRatio: result.items.length
|
|
32
48
|
? Number((uniqueStrings(result.items.map((item) => item.path)).length / result.items.length).toFixed(4))
|
|
33
49
|
: 0,
|
|
34
50
|
budgetTruncatedItems: packed.budgetTruncatedItems,
|
|
35
|
-
budgetSkippedItems: packed.budgetSkippedItems
|
|
51
|
+
budgetSkippedItems: packed.budgetSkippedItems,
|
|
52
|
+
redundancySkippedItems: packed.redundancySkippedItems || undefined
|
|
36
53
|
}
|
|
37
54
|
};
|
|
38
55
|
}
|
|
@@ -208,10 +225,12 @@ function collectContextCandidates(repository, config, results, maxDepth) {
|
|
|
208
225
|
}
|
|
209
226
|
function enrichContextCandidates(repository, candidates) {
|
|
210
227
|
return candidates.map((candidate) => {
|
|
228
|
+
const row = repository.contextChunkForNode(candidate.nodeId);
|
|
211
229
|
const sourceRefs = sourceRefsForCandidate(repository, candidate);
|
|
212
230
|
const riskNotes = riskNotesForCandidate(candidate);
|
|
213
231
|
return {
|
|
214
232
|
...candidate,
|
|
233
|
+
chunkId: row?.chunk.id,
|
|
215
234
|
sourceRefs: sourceRefs.length ? sourceRefs : undefined,
|
|
216
235
|
riskNotes: riskNotes.length ? riskNotes : undefined
|
|
217
236
|
};
|
|
@@ -294,16 +313,19 @@ function compareContextCandidates(left, right) {
|
|
|
294
313
|
}
|
|
295
314
|
return right.score - left.score;
|
|
296
315
|
}
|
|
297
|
-
function packContext(query, candidates, maxChars, mode) {
|
|
316
|
+
function packContext(repository, config, query, candidates, maxChars, mode, packingStrategy, mmrLambda) {
|
|
317
|
+
const ranking = packingStrategy === "mmr"
|
|
318
|
+
? rankCandidatesWithMmr(repository, config, candidates, mmrLambda)
|
|
319
|
+
: { candidates, redundancySkippedItems: 0 };
|
|
298
320
|
const items = [];
|
|
299
321
|
let usedChars = 0;
|
|
300
322
|
let budgetTruncatedItems = 0;
|
|
301
323
|
let budgetSkippedItems = 0;
|
|
302
|
-
for (let index = 0; index < candidates.length; index += 1) {
|
|
303
|
-
const candidate = candidates[index];
|
|
324
|
+
for (let index = 0; index < ranking.candidates.length; index += 1) {
|
|
325
|
+
const candidate = ranking.candidates[index];
|
|
304
326
|
const remaining = maxChars - usedChars;
|
|
305
327
|
if (remaining <= 0) {
|
|
306
|
-
budgetSkippedItems += candidates.length - index;
|
|
328
|
+
budgetSkippedItems += ranking.candidates.length - index;
|
|
307
329
|
break;
|
|
308
330
|
}
|
|
309
331
|
const content = trimToBudget(candidate.content, remaining);
|
|
@@ -332,7 +354,135 @@ function packContext(query, candidates, maxChars, mode) {
|
|
|
332
354
|
content
|
|
333
355
|
});
|
|
334
356
|
}
|
|
335
|
-
return {
|
|
357
|
+
return {
|
|
358
|
+
result: {
|
|
359
|
+
query,
|
|
360
|
+
maxChars,
|
|
361
|
+
usedChars,
|
|
362
|
+
mode,
|
|
363
|
+
items,
|
|
364
|
+
packing: {
|
|
365
|
+
strategy: packingStrategy,
|
|
366
|
+
similarity: ranking.packingSimilarity,
|
|
367
|
+
mmrLambda: packingStrategy === "mmr" ? mmrLambda : undefined,
|
|
368
|
+
redundancySkippedItems: ranking.redundancySkippedItems || undefined
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
packingStrategy,
|
|
372
|
+
packingSimilarity: ranking.packingSimilarity,
|
|
373
|
+
mmrLambda: packingStrategy === "mmr" ? mmrLambda : undefined,
|
|
374
|
+
packingSelections: ranking.packingSelections,
|
|
375
|
+
budgetTruncatedItems,
|
|
376
|
+
budgetSkippedItems,
|
|
377
|
+
redundancySkippedItems: ranking.redundancySkippedItems
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function rankCandidatesWithMmr(repository, config, candidates, lambda) {
|
|
381
|
+
if (!candidates.length) {
|
|
382
|
+
return {
|
|
383
|
+
candidates: [],
|
|
384
|
+
packingSimilarity: "lexical-jaccard",
|
|
385
|
+
packingSelections: [],
|
|
386
|
+
redundancySkippedItems: 0
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
const vectors = repository.chunkVectors(candidates.flatMap((candidate) => candidate.chunkId ? [candidate.chunkId] : []), config.embedding.provider, config.embedding.model, config.embedding.dimensions);
|
|
390
|
+
const tokenSets = new Map(candidates.map((candidate) => [candidate.nodeId, tokensForSimilarity(candidate.content)]));
|
|
391
|
+
const remaining = candidates.map((candidate, order) => ({ candidate, order }));
|
|
392
|
+
const selected = [];
|
|
393
|
+
const selections = [];
|
|
394
|
+
let redundancySkippedItems = 0;
|
|
395
|
+
const maximumScore = Math.max(...candidates.map((candidate) => Math.max(0, candidate.score)), 1);
|
|
396
|
+
while (remaining.length) {
|
|
397
|
+
const scored = remaining.map((entry) => {
|
|
398
|
+
const queryRelevance = clamp01(Math.max(0, entry.candidate.score) / maximumScore);
|
|
399
|
+
const similarities = selected.map((other) => candidateSimilarity(entry.candidate, other, vectors, tokenSets));
|
|
400
|
+
const mostRedundant = similarities.reduce((best, current) => current.value > best.value ? current : best, { value: 0, source: "none" });
|
|
401
|
+
return {
|
|
402
|
+
...entry,
|
|
403
|
+
queryRelevance,
|
|
404
|
+
redundancyPenalty: mostRedundant.value,
|
|
405
|
+
similaritySource: mostRedundant.source,
|
|
406
|
+
mmrScore: lambda * queryRelevance - (1 - lambda) * mostRedundant.value
|
|
407
|
+
};
|
|
408
|
+
}).sort((left, right) => (right.mmrScore - left.mmrScore
|
|
409
|
+
|| right.queryRelevance - left.queryRelevance
|
|
410
|
+
|| left.order - right.order));
|
|
411
|
+
const best = scored[0];
|
|
412
|
+
const remainingIndex = remaining.findIndex((entry) => entry.order === best.order);
|
|
413
|
+
remaining.splice(remainingIndex, 1);
|
|
414
|
+
const repeatsSelectedDocument = selected.some((candidate) => candidate.path === best.candidate.path);
|
|
415
|
+
if (repeatsSelectedDocument && best.redundancyPenalty >= MMR_SAME_DOCUMENT_REDUNDANCY_THRESHOLD) {
|
|
416
|
+
redundancySkippedItems += 1;
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
selected.push(best.candidate);
|
|
420
|
+
selections.push({
|
|
421
|
+
nodeId: best.candidate.nodeId,
|
|
422
|
+
path: best.candidate.path,
|
|
423
|
+
queryRelevance: roundScore(best.queryRelevance),
|
|
424
|
+
redundancyPenalty: roundScore(best.redundancyPenalty),
|
|
425
|
+
mmrScore: roundScore(best.mmrScore),
|
|
426
|
+
similaritySource: best.similaritySource
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const vectorCandidateCount = candidates.filter((candidate) => candidate.chunkId && vectors.has(candidate.chunkId)).length;
|
|
430
|
+
return {
|
|
431
|
+
candidates: selected,
|
|
432
|
+
packingSimilarity: vectorCandidateCount === candidates.length
|
|
433
|
+
? "embedding-cosine"
|
|
434
|
+
: vectorCandidateCount > 1 ? "hybrid" : "lexical-jaccard",
|
|
435
|
+
packingSelections: selections,
|
|
436
|
+
redundancySkippedItems
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function candidateSimilarity(left, right, vectors, tokenSets) {
|
|
440
|
+
const leftVector = left.chunkId ? vectors.get(left.chunkId) : undefined;
|
|
441
|
+
const rightVector = right.chunkId ? vectors.get(right.chunkId) : undefined;
|
|
442
|
+
if (leftVector && rightVector && leftVector.length === rightVector.length) {
|
|
443
|
+
return { value: clamp01(cosineSimilarity(leftVector, rightVector)), source: "embedding-cosine" };
|
|
444
|
+
}
|
|
445
|
+
return {
|
|
446
|
+
value: jaccardSimilarity(tokenSets.get(left.nodeId) ?? new Set(), tokenSets.get(right.nodeId) ?? new Set()),
|
|
447
|
+
source: "lexical-jaccard"
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
function cosineSimilarity(left, right) {
|
|
451
|
+
let dot = 0;
|
|
452
|
+
let leftMagnitude = 0;
|
|
453
|
+
let rightMagnitude = 0;
|
|
454
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
455
|
+
dot += left[index] * right[index];
|
|
456
|
+
leftMagnitude += left[index] * left[index];
|
|
457
|
+
rightMagnitude += right[index] * right[index];
|
|
458
|
+
}
|
|
459
|
+
return leftMagnitude > 0 && rightMagnitude > 0 ? dot / Math.sqrt(leftMagnitude * rightMagnitude) : 0;
|
|
460
|
+
}
|
|
461
|
+
function tokensForSimilarity(content) {
|
|
462
|
+
return new Set(content.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []);
|
|
463
|
+
}
|
|
464
|
+
function jaccardSimilarity(left, right) {
|
|
465
|
+
if (!left.size && !right.size) {
|
|
466
|
+
return 0;
|
|
467
|
+
}
|
|
468
|
+
let intersection = 0;
|
|
469
|
+
for (const token of left) {
|
|
470
|
+
if (right.has(token)) {
|
|
471
|
+
intersection += 1;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return intersection / (left.size + right.size - intersection);
|
|
475
|
+
}
|
|
476
|
+
function mmrLambdaOrDefault(value) {
|
|
477
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1
|
|
478
|
+
? value
|
|
479
|
+
: DEFAULT_MMR_LAMBDA;
|
|
480
|
+
}
|
|
481
|
+
function clamp01(value) {
|
|
482
|
+
return Math.min(1, Math.max(0, value));
|
|
483
|
+
}
|
|
484
|
+
function roundScore(value) {
|
|
485
|
+
return Number(value.toFixed(4));
|
|
336
486
|
}
|
|
337
487
|
function candidateFromSearchResult(result) {
|
|
338
488
|
return {
|