@daogee/mdgraph 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README-ZH.md +203 -0
- package/README.md +203 -0
- package/agent-pack/README.md +26 -0
- package/agent-pack/host-examples.md +71 -0
- package/agent-pack/mcp-config.example.json +14 -0
- package/agent-pack/mdgraph-agent-instructions.md +21 -0
- package/agent-pack/prompts/relationship-trace.md +12 -0
- package/agent-pack/prompts/status-doctor.md +13 -0
- package/agent-pack/prompts/task-start-context.md +15 -0
- package/dist/analysis/doctor-scope.d.ts +8 -0
- package/dist/analysis/doctor-scope.js +109 -0
- package/dist/analysis/doctor.d.ts +148 -0
- package/dist/analysis/doctor.js +919 -0
- package/dist/analysis/status-freshness.d.ts +13 -0
- package/dist/analysis/status-freshness.js +55 -0
- package/dist/benchmark/benchmark.d.ts +118 -0
- package/dist/benchmark/benchmark.js +357 -0
- package/dist/bin/mdgraph.d.ts +2 -0
- package/dist/bin/mdgraph.js +877 -0
- package/dist/bundle/bundle.d.ts +66 -0
- package/dist/bundle/bundle.js +320 -0
- package/dist/config/limits.d.ts +24 -0
- package/dist/config/limits.js +24 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +177 -0
- package/dist/db/connection.d.ts +15 -0
- package/dist/db/connection.js +145 -0
- package/dist/db/repositories.d.ts +159 -0
- package/dist/db/repositories.js +929 -0
- package/dist/db/schema.sql +110 -0
- package/dist/db/sqlite-adapter.d.ts +18 -0
- package/dist/db/sqlite-adapter.js +60 -0
- package/dist/diff/graph-diff.d.ts +41 -0
- package/dist/diff/graph-diff.js +334 -0
- package/dist/evaluation/retrieval-eval.d.ts +115 -0
- package/dist/evaluation/retrieval-eval.js +399 -0
- package/dist/export/diagram.d.ts +11 -0
- package/dist/export/diagram.js +41 -0
- package/dist/export/graphjson.d.ts +89 -0
- package/dist/export/graphjson.js +299 -0
- package/dist/export/markdown-index.d.ts +21 -0
- package/dist/export/markdown-index.js +89 -0
- package/dist/export/source-bridge.d.ts +22 -0
- package/dist/export/source-bridge.js +83 -0
- package/dist/extraction/entity-extractor.d.ts +12 -0
- package/dist/extraction/entity-extractor.js +153 -0
- package/dist/extraction/graph-builder.d.ts +2 -0
- package/dist/extraction/graph-builder.js +168 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +28 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +100 -0
- package/dist/mcp/debug.d.ts +7 -0
- package/dist/mcp/debug.js +41 -0
- package/dist/mcp/server-instructions.d.ts +2 -0
- package/dist/mcp/server-instructions.js +40 -0
- package/dist/mcp/server.d.ts +28 -0
- package/dist/mcp/server.js +232 -0
- package/dist/mcp/tools.d.ts +31 -0
- package/dist/mcp/tools.js +506 -0
- package/dist/mcp/transport.d.ts +50 -0
- package/dist/mcp/transport.js +88 -0
- package/dist/parser/frontmatter.d.ts +10 -0
- package/dist/parser/frontmatter.js +191 -0
- package/dist/parser/links.d.ts +6 -0
- package/dist/parser/links.js +9 -0
- package/dist/parser/markdown-parser.d.ts +2 -0
- package/dist/parser/markdown-parser.js +267 -0
- package/dist/query/context-builder.d.ts +85 -0
- package/dist/query/context-builder.js +413 -0
- package/dist/query/search.d.ts +32 -0
- package/dist/query/search.js +237 -0
- package/dist/query/trace.d.ts +10 -0
- package/dist/query/trace.js +55 -0
- package/dist/reporting/report.d.ts +49 -0
- package/dist/reporting/report.js +143 -0
- package/dist/resolution/link-resolver.d.ts +17 -0
- package/dist/resolution/link-resolver.js +113 -0
- package/dist/scanner/file-scanner.d.ts +4 -0
- package/dist/scanner/file-scanner.js +144 -0
- package/dist/semantic/local-embedding.d.ts +4 -0
- package/dist/semantic/local-embedding.js +30 -0
- package/dist/semantic/status.d.ts +19 -0
- package/dist/semantic/status.js +70 -0
- package/dist/semantic/vector-codec.d.ts +3 -0
- package/dist/semantic/vector-codec.js +35 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +15 -0
- package/dist/utils/bounded-json.d.ts +9 -0
- package/dist/utils/bounded-json.js +57 -0
- package/dist/utils/content-risk.d.ts +5 -0
- package/dist/utils/content-risk.js +20 -0
- package/dist/utils/fts.d.ts +3 -0
- package/dist/utils/fts.js +52 -0
- package/dist/utils/id.d.ts +2 -0
- package/dist/utils/id.js +8 -0
- package/dist/utils/path-safety.d.ts +4 -0
- package/dist/utils/path-safety.js +25 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.js +36 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +11 -0
- package/dist/watcher/file-watcher.d.ts +11 -0
- package/dist/watcher/file-watcher.js +127 -0
- package/docs/EN/Agent_Integration.md +129 -0
- package/docs/EN/Architecture.md +135 -0
- package/docs/EN/Evaluation_Questions.md +68 -0
- package/docs/EN/Output_Contracts.md +274 -0
- package/docs/EN/Public_Contracts.md +88 -0
- package/docs/EN/Public_Contracts_1.0.md +234 -0
- package/docs/EN/Release_Checklist.md +82 -0
- package/docs/ZH/Agent_Integration.md +105 -0
- package/docs/ZH/Architecture.md +124 -0
- package/docs/ZH/Evaluation_Questions.md +66 -0
- package/docs/ZH/Output_Contracts.md +269 -0
- package/docs/ZH/Public_Contracts.md +81 -0
- package/docs/ZH/Public_Contracts_1.0.md +202 -0
- package/docs/ZH/Release_Checklist.md +83 -0
- package/package.json +94 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { EDGE_WEIGHTS } from "../types.js";
|
|
2
|
+
import { LinkResolver } from "../resolution/link-resolver.js";
|
|
3
|
+
import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
|
|
4
|
+
import { stableId } from "../utils/id.js";
|
|
5
|
+
import { estimateTokens, normalizeEntityName, normalizePath } from "../utils/text.js";
|
|
6
|
+
import { extractEntities, inferEntityKind } from "./entity-extractor.js";
|
|
7
|
+
export function buildGraphRecords(documents, config) {
|
|
8
|
+
const now = new Date().toISOString();
|
|
9
|
+
const resolver = new LinkResolver(documents);
|
|
10
|
+
const graphDocuments = [];
|
|
11
|
+
const sections = [];
|
|
12
|
+
const chunks = [];
|
|
13
|
+
const entities = [];
|
|
14
|
+
const sourceRefs = [];
|
|
15
|
+
const edges = [];
|
|
16
|
+
const vectors = [];
|
|
17
|
+
const entityByKey = new Map();
|
|
18
|
+
const sourceRefByPath = new Map();
|
|
19
|
+
const shouldEmbed = supportsLocalEmbedding(config);
|
|
20
|
+
for (const document of documents) {
|
|
21
|
+
graphDocuments.push({
|
|
22
|
+
id: document.id,
|
|
23
|
+
path: document.relativePath,
|
|
24
|
+
title: document.title,
|
|
25
|
+
type: document.frontmatter.type ?? "other",
|
|
26
|
+
status: document.frontmatter.status ?? "active",
|
|
27
|
+
hash: document.hash,
|
|
28
|
+
trustTier: document.frontmatter.trust_tier ?? "authored",
|
|
29
|
+
updatedAt: undefined,
|
|
30
|
+
indexedAt: now,
|
|
31
|
+
metadata: {
|
|
32
|
+
declaredTrustTier: document.frontmatter.trust_tier,
|
|
33
|
+
frontmatterId: document.frontmatter.id,
|
|
34
|
+
tags: document.frontmatter.tags ?? []
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
for (const section of document.sections) {
|
|
38
|
+
sections.push({ ...section, documentId: document.id });
|
|
39
|
+
edges.push(makeEdge(document.id, section.id, "CONTAINS", "heading", 1, now));
|
|
40
|
+
const chunk = {
|
|
41
|
+
id: stableId("chunk", `${section.id}:content`),
|
|
42
|
+
documentId: document.id,
|
|
43
|
+
sectionId: section.id,
|
|
44
|
+
content: section.content,
|
|
45
|
+
tokenEstimate: estimateTokens(section.content),
|
|
46
|
+
metadata: { heading: section.heading, anchor: section.anchor }
|
|
47
|
+
};
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
if (shouldEmbed) {
|
|
50
|
+
vectors.push({
|
|
51
|
+
chunkId: chunk.id,
|
|
52
|
+
provider: config.embedding.provider,
|
|
53
|
+
model: config.embedding.model,
|
|
54
|
+
dimensions: config.embedding.dimensions,
|
|
55
|
+
vector: embedTextLocal(chunk.content, config.embedding.dimensions),
|
|
56
|
+
createdAt: now
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
edges.push(makeEdge(section.id, chunk.id, "CONTAINS", "heading", 1, now));
|
|
60
|
+
}
|
|
61
|
+
for (const extracted of extractEntities(document, config)) {
|
|
62
|
+
const entity = ensureEntity(entities, entityByKey, extracted, now);
|
|
63
|
+
const fromId = extracted.sectionId ?? document.id;
|
|
64
|
+
edges.push(makeEdge(fromId, entity.id, extracted.role === "definition" ? "DEFINES" : "REFERENCES", extracted.provenance, extracted.confidence, now));
|
|
65
|
+
}
|
|
66
|
+
addSourceRefEdges(document, document.frontmatter.implements ?? [], "IMPLEMENTS", sourceRefs, sourceRefByPath, edges, now);
|
|
67
|
+
addSourceRefEdges(document, document.frontmatter.source_refs ?? [], "REFERENCES_SOURCE", sourceRefs, sourceRefByPath, edges, now);
|
|
68
|
+
addRelationshipEdges(document, document.frontmatter.depends_on ?? [], "DEPENDS_ON", "frontmatter", resolver, entities, entityByKey, edges, now);
|
|
69
|
+
addRelationshipEdges(document, document.frontmatter.supersedes ?? [], "SUPERSEDES", "frontmatter", resolver, entities, entityByKey, edges, now);
|
|
70
|
+
addRelationshipEdges(document, document.frontmatter.deprecated_by ?? [], "DEPRECATED_BY", "frontmatter", resolver, entities, entityByKey, edges, now);
|
|
71
|
+
for (const link of document.markdownLinks) {
|
|
72
|
+
const resolved = resolver.resolveMarkdownUrl(link.url, document);
|
|
73
|
+
if (resolved) {
|
|
74
|
+
edges.push(makeEdge(link.sectionId ?? document.id, resolved.nodeId, "LINKS_TO", "markdown_link", 0.9, now));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const link of document.wikiLinks) {
|
|
78
|
+
const resolved = resolver.resolveDocumentRef(link.target, document, link.anchor);
|
|
79
|
+
if (resolved) {
|
|
80
|
+
edges.push(makeEdge(link.sectionId ?? document.id, resolved.nodeId, "LINKS_TO", "wikilink", 0.9, now));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
documents: dedupeById(graphDocuments),
|
|
86
|
+
sections: dedupeById(sections),
|
|
87
|
+
entities: dedupeById(entities),
|
|
88
|
+
sourceRefs: dedupeById(sourceRefs),
|
|
89
|
+
edges: dedupeEdges(edges),
|
|
90
|
+
chunks: dedupeById(chunks),
|
|
91
|
+
vectors: dedupeVectors(vectors)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function addSourceRefEdges(document, paths, kind, sourceRefs, sourceRefByPath, edges, now) {
|
|
95
|
+
for (const sourcePath of paths) {
|
|
96
|
+
const sourceRef = ensureSourceRef(sourceRefs, sourceRefByPath, sourcePath, now);
|
|
97
|
+
edges.push(makeEdge(document.id, sourceRef.id, kind, "frontmatter", 1, now));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function addRelationshipEdges(document, references, kind, provenance, resolver, entities, entityByKey, edges, now) {
|
|
101
|
+
for (const reference of references) {
|
|
102
|
+
const resolved = resolver.resolveDocumentRef(reference, document);
|
|
103
|
+
if (resolved) {
|
|
104
|
+
edges.push(makeEdge(document.id, resolved.nodeId, kind, provenance, 1, now));
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const entity = ensureEntity(entities, entityByKey, {
|
|
108
|
+
name: reference,
|
|
109
|
+
kind: inferEntityKind(reference)
|
|
110
|
+
}, now);
|
|
111
|
+
edges.push(makeEdge(document.id, entity.id, kind, provenance, 0.85, now));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function ensureEntity(target, byKey, extracted, now) {
|
|
115
|
+
const normalizedName = normalizeEntityName(extracted.name);
|
|
116
|
+
const key = `${extracted.kind}:${normalizedName}`;
|
|
117
|
+
const existing = byKey.get(key);
|
|
118
|
+
if (existing) {
|
|
119
|
+
return existing;
|
|
120
|
+
}
|
|
121
|
+
const entity = {
|
|
122
|
+
id: stableId("entity", key),
|
|
123
|
+
name: extracted.name,
|
|
124
|
+
normalizedName,
|
|
125
|
+
kind: extracted.kind,
|
|
126
|
+
createdAt: now
|
|
127
|
+
};
|
|
128
|
+
byKey.set(key, entity);
|
|
129
|
+
target.push(entity);
|
|
130
|
+
return entity;
|
|
131
|
+
}
|
|
132
|
+
function ensureSourceRef(target, byPath, rawPath, now) {
|
|
133
|
+
const normalizedPath = normalizePath(rawPath.trim());
|
|
134
|
+
const existing = byPath.get(normalizedPath.toLowerCase());
|
|
135
|
+
if (existing) {
|
|
136
|
+
return existing;
|
|
137
|
+
}
|
|
138
|
+
const sourceRef = {
|
|
139
|
+
id: stableId("source_ref", normalizedPath.toLowerCase()),
|
|
140
|
+
path: normalizedPath,
|
|
141
|
+
normalizedPath: normalizedPath.toLowerCase(),
|
|
142
|
+
createdAt: now
|
|
143
|
+
};
|
|
144
|
+
byPath.set(sourceRef.normalizedPath, sourceRef);
|
|
145
|
+
target.push(sourceRef);
|
|
146
|
+
return sourceRef;
|
|
147
|
+
}
|
|
148
|
+
function makeEdge(fromId, toId, kind, provenance, confidence, now) {
|
|
149
|
+
return {
|
|
150
|
+
id: stableId("edge", `${fromId}:${kind}:${toId}:${provenance}`),
|
|
151
|
+
fromId,
|
|
152
|
+
toId,
|
|
153
|
+
kind,
|
|
154
|
+
weight: EDGE_WEIGHTS[kind],
|
|
155
|
+
confidence,
|
|
156
|
+
provenance,
|
|
157
|
+
createdAt: now
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function dedupeById(items) {
|
|
161
|
+
return [...new Map(items.map((item) => [item.id, item])).values()];
|
|
162
|
+
}
|
|
163
|
+
function dedupeEdges(edges) {
|
|
164
|
+
return [...new Map(edges.map((edge) => [`${edge.fromId}:${edge.toId}:${edge.kind}:${edge.provenance}`, edge])).values()];
|
|
165
|
+
}
|
|
166
|
+
function dedupeVectors(vectors) {
|
|
167
|
+
return [...new Map(vectors.map((vector) => [vector.chunkId, vector])).values()];
|
|
168
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export { DEFAULT_CONFIG, configPath, databasePath, initConfig, loadConfig } from "./config/load-config.js";
|
|
2
|
+
export { DOCTOR_WARNING_CODES, runDoctor, formatDoctorReport } from "./analysis/doctor.js";
|
|
3
|
+
export { formatBenchmarkReport, generateBenchmarkReport, loadBenchmarkReport, parseAgentRunRecords } from "./benchmark/benchmark.js";
|
|
4
|
+
export { createGraphBundle, verifyGraphBundle, sourceSnapshot, hashCanonical, canonicalJson } from "./bundle/bundle.js";
|
|
5
|
+
export { openDatabase } from "./db/connection.js";
|
|
6
|
+
export { GraphRepository } from "./db/repositories.js";
|
|
7
|
+
export { generateGraphDiff, formatGraphDiff } from "./diff/graph-diff.js";
|
|
8
|
+
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
9
|
+
export { buildMermaidTraceExport, formatTraceMermaid } from "./export/diagram.js";
|
|
10
|
+
export { buildGraphJsonExport, formatGraphJsonVerification, graphJsonHash, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "./export/graphjson.js";
|
|
11
|
+
export { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "./export/markdown-index.js";
|
|
12
|
+
export { buildSourceBridgeReport } from "./export/source-bridge.js";
|
|
13
|
+
export { buildGraphRecords } from "./extraction/graph-builder.js";
|
|
14
|
+
export { extractEntities } from "./extraction/entity-extractor.js";
|
|
15
|
+
export { indexProject } from "./indexer.js";
|
|
16
|
+
export { MCPServer, startStdioMcpServer } from "./mcp/server.js";
|
|
17
|
+
export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
18
|
+
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
|
+
export { buildContext } from "./query/context-builder.js";
|
|
20
|
+
export { explainSearchGraph, searchGraph } from "./query/search.js";
|
|
21
|
+
export { traceNodes } from "./query/trace.js";
|
|
22
|
+
export { generateReport, formatReport } from "./reporting/report.js";
|
|
23
|
+
export { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
24
|
+
export { embedTextLocal } from "./semantic/local-embedding.js";
|
|
25
|
+
export { semanticStatusReport } from "./semantic/status.js";
|
|
26
|
+
export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-codec.js";
|
|
27
|
+
export { watchProject } from "./watcher/file-watcher.js";
|
|
28
|
+
export * from "./types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export { DEFAULT_CONFIG, configPath, databasePath, initConfig, loadConfig } from "./config/load-config.js";
|
|
2
|
+
export { DOCTOR_WARNING_CODES, runDoctor, formatDoctorReport } from "./analysis/doctor.js";
|
|
3
|
+
export { formatBenchmarkReport, generateBenchmarkReport, loadBenchmarkReport, parseAgentRunRecords } from "./benchmark/benchmark.js";
|
|
4
|
+
export { createGraphBundle, verifyGraphBundle, sourceSnapshot, hashCanonical, canonicalJson } from "./bundle/bundle.js";
|
|
5
|
+
export { openDatabase } from "./db/connection.js";
|
|
6
|
+
export { GraphRepository } from "./db/repositories.js";
|
|
7
|
+
export { generateGraphDiff, formatGraphDiff } from "./diff/graph-diff.js";
|
|
8
|
+
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
9
|
+
export { buildMermaidTraceExport, formatTraceMermaid } from "./export/diagram.js";
|
|
10
|
+
export { buildGraphJsonExport, formatGraphJsonVerification, graphJsonHash, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "./export/graphjson.js";
|
|
11
|
+
export { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "./export/markdown-index.js";
|
|
12
|
+
export { buildSourceBridgeReport } from "./export/source-bridge.js";
|
|
13
|
+
export { buildGraphRecords } from "./extraction/graph-builder.js";
|
|
14
|
+
export { extractEntities } from "./extraction/entity-extractor.js";
|
|
15
|
+
export { indexProject } from "./indexer.js";
|
|
16
|
+
export { MCPServer, startStdioMcpServer } from "./mcp/server.js";
|
|
17
|
+
export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
18
|
+
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
|
+
export { buildContext } from "./query/context-builder.js";
|
|
20
|
+
export { explainSearchGraph, searchGraph } from "./query/search.js";
|
|
21
|
+
export { traceNodes } from "./query/trace.js";
|
|
22
|
+
export { generateReport, formatReport } from "./reporting/report.js";
|
|
23
|
+
export { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
24
|
+
export { embedTextLocal } from "./semantic/local-embedding.js";
|
|
25
|
+
export { semanticStatusReport } from "./semantic/status.js";
|
|
26
|
+
export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-codec.js";
|
|
27
|
+
export { watchProject } from "./watcher/file-watcher.js";
|
|
28
|
+
export * from "./types.js";
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type StatusCounts } from "./db/repositories.js";
|
|
2
|
+
export interface IndexResult {
|
|
3
|
+
files: number;
|
|
4
|
+
changed: number;
|
|
5
|
+
deleted: number;
|
|
6
|
+
unchanged: number;
|
|
7
|
+
skipped: number;
|
|
8
|
+
skippedFiles: Array<{
|
|
9
|
+
path: string;
|
|
10
|
+
reason: string;
|
|
11
|
+
}>;
|
|
12
|
+
mode: "full" | "incremental";
|
|
13
|
+
counts: StatusCounts;
|
|
14
|
+
}
|
|
15
|
+
export interface IndexOptions {
|
|
16
|
+
full?: boolean;
|
|
17
|
+
semantic?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export declare function indexProject(projectRoot: string, options?: IndexOptions): Promise<IndexResult>;
|
package/dist/indexer.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { loadConfig } from "./config/load-config.js";
|
|
2
|
+
import { openDatabase } from "./db/connection.js";
|
|
3
|
+
import { GraphRepository } from "./db/repositories.js";
|
|
4
|
+
import { buildGraphRecords } from "./extraction/graph-builder.js";
|
|
5
|
+
import { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
6
|
+
import { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
7
|
+
import { relativePathInsideRoot } from "./utils/path-safety.js";
|
|
8
|
+
export async function indexProject(projectRoot, options = {}) {
|
|
9
|
+
const config = effectiveConfig(loadConfig(projectRoot), options);
|
|
10
|
+
const files = await scanMarkdownFiles(projectRoot, config);
|
|
11
|
+
const { parsed, skippedFiles } = parseScannedFiles(projectRoot, files);
|
|
12
|
+
const records = buildGraphRecords(parsed, config);
|
|
13
|
+
const db = openDatabase(projectRoot);
|
|
14
|
+
try {
|
|
15
|
+
const repository = new GraphRepository(db);
|
|
16
|
+
if (options.full || repository.counts().documents === 0) {
|
|
17
|
+
repository.replaceAll(records);
|
|
18
|
+
return {
|
|
19
|
+
files: files.length,
|
|
20
|
+
changed: parsed.length,
|
|
21
|
+
deleted: 0,
|
|
22
|
+
unchanged: 0,
|
|
23
|
+
skipped: skippedFiles.length,
|
|
24
|
+
skippedFiles,
|
|
25
|
+
mode: "full",
|
|
26
|
+
counts: repository.counts()
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const existing = repository.documentHashes();
|
|
30
|
+
const currentPaths = new Set(files.map((file) => relativePathInsideRoot(projectRoot, file)).filter((value) => Boolean(value)));
|
|
31
|
+
const changedDocuments = parsed.filter((document) => existing.get(document.relativePath)?.hash !== document.hash);
|
|
32
|
+
const deletedDocumentIds = [...existing.entries()]
|
|
33
|
+
.filter(([documentPath]) => !currentPaths.has(documentPath))
|
|
34
|
+
.map(([, document]) => document.id);
|
|
35
|
+
if (changedDocuments.length || deletedDocumentIds.length) {
|
|
36
|
+
const changedIds = new Set(changedDocuments.map((document) => document.id));
|
|
37
|
+
const replacedDocumentIds = changedDocuments
|
|
38
|
+
.map((document) => existing.get(document.relativePath)?.id)
|
|
39
|
+
.filter((existingId) => typeof existingId === "string" && !changedIds.has(existingId));
|
|
40
|
+
repository.replaceDocuments(filterRecordsForDocuments(records, changedIds), [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds]);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
files: files.length,
|
|
44
|
+
changed: changedDocuments.length,
|
|
45
|
+
deleted: deletedDocumentIds.length,
|
|
46
|
+
unchanged: files.length - changedDocuments.length - skippedFiles.length,
|
|
47
|
+
skipped: skippedFiles.length,
|
|
48
|
+
skippedFiles,
|
|
49
|
+
mode: "incremental",
|
|
50
|
+
counts: repository.counts()
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
db.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function parseScannedFiles(projectRoot, files) {
|
|
58
|
+
const parsed = [];
|
|
59
|
+
const skippedFiles = [];
|
|
60
|
+
for (const file of files) {
|
|
61
|
+
try {
|
|
62
|
+
parsed.push(parseMarkdownDocument(projectRoot, file));
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
skippedFiles.push({
|
|
66
|
+
path: relativePathInsideRoot(projectRoot, file) ?? file,
|
|
67
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { parsed, skippedFiles };
|
|
72
|
+
}
|
|
73
|
+
function effectiveConfig(config, options) {
|
|
74
|
+
if (options.semantic === undefined) {
|
|
75
|
+
return config;
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
...config,
|
|
79
|
+
embedding: {
|
|
80
|
+
...config.embedding,
|
|
81
|
+
enabled: options.semantic
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function filterRecordsForDocuments(records, documentIds) {
|
|
86
|
+
const sectionIds = new Set(records.sections.filter((section) => documentIds.has(section.documentId)).map((section) => section.id));
|
|
87
|
+
const chunkIds = new Set(records.chunks.filter((chunk) => documentIds.has(chunk.documentId)).map((chunk) => chunk.id));
|
|
88
|
+
const ownedNodeIds = new Set([...documentIds, ...sectionIds, ...chunkIds]);
|
|
89
|
+
const changedEdges = records.edges.filter((edge) => ownedNodeIds.has(edge.fromId) || ownedNodeIds.has(edge.toId));
|
|
90
|
+
const referencedEntityIds = new Set(changedEdges.flatMap((edge) => [edge.fromId, edge.toId]));
|
|
91
|
+
return {
|
|
92
|
+
documents: records.documents.filter((document) => documentIds.has(document.id)),
|
|
93
|
+
sections: records.sections.filter((section) => sectionIds.has(section.id)),
|
|
94
|
+
entities: records.entities.filter((entity) => referencedEntityIds.has(entity.id)),
|
|
95
|
+
sourceRefs: records.sourceRefs.filter((sourceRef) => referencedEntityIds.has(sourceRef.id)),
|
|
96
|
+
edges: changedEdges,
|
|
97
|
+
chunks: records.chunks.filter((chunk) => chunkIds.has(chunk.id)),
|
|
98
|
+
vectors: records.vectors.filter((vector) => chunkIds.has(vector.chunkId))
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type McpErrorLayer = "transport.parse" | "transport.validate" | "transport.dispatch" | "protocol.dispatch" | "initialize.params" | "initialize.watch" | "tools.call.params" | "tools.call.input" | "tools.call.execute";
|
|
2
|
+
export declare function mcpDebugEnabled(): boolean;
|
|
3
|
+
export declare function mcpDebug(message: string, details?: Record<string, unknown>): void;
|
|
4
|
+
export declare function internalToolErrorMessage(error: unknown): string;
|
|
5
|
+
export declare function initializeErrorMessage(error: unknown): string;
|
|
6
|
+
export declare function errorMessage(error: unknown): string;
|
|
7
|
+
export declare function mcpErrorData(layer: McpErrorLayer, details?: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const DEBUG_ENV = "MDGRAPH_MCP_DEBUG";
|
|
2
|
+
export function mcpDebugEnabled() {
|
|
3
|
+
const raw = process.env[DEBUG_ENV];
|
|
4
|
+
return !!raw && raw !== "0" && raw.toLowerCase() !== "false";
|
|
5
|
+
}
|
|
6
|
+
export function mcpDebug(message, details) {
|
|
7
|
+
if (!mcpDebugEnabled()) {
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
const suffix = details ? ` ${safeDetails(details)}` : "";
|
|
11
|
+
process.stderr.write(`[MDGraph MCP] ${message}${suffix}\n`);
|
|
12
|
+
}
|
|
13
|
+
export function internalToolErrorMessage(error) {
|
|
14
|
+
return [
|
|
15
|
+
`MDGraph MCP internal error: ${errorMessage(error)}.`,
|
|
16
|
+
"Retry once; if it persists, use raw file tools for this task and inspect server stderr with MDGRAPH_MCP_DEBUG=1."
|
|
17
|
+
].join(" ");
|
|
18
|
+
}
|
|
19
|
+
export function initializeErrorMessage(error) {
|
|
20
|
+
return [
|
|
21
|
+
`MDGraph MCP initialization failed: ${errorMessage(error)}.`,
|
|
22
|
+
"Inspect server stderr for details; set MDGRAPH_MCP_DEBUG=1 to log initialize/tool-call boundaries."
|
|
23
|
+
].join(" ");
|
|
24
|
+
}
|
|
25
|
+
export function errorMessage(error) {
|
|
26
|
+
return error instanceof Error ? error.message : String(error);
|
|
27
|
+
}
|
|
28
|
+
export function mcpErrorData(layer, details) {
|
|
29
|
+
return {
|
|
30
|
+
layer,
|
|
31
|
+
...(details ?? {})
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function safeDetails(details) {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.stringify(details);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return "[unserializable details]";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare const SERVER_INSTRUCTIONS = "# MDGraph \u2014 Markdown document graph for coding agents\n\nMDGraph indexes project Markdown into a local SQLite graph: documents, sections,\nentities, source references, and semantic edges such as DEFINES, DEPENDS_ON,\nLINKS_TO, IMPLEMENTS, and REFERENCES_SOURCE.\n\nUse MDGraph as the first stop for documentation work. Treat it as invited\ndocumentation context, not hidden memory and not a source-code graph.\n\nDefault order for Markdown/documentation questions:\n\n1. mdgraph_status if index availability or freshness is unclear.\n2. mdgraph_context for task-start context when the task touches architecture,\n\troadmap, public contracts, CLI/MCP behavior, release process, docs policy,\n\tADRs, runbooks, incidents, source_refs, or any cross-document feature chain.\n3. mdgraph_search for exact docs keyword/entity/path/command/config/API/error\n\tlookups before raw grep or manual file reads.\n4. mdgraph_node or mdgraph_trace after search/context narrows the target.\n5. Raw file reads or text search only when MDGraph is inactive, stale for the\n\ttask, too sparse, exact neighboring prose is required, or the user explicitly\n\tasks for file-level inspection.\n\n- If index availability is unclear -> mdgraph_status.\n- Cross-document design, ADR, spec, runbook, incident, API, source-ref, or feature-chain questions -> mdgraph_context.\n- Quick keyword, entity, path, command, config key, API route, or error-code lookup -> mdgraph_search.\n- Known entity, document title, source path, graph id, or section path#anchor -> mdgraph_node.\n- Relationship questions such as \"how is A related to B\" -> mdgraph_trace.\n\nFor coding tasks, include the task text and any known file paths in the\nmdgraph_context query so the result works as a task-start documentation brief.\n\nPrefer returned context directly when it includes enough content, reasons,\nprovenance, source refs, and risk notes. Read files when MDGraph is unavailable, the result\nis too sparse, exact neighboring prose is required, or the user explicitly asks\nfor file-level inspection.";
|
|
2
|
+
export declare const SERVER_INSTRUCTIONS_UNINDEXED = "# MDGraph \u2014 inactive\n\nNo MDGraph index was found for this workspace. Use normal file tools for this\nsession unless the user asks to initialize or index MDGraph. Do not create or\nupdate an index without an explicit user request.";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const SERVER_INSTRUCTIONS = `# MDGraph — Markdown document graph for coding agents
|
|
2
|
+
|
|
3
|
+
MDGraph indexes project Markdown into a local SQLite graph: documents, sections,
|
|
4
|
+
entities, source references, and semantic edges such as DEFINES, DEPENDS_ON,
|
|
5
|
+
LINKS_TO, IMPLEMENTS, and REFERENCES_SOURCE.
|
|
6
|
+
|
|
7
|
+
Use MDGraph as the first stop for documentation work. Treat it as invited
|
|
8
|
+
documentation context, not hidden memory and not a source-code graph.
|
|
9
|
+
|
|
10
|
+
Default order for Markdown/documentation questions:
|
|
11
|
+
|
|
12
|
+
1. mdgraph_status if index availability or freshness is unclear.
|
|
13
|
+
2. mdgraph_context for task-start context when the task touches architecture,
|
|
14
|
+
roadmap, public contracts, CLI/MCP behavior, release process, docs policy,
|
|
15
|
+
ADRs, runbooks, incidents, source_refs, or any cross-document feature chain.
|
|
16
|
+
3. mdgraph_search for exact docs keyword/entity/path/command/config/API/error
|
|
17
|
+
lookups before raw grep or manual file reads.
|
|
18
|
+
4. mdgraph_node or mdgraph_trace after search/context narrows the target.
|
|
19
|
+
5. Raw file reads or text search only when MDGraph is inactive, stale for the
|
|
20
|
+
task, too sparse, exact neighboring prose is required, or the user explicitly
|
|
21
|
+
asks for file-level inspection.
|
|
22
|
+
|
|
23
|
+
- If index availability is unclear -> mdgraph_status.
|
|
24
|
+
- Cross-document design, ADR, spec, runbook, incident, API, source-ref, or feature-chain questions -> mdgraph_context.
|
|
25
|
+
- Quick keyword, entity, path, command, config key, API route, or error-code lookup -> mdgraph_search.
|
|
26
|
+
- Known entity, document title, source path, graph id, or section path#anchor -> mdgraph_node.
|
|
27
|
+
- Relationship questions such as "how is A related to B" -> mdgraph_trace.
|
|
28
|
+
|
|
29
|
+
For coding tasks, include the task text and any known file paths in the
|
|
30
|
+
mdgraph_context query so the result works as a task-start documentation brief.
|
|
31
|
+
|
|
32
|
+
Prefer returned context directly when it includes enough content, reasons,
|
|
33
|
+
provenance, source refs, and risk notes. Read files when MDGraph is unavailable, the result
|
|
34
|
+
is too sparse, exact neighboring prose is required, or the user explicitly asks
|
|
35
|
+
for file-level inspection.`;
|
|
36
|
+
export const SERVER_INSTRUCTIONS_UNINDEXED = `# MDGraph — inactive
|
|
37
|
+
|
|
38
|
+
No MDGraph index was found for this workspace. Use normal file tools for this
|
|
39
|
+
session unless the user asks to initialize or index MDGraph. Do not create or
|
|
40
|
+
update an index without an explicit user request.`;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type JsonRpcTransport } from "./transport.js";
|
|
2
|
+
export declare const PROTOCOL_VERSION = "2024-11-05";
|
|
3
|
+
export interface MCPServerOptions {
|
|
4
|
+
projectRoot?: string;
|
|
5
|
+
watch?: boolean;
|
|
6
|
+
semantic?: boolean;
|
|
7
|
+
debounceMs?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class MCPServer {
|
|
10
|
+
private readonly transport;
|
|
11
|
+
private readonly boundProjectRoot;
|
|
12
|
+
private projectRoot;
|
|
13
|
+
private toolHandler;
|
|
14
|
+
private readonly watchEnabled;
|
|
15
|
+
private readonly watchSemantic;
|
|
16
|
+
private readonly watchDebounceMs;
|
|
17
|
+
private watchHandle;
|
|
18
|
+
private watchRoot;
|
|
19
|
+
constructor(transport: JsonRpcTransport, options?: MCPServerOptions);
|
|
20
|
+
start(): void;
|
|
21
|
+
stop(): Promise<void>;
|
|
22
|
+
private handleMessage;
|
|
23
|
+
private handleInitialize;
|
|
24
|
+
private handleToolsCall;
|
|
25
|
+
private ensureWatch;
|
|
26
|
+
private stopWatch;
|
|
27
|
+
}
|
|
28
|
+
export declare function startStdioMcpServer(options?: MCPServerOptions): MCPServer;
|