@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
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { StorageDiagnostics, StatusCounts } from "../db/repositories.js";
|
|
2
2
|
import type { MDGraphConfig } from "../types.js";
|
|
3
|
+
import type { EmbeddingCapability, EmbeddingRuntimeStatus } from "./provider.js";
|
|
4
|
+
export { SUPPORTED_EMBEDDING_PROVIDERS } from "./provider-registry.js";
|
|
3
5
|
export type SemanticStatusState = "disabled" | "not_indexed" | "ready" | "unsupported_provider" | "needs_reindex";
|
|
4
6
|
export interface SemanticStatusReport {
|
|
5
7
|
state: SemanticStatusState;
|
|
@@ -8,6 +10,9 @@ export interface SemanticStatusReport {
|
|
|
8
10
|
model: string;
|
|
9
11
|
dimensions: number;
|
|
10
12
|
providerSupported: boolean;
|
|
13
|
+
capability: EmbeddingCapability | "unknown";
|
|
14
|
+
runtimeStatus: EmbeddingRuntimeStatus;
|
|
15
|
+
runtimeReason?: string;
|
|
11
16
|
indexed: boolean;
|
|
12
17
|
chunks: number;
|
|
13
18
|
vectors: number;
|
|
@@ -15,5 +20,5 @@ export interface SemanticStatusReport {
|
|
|
15
20
|
indexedProviders: StorageDiagnostics["vectors"]["providers"];
|
|
16
21
|
guidance: string[];
|
|
17
22
|
}
|
|
18
|
-
export declare const SUPPORTED_EMBEDDING_PROVIDERS: readonly ["local-hash"];
|
|
19
23
|
export declare function semanticStatusReport(config: MDGraphConfig, counts: StatusCounts | undefined, storage: StorageDiagnostics | undefined): SemanticStatusReport;
|
|
24
|
+
export declare function semanticStatusReportAsync(config: MDGraphConfig, counts: StatusCounts | undefined, storage: StorageDiagnostics | undefined): Promise<SemanticStatusReport>;
|
package/dist/semantic/status.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { LOCAL_EMBEDDING_PROVIDER } from "./local-embedding.js";
|
|
2
|
-
|
|
2
|
+
import { createEmbeddingProvider, embeddingCapability, isSupportedEmbeddingProvider } from "./provider-registry.js";
|
|
3
|
+
export { SUPPORTED_EMBEDDING_PROVIDERS } from "./provider-registry.js";
|
|
3
4
|
export function semanticStatusReport(config, counts, storage) {
|
|
4
5
|
const providerSupported = isSupportedEmbeddingProvider(config.embedding.provider);
|
|
5
6
|
const indexed = Boolean(counts);
|
|
@@ -39,6 +40,8 @@ export function semanticStatusReport(config, counts, storage) {
|
|
|
39
40
|
model: config.embedding.model,
|
|
40
41
|
dimensions: config.embedding.dimensions,
|
|
41
42
|
providerSupported,
|
|
43
|
+
capability: embeddingCapability(config.embedding.provider),
|
|
44
|
+
runtimeStatus: initialRuntimeStatus(config, providerSupported),
|
|
42
45
|
indexed,
|
|
43
46
|
chunks,
|
|
44
47
|
vectors,
|
|
@@ -47,8 +50,51 @@ export function semanticStatusReport(config, counts, storage) {
|
|
|
47
50
|
guidance
|
|
48
51
|
};
|
|
49
52
|
}
|
|
50
|
-
function
|
|
51
|
-
|
|
53
|
+
export async function semanticStatusReportAsync(config, counts, storage) {
|
|
54
|
+
const report = semanticStatusReport(config, counts, storage);
|
|
55
|
+
if (!config.embedding.enabled || !report.providerSupported || config.embedding.provider === LOCAL_EMBEDDING_PROVIDER) {
|
|
56
|
+
return report;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const availability = await createEmbeddingProvider(config.embedding).availability();
|
|
60
|
+
if (availability.status === "available") {
|
|
61
|
+
return { ...report, runtimeStatus: "available" };
|
|
62
|
+
}
|
|
63
|
+
const guidance = [...report.guidance];
|
|
64
|
+
if (availability.status === "model_missing") {
|
|
65
|
+
guidance.push(`Install the configured embedding model '${config.embedding.model}' before indexing or semantic queries.`);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
guidance.push("Start the configured embedding provider or correct embedding.endpoint before retrying semantic operations.");
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
...report,
|
|
72
|
+
runtimeStatus: availability.status,
|
|
73
|
+
runtimeReason: availability.reason,
|
|
74
|
+
guidance
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
79
|
+
return {
|
|
80
|
+
...report,
|
|
81
|
+
runtimeStatus: "unavailable",
|
|
82
|
+
runtimeReason: reason,
|
|
83
|
+
guidance: [...report.guidance, "Correct the embedding provider configuration before retrying semantic operations."]
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function initialRuntimeStatus(config, providerSupported) {
|
|
88
|
+
if (!config.embedding.enabled) {
|
|
89
|
+
return "disabled";
|
|
90
|
+
}
|
|
91
|
+
if (!providerSupported) {
|
|
92
|
+
return "unavailable";
|
|
93
|
+
}
|
|
94
|
+
if (config.embedding.provider === LOCAL_EMBEDDING_PROVIDER) {
|
|
95
|
+
return "available";
|
|
96
|
+
}
|
|
97
|
+
return "unchecked";
|
|
52
98
|
}
|
|
53
99
|
function semanticState(input) {
|
|
54
100
|
if (!input.indexed) {
|
package/dist/types.d.ts
CHANGED
|
@@ -3,8 +3,9 @@ export type TrustTier = "authored" | "generated" | "validated" | "external" | "u
|
|
|
3
3
|
export type SearchQueryMode = "auto" | "keyword" | "semantic";
|
|
4
4
|
export type EntityKind = "symbol" | "api_route" | "error_code" | "config_key" | "file_path" | "command" | "package" | "concept" | "decision";
|
|
5
5
|
export type EdgeKind = "CONTAINS" | "DEFINES" | "REFERENCES" | "DEPENDS_ON" | "LINKS_TO" | "IMPLEMENTS" | "REFERENCES_SOURCE" | "SUPERSEDES" | "DEPRECATED_BY" | "SAME_AS" | "RELATED_TO" | "CONTRADICTS";
|
|
6
|
-
export declare const RESERVED_EDGE_KINDS: readonly ["SAME_AS", "
|
|
7
|
-
export
|
|
6
|
+
export declare const RESERVED_EDGE_KINDS: readonly ["SAME_AS", "CONTRADICTS"];
|
|
7
|
+
export declare const DERIVED_EDGE_KINDS: readonly ["RELATED_TO"];
|
|
8
|
+
export type Provenance = "frontmatter" | "markdown_link" | "wikilink" | "declared_section" | "heading" | "inline_code" | "code_block" | "regex" | "embedding_similarity";
|
|
8
9
|
export interface MDGraphConfig {
|
|
9
10
|
docs: {
|
|
10
11
|
include: string[];
|
|
@@ -30,6 +31,9 @@ export interface MDGraphConfig {
|
|
|
30
31
|
provider: string;
|
|
31
32
|
model: string;
|
|
32
33
|
dimensions: number;
|
|
34
|
+
endpoint?: string;
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
batchSize?: number;
|
|
33
37
|
};
|
|
34
38
|
}
|
|
35
39
|
export interface DocumentFrontmatter {
|
|
@@ -92,6 +96,7 @@ export interface ParsedDocument {
|
|
|
92
96
|
relativePath: string;
|
|
93
97
|
title: string;
|
|
94
98
|
hash: string;
|
|
99
|
+
updatedAt?: string;
|
|
95
100
|
frontmatter: DocumentFrontmatter;
|
|
96
101
|
frontmatterDiagnostics: FrontmatterDiagnostic[];
|
|
97
102
|
body: string;
|
package/dist/types.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { type IndexResult } from "../indexer.js";
|
|
2
|
+
import { type WatchHealthSnapshot } from "./watch-health.js";
|
|
2
3
|
export interface WatchProjectOptions {
|
|
3
4
|
debounceMs?: number;
|
|
4
5
|
semantic?: boolean;
|
|
6
|
+
usePolling?: boolean;
|
|
5
7
|
onIndexed?: (result: IndexResult) => void;
|
|
6
8
|
onError?: (error: Error) => void;
|
|
9
|
+
onHealthChanged?: (health: WatchHealthSnapshot) => void;
|
|
7
10
|
}
|
|
8
11
|
export interface WatchHandle {
|
|
9
12
|
close: () => Promise<void>;
|
|
13
|
+
getHealth: () => WatchHealthSnapshot;
|
|
10
14
|
}
|
|
11
15
|
export declare function watchProject(projectRoot: string, options?: WatchProjectOptions): Promise<WatchHandle>;
|
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
import chokidar from "chokidar";
|
|
2
|
+
import path from "node:path";
|
|
2
3
|
import { loadConfig } from "../config/load-config.js";
|
|
3
4
|
import { indexProject } from "../indexer.js";
|
|
4
5
|
import { resolveIgnorePatterns } from "../scanner/file-scanner.js";
|
|
6
|
+
import { WatchHealthTracker } from "./watch-health.js";
|
|
5
7
|
export async function watchProject(projectRoot, options = {}) {
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
+
const health = new WatchHealthTracker(options.usePolling ?? false, options.onHealthChanged);
|
|
9
|
+
let config;
|
|
10
|
+
let ignored;
|
|
11
|
+
try {
|
|
12
|
+
config = loadConfig(projectRoot);
|
|
13
|
+
ignored = await resolveIgnorePatterns(projectRoot, config);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
health.recordError(error, "startup");
|
|
17
|
+
notifyError(options.onError, error);
|
|
18
|
+
health.close();
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
8
21
|
const watchesMdx = config.index.parseMdx;
|
|
9
22
|
const debounceMs = options.debounceMs ?? 250;
|
|
10
23
|
let timer;
|
|
11
24
|
let running = false;
|
|
12
25
|
let queued = false;
|
|
13
26
|
let closed = false;
|
|
27
|
+
let ready = false;
|
|
14
28
|
let activeIndex;
|
|
15
29
|
const runIndex = async () => {
|
|
16
30
|
if (closed) {
|
|
@@ -25,9 +39,11 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
25
39
|
activeIndex = (async () => {
|
|
26
40
|
try {
|
|
27
41
|
const result = await indexProject(projectRoot, { semantic: options.semantic });
|
|
28
|
-
|
|
42
|
+
health.recordIndexSuccess();
|
|
43
|
+
notifyIndexed(options.onIndexed, result);
|
|
29
44
|
}
|
|
30
45
|
catch (error) {
|
|
46
|
+
health.recordError(error, "indexing");
|
|
31
47
|
notifyError(options.onError, error);
|
|
32
48
|
}
|
|
33
49
|
finally {
|
|
@@ -59,29 +75,49 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
59
75
|
scheduleIndex();
|
|
60
76
|
}
|
|
61
77
|
};
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
78
|
+
let watcher;
|
|
79
|
+
try {
|
|
80
|
+
watcher = chokidar.watch(".", {
|
|
81
|
+
cwd: projectRoot,
|
|
82
|
+
ignored: createWatchIgnoreMatcher(projectRoot, ignored, watchesMdx),
|
|
83
|
+
ignoreInitial: true,
|
|
84
|
+
persistent: true,
|
|
85
|
+
usePolling: options.usePolling ?? false,
|
|
86
|
+
awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
health.recordError(error, "startup");
|
|
91
|
+
notifyError(options.onError, error);
|
|
92
|
+
health.close();
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
69
95
|
watcher.on("add", scheduleIndexForMarkdown);
|
|
70
96
|
watcher.on("change", scheduleIndexForMarkdown);
|
|
71
97
|
watcher.on("unlink", scheduleIndexForMarkdown);
|
|
72
98
|
watcher.on("error", (error) => {
|
|
99
|
+
if (!ready) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
health.recordError(error, "runtime");
|
|
73
103
|
notifyError(options.onError, error);
|
|
74
104
|
});
|
|
75
105
|
try {
|
|
76
106
|
await waitForReady(watcher);
|
|
107
|
+
ready = true;
|
|
108
|
+
health.recordReady();
|
|
77
109
|
await runIndex();
|
|
78
110
|
}
|
|
79
111
|
catch (error) {
|
|
80
112
|
closed = true;
|
|
113
|
+
health.recordError(error, "startup");
|
|
114
|
+
notifyError(options.onError, error);
|
|
81
115
|
await watcher.close();
|
|
116
|
+
health.close();
|
|
82
117
|
throw error;
|
|
83
118
|
}
|
|
84
119
|
return {
|
|
120
|
+
getHealth: () => health.snapshot(),
|
|
85
121
|
close: async () => {
|
|
86
122
|
closed = true;
|
|
87
123
|
if (timer) {
|
|
@@ -95,10 +131,39 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
95
131
|
}
|
|
96
132
|
finally {
|
|
97
133
|
await watcher.close();
|
|
134
|
+
health.close();
|
|
98
135
|
}
|
|
99
136
|
}
|
|
100
137
|
};
|
|
101
138
|
}
|
|
139
|
+
function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
|
|
140
|
+
const root = path.resolve(projectRoot);
|
|
141
|
+
return (candidatePath, stats) => {
|
|
142
|
+
const absolutePath = path.isAbsolute(candidatePath) ? candidatePath : path.resolve(root, candidatePath);
|
|
143
|
+
const relativePath = path.relative(root, absolutePath);
|
|
144
|
+
if (!relativePath || relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
const normalizedPath = relativePath.split(path.sep).join("/");
|
|
148
|
+
if (patterns.some((pattern) => (path.matchesGlob(normalizedPath, pattern)
|
|
149
|
+
|| path.matchesGlob(`${normalizedPath}/`, pattern)))) {
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
if (stats && !stats.isDirectory()) {
|
|
153
|
+
return !normalizedPath.toLowerCase().endsWith(".md")
|
|
154
|
+
&& !(watchesMdx && normalizedPath.toLowerCase().endsWith(".mdx"));
|
|
155
|
+
}
|
|
156
|
+
return false;
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function notifyIndexed(onIndexed, result) {
|
|
160
|
+
try {
|
|
161
|
+
onIndexed?.(result);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// User callbacks must not break watcher cleanup or future indexing.
|
|
165
|
+
}
|
|
166
|
+
}
|
|
102
167
|
function notifyError(onError, error) {
|
|
103
168
|
try {
|
|
104
169
|
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type WatchHealthState = "starting" | "healthy" | "degraded" | "failed";
|
|
2
|
+
export type WatchFailurePhase = "startup" | "runtime" | "indexing";
|
|
3
|
+
export type WatchFailureCode = "ENOSPC" | "EMFILE" | "EACCES" | "INDEX_ERROR" | "UNKNOWN";
|
|
4
|
+
export interface WatchHealthError {
|
|
5
|
+
code: WatchFailureCode;
|
|
6
|
+
originalCode?: string;
|
|
7
|
+
phase: WatchFailurePhase;
|
|
8
|
+
message: string;
|
|
9
|
+
occurredAt: string;
|
|
10
|
+
fatal: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface WatchHealthSnapshot {
|
|
13
|
+
state: WatchHealthState;
|
|
14
|
+
startedAt: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
lastSuccessfulIndexAt?: string;
|
|
17
|
+
lastError?: WatchHealthError;
|
|
18
|
+
consecutiveIndexFailures: number;
|
|
19
|
+
coverageReliable: boolean;
|
|
20
|
+
polling: boolean;
|
|
21
|
+
closed: boolean;
|
|
22
|
+
}
|
|
23
|
+
export declare class WatchHealthTracker {
|
|
24
|
+
private readonly onChanged?;
|
|
25
|
+
private snapshotValue;
|
|
26
|
+
constructor(polling?: boolean, onChanged?: ((health: WatchHealthSnapshot) => void) | undefined, startedAt?: string);
|
|
27
|
+
snapshot(): WatchHealthSnapshot;
|
|
28
|
+
recordReady(at?: string): void;
|
|
29
|
+
recordIndexSuccess(at?: string): void;
|
|
30
|
+
recordError(error: unknown, phase: WatchFailurePhase, at?: string): WatchHealthError;
|
|
31
|
+
close(at?: string): void;
|
|
32
|
+
private update;
|
|
33
|
+
}
|
|
34
|
+
export declare function normalizeWatchError(error: unknown, phase: WatchFailurePhase, occurredAt?: string): WatchHealthError;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export class WatchHealthTracker {
|
|
2
|
+
onChanged;
|
|
3
|
+
snapshotValue;
|
|
4
|
+
constructor(polling = false, onChanged, startedAt = new Date().toISOString()) {
|
|
5
|
+
this.onChanged = onChanged;
|
|
6
|
+
this.snapshotValue = {
|
|
7
|
+
state: "starting",
|
|
8
|
+
startedAt,
|
|
9
|
+
updatedAt: startedAt,
|
|
10
|
+
consecutiveIndexFailures: 0,
|
|
11
|
+
coverageReliable: true,
|
|
12
|
+
polling,
|
|
13
|
+
closed: false
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
snapshot() {
|
|
17
|
+
return structuredClone(this.snapshotValue);
|
|
18
|
+
}
|
|
19
|
+
recordReady(at = new Date().toISOString()) {
|
|
20
|
+
this.update({ state: "healthy", updatedAt: at });
|
|
21
|
+
}
|
|
22
|
+
recordIndexSuccess(at = new Date().toISOString()) {
|
|
23
|
+
this.update({
|
|
24
|
+
state: this.snapshotValue.coverageReliable ? "healthy" : "degraded",
|
|
25
|
+
updatedAt: at,
|
|
26
|
+
lastSuccessfulIndexAt: at,
|
|
27
|
+
consecutiveIndexFailures: 0
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
recordError(error, phase, at = new Date().toISOString()) {
|
|
31
|
+
const normalized = normalizeWatchError(error, phase, at);
|
|
32
|
+
const coverageReliable = phase === "runtime" ? false : this.snapshotValue.coverageReliable;
|
|
33
|
+
this.update({
|
|
34
|
+
state: normalized.fatal ? "failed" : "degraded",
|
|
35
|
+
updatedAt: at,
|
|
36
|
+
lastError: normalized,
|
|
37
|
+
coverageReliable,
|
|
38
|
+
consecutiveIndexFailures: phase === "indexing" ? this.snapshotValue.consecutiveIndexFailures + 1 : this.snapshotValue.consecutiveIndexFailures
|
|
39
|
+
});
|
|
40
|
+
return normalized;
|
|
41
|
+
}
|
|
42
|
+
close(at = new Date().toISOString()) {
|
|
43
|
+
this.update({ updatedAt: at, closed: true });
|
|
44
|
+
}
|
|
45
|
+
update(changes) {
|
|
46
|
+
this.snapshotValue = { ...this.snapshotValue, ...changes };
|
|
47
|
+
try {
|
|
48
|
+
this.onChanged?.(this.snapshot());
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// Health observers must not break watcher cleanup or indexing.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function normalizeWatchError(error, phase, occurredAt = new Date().toISOString()) {
|
|
56
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
57
|
+
const rawCode = errorCode(error);
|
|
58
|
+
const code = phase === "indexing"
|
|
59
|
+
? "INDEX_ERROR"
|
|
60
|
+
: rawCode === "ENOSPC" || rawCode === "EMFILE" || rawCode === "EACCES" ? rawCode : "UNKNOWN";
|
|
61
|
+
return {
|
|
62
|
+
code,
|
|
63
|
+
originalCode: phase === "indexing" && rawCode ? rawCode : undefined,
|
|
64
|
+
phase,
|
|
65
|
+
message,
|
|
66
|
+
occurredAt,
|
|
67
|
+
fatal: phase === "startup"
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function errorCode(error) {
|
|
71
|
+
if (!error || typeof error !== "object" || !("code" in error)) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
return typeof error.code === "string" && error.code ? error.code : undefined;
|
|
75
|
+
}
|
|
@@ -8,7 +8,7 @@ source_refs:
|
|
|
8
8
|
|
|
9
9
|
# MDGraph Agent Integration
|
|
10
10
|
|
|
11
|
-
This guide is the shared
|
|
11
|
+
This guide is the shared integration contract for coding agents. Host-specific setup should stay thin: start the same MCP server, expose the same five tools, and teach the agent when to query MDGraph before reading Markdown files directly.
|
|
12
12
|
|
|
13
13
|
For active documentation editing sessions, use `serve --mcp`; the same MCP process keeps the local graph fresh by default.
|
|
14
14
|
|
package/docs/EN/Architecture.md
CHANGED
|
@@ -6,6 +6,9 @@ implements:
|
|
|
6
6
|
source_refs:
|
|
7
7
|
- src/db/schema.sql
|
|
8
8
|
- src/types.ts
|
|
9
|
+
- src/semantic/provider.ts
|
|
10
|
+
- src/semantic/provider-registry.ts
|
|
11
|
+
- src/semantic/ollama-provider.ts
|
|
9
12
|
---
|
|
10
13
|
|
|
11
14
|
# MDGraph Architecture
|
|
@@ -23,16 +26,16 @@ MDGraph uses this implemented pipeline: scanner -> parser -> extractor/resolver
|
|
|
23
26
|
| Extraction | `src/extraction/*` | Converts parsed documents into graph records and deterministic entity/edge signals. |
|
|
24
27
|
| Resolution | `src/resolution/link-resolver.ts` | Resolves Markdown and WikiLink targets to indexed documents or sections. |
|
|
25
28
|
| Storage | `src/db/*` | SQLite connection, schema, record replacement, incremental updates, graph queries, and storage diagnostics. |
|
|
26
|
-
| Query | `src/query/*` | Search ranking, context packing, and
|
|
29
|
+
| Query | `src/query/*` | Search ranking, context packing, graph trace, and the experimental structured-query tokenizer/AST/executor. |
|
|
27
30
|
| Evaluation | `src/evaluation/*` | Retrieval evaluation cases, expected records, and lightweight metrics for search/context/trace quality. |
|
|
28
31
|
| Benchmark | `src/benchmark/*` | Structured with/without-MDGraph agent run record parsing and paired delta aggregation. |
|
|
29
32
|
| Bundle | `src/bundle/*` | Private directory graph bundle creation and verification using schema/source/config/document hashes. |
|
|
30
33
|
| Reporting | `src/reporting/*` | CI-friendly graph workflow reports that aggregate counts, storage, doctor, eval, bundle, diff, and benchmark summaries. |
|
|
31
34
|
| Diff | `src/diff/*` | Git base-ref documentation graph diff and PR impact summary generation. |
|
|
32
35
|
| Export/Import | `src/export/*` | Deterministic GraphJSON, Mermaid, Markdown/docs-site, and read-only source bridge adapters. |
|
|
33
|
-
| Semantic | `src/semantic/*` |
|
|
36
|
+
| Semantic | `src/semantic/*` | Pluggable embedding providers, the compatibility `local-hash` implementation, opt-in Ollama integration, Float32 vector codec, provider diagnostics, and cosine scoring. |
|
|
34
37
|
| MCP | `src/mcp/*` | Newline-delimited JSON-RPC MCP server and tool handlers. |
|
|
35
|
-
| Watch | `src/watcher/file-watcher.ts` | Debounced incremental reindexing via chokidar. |
|
|
38
|
+
| Watch | `src/watcher/file-watcher.ts`, `src/watcher/watch-health.ts` | Debounced incremental reindexing via chokidar plus persistent in-process health classification. |
|
|
36
39
|
| Analysis | `src/analysis/doctor.ts` | Documentation health and governance report. |
|
|
37
40
|
|
|
38
41
|
## Public Contract Boundary
|
|
@@ -60,11 +63,26 @@ Primary records:
|
|
|
60
63
|
|
|
61
64
|
1. `scanMarkdownFiles` selects candidate Markdown files from config.
|
|
62
65
|
2. `parseMarkdownDocument` reads front matter and Markdown structure.
|
|
63
|
-
3. `buildGraphRecords` creates documents, sections, entities, source refs, chunks,
|
|
64
|
-
4. `
|
|
65
|
-
5. `
|
|
66
|
+
3. `buildGraphRecords` synchronously creates deterministic documents, sections, entities, source refs, chunks, and edges.
|
|
67
|
+
4. When embedding is enabled, `indexProject` resolves an `EmbeddingProvider` and asynchronously embeds all chunks for a new/provider-changed index or only changed chunks for a matching incremental index.
|
|
68
|
+
5. `GraphRepository.replaceAll` writes a full rebuild, or `replaceDocuments` updates changed/deleted documents and their vectors.
|
|
69
|
+
6. `indexProject` compares stored hashes and vector profile coverage to choose full or incremental mode.
|
|
66
70
|
|
|
67
|
-
Incremental mode deletes document-derived records for changed and removed files, removes their FTS terms, reinserts changed records, and prunes unreferenced global entities/source refs after cleanup. Full rebuilds optimize and vacuum the SQLite database so old FTS pages and deleted rows do not keep inflating the on-disk file.
|
|
71
|
+
Embedding completes before either repository write begins. A provider error therefore leaves the prior graph intact instead of committing partial vector coverage. Incremental mode deletes document-derived records for changed and removed files, removes their FTS terms, reinserts changed records, and prunes unreferenced global entities/source refs after cleanup. Full rebuilds optimize and vacuum the SQLite database so old FTS pages and deleted rows do not keep inflating the on-disk file.
|
|
72
|
+
|
|
73
|
+
## Derived Relationship Flow
|
|
74
|
+
|
|
75
|
+
`relationships derive` is an explicit post-index workflow; it is not part of ordinary indexing or watch mode. It requires a clean doctor content-hash/ID freshness audit with no parse failures, a configured `semantic-model` provider, and complete vector coverage for the current provider/model/dimensions. `local-hash` is rejected. The implementation samples bounded document chunks, uses normalized document centroids for candidate filtering, requires multiple independent high-similarity section pairs, and keeps only reciprocal top-K neighbors.
|
|
76
|
+
|
|
77
|
+
Accepted pairs become two symmetric, low-weight `RELATED_TO` edges with `embedding_similarity` provenance and metadata containing provider/model identity, algorithm and gate versions, thresholds, evidence section IDs, and generation time. Replacement is atomic. Incremental indexing removes derived edges connected to changed or deleted documents, while a full rebuild removes the optional layer entirely. See [Structured Query and Relationships](Structured_Query_and_Relationships.md#derived-related-document-relationships) for the workflow, safety budgets, and lifecycle.
|
|
78
|
+
|
|
79
|
+
Derived edges can contribute to graph retrieval, trace, and structured edge predicates. They are excluded from doctor orphan/weak-link authoritative-link counts so inference cannot conceal missing maintained links.
|
|
80
|
+
|
|
81
|
+
## Entity Extraction
|
|
82
|
+
|
|
83
|
+
`extractEntities` is deterministic and source-aware. Explicit front matter and `Defines` sections create definitions. Ordinary prose emits only high-structure references such as API routes, error codes, and shaped config keys; broad PascalCase words are not promoted. Standalone inline code may identify a complete Latin or CJK symbol, while fenced code limits bare symbols to declaration and type-reference contexts. Unicode-aware patterns cover CJK API paths, segmented config keys, and function identifiers. Route boundaries prevent a file path from also producing a truncated route.
|
|
84
|
+
|
|
85
|
+
`entities.stopEntities` suppresses inferred references of every entity kind, while author-declared definitions remain authoritative. This layer is an interpretable heuristic, not general-purpose NER or a source-language AST. Its signal policy and limits are documented in [Retrieval and Context](Retrieval_and_Context.md#deterministic-entity-extraction).
|
|
68
86
|
|
|
69
87
|
## Storage Diagnostics
|
|
70
88
|
|
|
@@ -102,34 +120,39 @@ The diff report includes Markdown document additions, modifications, deletions,
|
|
|
102
120
|
|
|
103
121
|
- FTS5 chunk hits, including lightweight CJK n-gram matches for continuous Chinese/Japanese/Korean text.
|
|
104
122
|
- Exact entity matches.
|
|
105
|
-
- Optional
|
|
123
|
+
- Optional embedding vector matches.
|
|
106
124
|
- Graph neighbors around matching entities.
|
|
107
125
|
|
|
108
126
|
When the same document or section is reached by multiple paths, search applies reciprocal rank fusion (RRF) across definition, FTS, and optional semantic channels, then keeps the highest base score while merging the main reasons and matched entities so provenance is not lost. Each fused result keeps an explainable `RRF fusion (...)` reason.
|
|
109
127
|
|
|
110
|
-
`buildContext`
|
|
128
|
+
The synchronous `searchGraph`, `buildContext`, and `evaluateRetrieval` APIs retain their 1.0 behavior and can execute `local-hash` in process. Their async counterparts resolve external providers such as Ollama and are used by CLI and MCP query paths. Provider unavailability, timeouts, invalid responses, missing models, and missing vector coverage fall back to keyword/entity/graph retrieval with an additive `semanticDiagnostic`; CLI text and non-explain JSON commands also write the diagnostic to stderr.
|
|
129
|
+
|
|
130
|
+
`buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path. The compatibility default orders candidates by document round-robin. Opt-in `mmr` maximizes query relevance minus redundancy, uses stored configured-provider vectors when both candidates have them, falls back to deterministic Unicode-token Jaccard otherwise, and prunes same-document near duplicates while preserving a first candidate from each document.
|
|
131
|
+
|
|
132
|
+
Every context result includes additive packing metadata. When requested through `context --debug`, context building also reports seed nodes, visited nodes, expanded edges, skipped expansion reasons, candidate counts, strategy/similarity selection, per-item query relevance, redundancy penalty and MMR score, redundancy pruning, and budget truncation counts. These diagnostics are not graph facts; they exist to explain context packing and evaluate retrieval quality.
|
|
111
133
|
|
|
112
|
-
|
|
134
|
+
The experimental structured-query path is separate from natural-language search. `structured-query.ts` tokenizes bounded input and validates a typed boolean AST. `GraphRepository` compiles document, tag, date, and outgoing-edge predicates from closed field/operator sets into parameterized SQLite operations. `structured-query-executor.ts` uses that direct SQL path unless the AST contains a doctor-derived health predicate; health queries combine parameterized atomic document-id sets with a fresh doctor report and evaluate the original boolean tree. Source file mtime is captured in the existing `documents.updated_at` column during indexing so date governance queries require no schema migration.
|
|
113
135
|
|
|
114
136
|
`traceNodes` performs bounded graph traversal between resolved nodes and returns each step with edge kind, provenance, and confidence.
|
|
115
137
|
|
|
116
|
-
`evaluateRetrieval`
|
|
138
|
+
`evaluateRetrieval` and `evaluateRetrievalAsync` run the repository-owned alpha or CJK evaluation cases against an indexed project. They reuse the corresponding search/context path plus `traceNodes`, then report expected-document recall, expected-section recall, context precision, trace success, latency, returned character budget, context diversity, reason coverage, RRF channels, query mode, optional semantic reranker status, and async provider diagnostics. The evaluation output is a measurement aid, not a learned ranking model and not a replacement for focused regression tests.
|
|
117
139
|
|
|
118
140
|
`generateBenchmarkReport` consumes structured `AgentRunRecord` JSON only. It pairs one `with_mdgraph` and one `without_mdgraph` record by `questionId`, reports incomplete or duplicate pairs as skipped, and calculates deltas for file reads, searches, tool calls, MDGraph calls, character/token budgets, latency, raw-file fallback, and citation correctness. It does not parse transcripts, invoke models, or host agent runs.
|
|
119
141
|
|
|
120
142
|
## MCP Boundary
|
|
121
143
|
|
|
122
|
-
The MCP server intentionally exposes only five tools. Tool output is text-first and JSON-compatible so agents can use it without needing to inspect the SQLite database or read raw files first. The server is project-bound: initialize roots and tool `projectPath` values must stay inside the served root.
|
|
144
|
+
The MCP server intentionally exposes only five tools. Search and context dispatch through the async provider-aware handlers, while node, trace, and status retain their synchronous behavior. Tool output is text-first and JSON-compatible so agents can use it without needing to inspect the SQLite database or read raw files first. A semantic fallback adds a text banner and structured diagnostic without turning a usable lexical/graph result into an MCP error. The server is project-bound: initialize roots and tool `projectPath` values must stay inside the served root.
|
|
123
145
|
|
|
124
146
|
## Current Tradeoffs
|
|
125
147
|
|
|
126
|
-
-
|
|
127
|
-
-
|
|
148
|
+
- `local-hash` remains a deterministic lexical feature hash for compatibility, not a language-model embedding. Ollama is the first opt-in `semantic-model` provider and requires a separately running local service/model. Unsupported or unavailable providers degrade to FTS5 and graph search; `semantic status` reports capability, runtime availability, vector coverage, storage format, and reindex guidance.
|
|
149
|
+
- Structured `query` is experimental and covers documented stored fields, tags, outgoing edges, and selected doctor health classes. Arbitrary front-matter keys, incoming-edge predicates, aggregations, joins, and an MCP structured filter remain outside the current implementation.
|
|
150
|
+
- Watch mode updates SQLite on file changes and retains `starting | healthy | degraded | failed` health, the last successful index, the last error, and coverage reliability. Startup registration errors are fatal; indexing errors can recover after a later successful index; runtime resource failures remain degraded until restart. Integrated MCP exposes the snapshot through `mdgraph_status`. Native events remain the default, while `watch --poll` and `serve --mcp --watch-poll` are explicit higher-cost fallbacks.
|
|
128
151
|
- Doctor checks are rule-based warnings. They first compare current files with indexed document hashes and IDs; stale indexes produce a read-only freshness diagnostic instead of mixed-time health conclusions.
|
|
129
152
|
- `doctor --changed` and `doctor --since <ref>` are Git-scoped views over the same health model; they report scope metadata, scoped graph issues, directly related one-hop graph documents, deleted-document warnings, and freshness diagnostics.
|
|
130
153
|
- Storage diagnostics are exposed through `status --storage` and reused by doctor for storage health summaries; they are not graph facts and do not expand the MCP tool surface.
|
|
131
154
|
- Private bundle artifacts are local workflow artifacts, not public exports. Public-safe sanitization and zip packaging are outside the current implementation.
|
|
132
155
|
- Benchmark reports are aggregate-only measurements from explicit structured records; full transcripts, hosted analytics, and agent runtime capture stay outside MDGraph.
|
|
133
156
|
- Interoperability adapters are read-oriented. GraphJSON verify, Mermaid/Markdown/docs-site exports, and source bridge reports do not merge external graphs into the main SQLite index.
|
|
134
|
-
- `
|
|
135
|
-
- The current implementation favors a compact
|
|
157
|
+
- `RELATED_TO` is an experimental derived edge emitted only by explicit provider-gated execution; it is never emitted by ordinary deterministic indexing. `SAME_AS` and `CONTRADICTS` remain reserved, and contradiction-like signals continue to be reported by `doctor` rather than inserted as graph edges.
|
|
158
|
+
- The current implementation favors a compact, deterministic core over broad Markdown/MDX dialect support.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# MDGraph Evaluation Questions
|
|
2
2
|
|
|
3
|
-
These questions
|
|
3
|
+
These questions provide a reusable engineering smoke set for a realistic project documentation corpus. They test whether MDGraph returns the right documents, sections, entities, graph evidence, and context rather than treating a single ranking score as sufficient evidence.
|
|
4
4
|
|
|
5
5
|
The built-in CLI entry is:
|
|
6
6
|
|
|
@@ -11,7 +11,23 @@ mdgraph eval --query-set cjk --path /path/to/project --json
|
|
|
11
11
|
mdgraph eval --query-mode semantic --json
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
`mdgraph eval` runs the repository-owned alpha query set by default and reports pass/fail plus lightweight retrieval metrics. It also reports
|
|
14
|
+
`mdgraph eval` runs the repository-owned `alpha` query set by default and reports pass/fail plus lightweight retrieval metrics. It also reports query mode, RRF channels, compatibility context packing, and optional semantic-provider status. `--query-set cjk` selects a small Chinese/Japanese retrieval baseline covered by lightweight CJK n-gram preprocessing. These are deterministic engineering checks, not a completed IR benchmark or real-agent A/B benchmark.
|
|
15
|
+
|
|
16
|
+
## Repository Regression Suites
|
|
17
|
+
|
|
18
|
+
Maintainers use focused, non-public suites in addition to `mdgraph eval`. Their names describe the capability they protect. None adds a value to the frozen `eval --query-set alpha | cjk` enum or writes the repository's `.mdgraph` index.
|
|
19
|
+
|
|
20
|
+
| Command | Capability protected | Recorded result / gate |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| `npm run baseline:historical` | Historical lexical-hash, entity, context, and watch-failure comparison snapshot | Keyword synonym Recall@5 `0.0000`; `local-hash` `0.5000`; historical entity precision/recall `0.5000 / 1.0000`; round-robin average pairwise Jaccard `0.3808` with three near-duplicate pairs. These values are intentionally immutable historical evidence. |
|
|
23
|
+
| `npm run baseline:entity-extraction` | Source-aware Latin/CJK entity extraction | Precision `1.0000`, recall `1.0000`, CJK recall `1.0000`, and zero known-noise leakage; gates are `>= 0.90`, `>= 0.80`, `>= 0.80`, and zero. |
|
|
24
|
+
| `npm run baseline:context-packing` | Opt-in true-MMR context packing | Expected-document recall remains `1.0000`; average pairwise Jaccard falls from `0.3808` to `0.1576` and near-duplicate pairs from three to zero, a `58.61%` redundancy reduction. |
|
|
25
|
+
| `npm run baseline:structured-query` | Structured-query correctness and safety | Four of four annotated governance queries correct; parameterized repository predicates and SQL-injection isolation pass. |
|
|
26
|
+
| `npm run baseline:related-documents` | Provider-gated related-document derivation | Precision `1.0000`, recall `1.0000`, complete provenance, and deterministic replacement; gates require precision `>= 0.90`, recall `>= 0.80`, complete provenance, and stable replacement. |
|
|
27
|
+
|
|
28
|
+
The provider integration fixture also maps four no-overlap semantic cases through a deterministic fake Ollama endpoint and reaches Recall@5 `1.0000`. This validates batching, vector persistence, async routing, RRF participation, diagnostics, and provider attribution; it does not predict the quality of an arbitrary live model.
|
|
29
|
+
|
|
30
|
+
Watcher tests cover startup/runtime `ENOSPC`, runtime `EMFILE`, startup `EACCES`, indexing failure, recovery, persistent in-process health, and explicit polling. See [Retrieval and Context](Retrieval_and_Context.md), [Operations](Operations.md), and [Structured Query and Relationships](Structured_Query_and_Relationships.md) for the user-facing behavior behind these suites.
|
|
15
31
|
|
|
16
32
|
1. Why does a specific error code affect a specific user flow?
|
|
17
33
|
2. Which older decisions does a given design document depend on?
|
|
@@ -45,7 +61,7 @@ The machine-readable expected records live in `src/evaluation/retrieval-eval.ts`
|
|
|
45
61
|
|
|
46
62
|
## CJK Expected Records
|
|
47
63
|
|
|
48
|
-
The `cjk` query set is
|
|
64
|
+
The `cjk` query set is the built-in retrieval baseline for Chinese and Japanese Markdown. It uses expected records from the repository test fixture `createCjkFixtureDocs`, including Chinese design/API/runbook/spec documents and a Japanese design document. Its cases cover:
|
|
49
65
|
|
|
50
66
|
- Chinese spaced keyword queries such as `登录流程 缓存超时 认证重试`.
|
|
51
67
|
- Continuous Chinese natural-language phrasing such as `缓存超时影响登录流程的处理`, covered by the lightweight CJK n-gram preprocessing baseline.
|
|
@@ -63,6 +79,6 @@ For each question, compare agent behavior with and without MDGraph attached:
|
|
|
63
79
|
- Whether the context returned by MDGraph is sufficient without follow-up file inspection.
|
|
64
80
|
- Time and tool-call count for the full agent run.
|
|
65
81
|
- `mdgraph eval` metrics: top-K document recall, expected-section recall, context precision, trace success, latency, returned character count, budget fit, fanout, context diversity, reason coverage, and ranking reason coverage.
|
|
66
|
-
- `mdgraph eval` ranking report: query mode, RRF search fusion channels,
|
|
82
|
+
- `mdgraph eval` ranking report: query mode, RRF search fusion channels, compatibility context packing strategy, optional reranker status, and semantic-active case count. Use the focused context regression suite to compare opt-in true MMR against that frozen default.
|
|
67
83
|
|
|
68
|
-
Use `mdgraph report --benchmark benchmark-runs.json --json` for
|
|
84
|
+
Use `mdgraph report --benchmark benchmark-runs.json --json` for A/B reporting on these questions. It consumes structured run records and reports aggregate deltas; full transcripts should remain outside public docs.
|