@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.
Files changed (81) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README-ZH.md +54 -2
  3. package/README.md +73 -21
  4. package/dist/bin/mdgraph.js +136 -19
  5. package/dist/config/limits.d.ts +2 -0
  6. package/dist/config/limits.js +3 -1
  7. package/dist/config/load-config.js +8 -2
  8. package/dist/db/repositories.d.ts +27 -0
  9. package/dist/db/repositories.js +310 -6
  10. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  11. package/dist/evaluation/context-packing-evaluation.js +134 -0
  12. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  13. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  14. package/dist/evaluation/historical-baseline.d.ts +70 -0
  15. package/dist/evaluation/historical-baseline.js +278 -0
  16. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  17. package/dist/evaluation/related-documents-evaluation.js +163 -0
  18. package/dist/evaluation/retrieval-eval.d.ts +14 -5
  19. package/dist/evaluation/retrieval-eval.js +44 -6
  20. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  21. package/dist/evaluation/structured-query-evaluation.js +156 -0
  22. package/dist/extraction/entity-extractor.js +42 -22
  23. package/dist/extraction/graph-builder.js +2 -18
  24. package/dist/index.d.ts +17 -4
  25. package/dist/index.js +9 -4
  26. package/dist/indexer.js +20 -2
  27. package/dist/mcp/server.d.ts +4 -0
  28. package/dist/mcp/server.js +16 -7
  29. package/dist/mcp/tools.d.ts +5 -1
  30. package/dist/mcp/tools.js +93 -9
  31. package/dist/parser/markdown-parser.js +2 -0
  32. package/dist/query/context-builder.d.ts +31 -2
  33. package/dist/query/context-builder.js +162 -12
  34. package/dist/query/search.d.ts +5 -1
  35. package/dist/query/search.js +77 -13
  36. package/dist/query/structured-query-executor.d.ts +28 -0
  37. package/dist/query/structured-query-executor.js +138 -0
  38. package/dist/query/structured-query.d.ts +50 -0
  39. package/dist/query/structured-query.js +390 -0
  40. package/dist/relationships/derive-related.d.ts +86 -0
  41. package/dist/relationships/derive-related.js +322 -0
  42. package/dist/reporting/report.js +2 -2
  43. package/dist/semantic/embed-chunks.d.ts +2 -0
  44. package/dist/semantic/embed-chunks.js +31 -0
  45. package/dist/semantic/ollama-provider.d.ts +6 -0
  46. package/dist/semantic/ollama-provider.js +131 -0
  47. package/dist/semantic/provider-registry.d.ts +8 -0
  48. package/dist/semantic/provider-registry.js +66 -0
  49. package/dist/semantic/provider.d.ts +35 -0
  50. package/dist/semantic/provider.js +29 -0
  51. package/dist/semantic/status.d.ts +6 -1
  52. package/dist/semantic/status.js +49 -3
  53. package/dist/types.d.ts +7 -2
  54. package/dist/types.js +2 -1
  55. package/dist/watcher/file-watcher.d.ts +4 -0
  56. package/dist/watcher/file-watcher.js +75 -10
  57. package/dist/watcher/watch-health.d.ts +34 -0
  58. package/dist/watcher/watch-health.js +75 -0
  59. package/docs/EN/Agent_Integration.md +1 -1
  60. package/docs/EN/Architecture.md +39 -16
  61. package/docs/EN/Evaluation_Questions.md +21 -5
  62. package/docs/EN/Operations.md +91 -0
  63. package/docs/EN/Output_Contracts.md +41 -7
  64. package/docs/EN/Public_Contracts.md +23 -16
  65. package/docs/EN/Public_Contracts_1.0.md +28 -18
  66. package/docs/EN/README.md +23 -0
  67. package/docs/EN/Release_Checklist.md +26 -13
  68. package/docs/EN/Retrieval_and_Context.md +112 -0
  69. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  70. package/docs/ZH/Agent_Integration.md +1 -1
  71. package/docs/ZH/Architecture.md +39 -19
  72. package/docs/ZH/Evaluation_Questions.md +22 -6
  73. package/docs/ZH/Operations.md +91 -0
  74. package/docs/ZH/Output_Contracts.md +41 -7
  75. package/docs/ZH/Public_Contracts.md +22 -15
  76. package/docs/ZH/Public_Contracts_1.0.md +27 -17
  77. package/docs/ZH/README.md +23 -0
  78. package/docs/ZH/Release_Checklist.md +26 -13
  79. package/docs/ZH/Retrieval_and_Context.md +112 -0
  80. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  81. package/package.json +44 -18
@@ -0,0 +1,118 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+ import { DEFAULT_CONFIG } from "../config/load-config.js";
6
+ import { extractEntities } from "../extraction/entity-extractor.js";
7
+ import { parseMarkdownDocument } from "../parser/markdown-parser.js";
8
+ import { normalizeEntityName } from "../utils/text.js";
9
+ export const ENTITY_EXTRACTION_EVALUATION_VERSION = 1;
10
+ export const ENTITY_EXTRACTION_GATES = {
11
+ minimumPrecision: 0.9,
12
+ minimumRecall: 0.8,
13
+ minimumCjkRecall: 0.8
14
+ };
15
+ export const ENTITY_EXTRACTION_EXPECTED = [
16
+ { name: "AuthCoordinator", kind: "symbol", language: "latin" },
17
+ { name: "AuthService", kind: "symbol", language: "latin" },
18
+ { name: "GET /api/auth/login", kind: "api_route", language: "latin" },
19
+ { name: "JWT_SECRET", kind: "config_key", language: "latin" },
20
+ { name: "src/auth/session.ts", kind: "file_path", language: "latin" },
21
+ { name: "RedisTimeoutError", kind: "error_code", language: "latin" },
22
+ { name: "loadSession()", kind: "symbol", language: "latin" },
23
+ { name: "SessionRepository", kind: "symbol", language: "latin" },
24
+ { name: "AuthAdapter", kind: "symbol", language: "latin" },
25
+ { name: "rotateToken()", kind: "symbol", language: "latin" },
26
+ { name: "登录服务", kind: "symbol", language: "cjk" },
27
+ { name: "POST /接口/登录", kind: "api_route", language: "cjk" },
28
+ { name: "登录.认证.重试", kind: "config_key", language: "cjk" },
29
+ { name: "验证登录()", kind: "symbol", language: "cjk" },
30
+ { name: "認証を確認()", kind: "symbol", language: "cjk" },
31
+ { name: "验证会话()", kind: "symbol", language: "cjk" }
32
+ ];
33
+ export const ENTITY_EXTRACTION_NOISE = [
34
+ "/auth/session.ts",
35
+ "Design",
36
+ "Do",
37
+ "Fall",
38
+ "GET",
39
+ "Include",
40
+ "Note",
41
+ "Prefer",
42
+ "Reason",
43
+ "Should",
44
+ "Start",
45
+ "The",
46
+ "Use",
47
+ "When"
48
+ ];
49
+ export function runEntityExtractionEvaluation() {
50
+ const started = performance.now();
51
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mdgraph-entity-extraction-"));
52
+ try {
53
+ const target = path.join(root, "docs", "entity-evaluation.md");
54
+ fs.mkdirSync(path.dirname(target), { recursive: true });
55
+ fs.writeFileSync(target, evaluationDocument(), "utf8");
56
+ const entities = extractEntities(parseMarkdownDocument(root, target), DEFAULT_CONFIG);
57
+ const extracted = uniqueEntities(entities.map(({ name, kind }) => ({ name, kind })));
58
+ const expectedByKey = new Map(ENTITY_EXTRACTION_EXPECTED.map((entity) => [entityKey(entity), entity]));
59
+ const extractedByKey = new Map(extracted.map((entity) => [entityKey(entity), entity]));
60
+ const truePositives = extracted.filter((entity) => expectedByKey.has(entityKey(entity)));
61
+ const falsePositives = extracted.filter((entity) => !expectedByKey.has(entityKey(entity)));
62
+ const falseNegatives = ENTITY_EXTRACTION_EXPECTED.filter((entity) => !extractedByKey.has(entityKey(entity)));
63
+ const extractedNames = new Set(extracted.map((entity) => normalizeEntityName(entity.name)));
64
+ const cjkExpected = ENTITY_EXTRACTION_EXPECTED.filter((entity) => entity.language === "cjk");
65
+ return {
66
+ evaluationVersion: ENTITY_EXTRACTION_EVALUATION_VERSION,
67
+ expected: ENTITY_EXTRACTION_EXPECTED,
68
+ extracted,
69
+ truePositives,
70
+ falsePositives,
71
+ falseNegatives,
72
+ expectedNoise: [...ENTITY_EXTRACTION_NOISE],
73
+ leakedNoise: ENTITY_EXTRACTION_NOISE.filter((name) => extractedNames.has(normalizeEntityName(name))),
74
+ precision: ratio(truePositives.length, extracted.length),
75
+ recall: ratio(truePositives.length, ENTITY_EXTRACTION_EXPECTED.length),
76
+ cjkRecall: ratio(cjkExpected.filter((entity) => extractedByKey.has(entityKey(entity))).length, cjkExpected.length),
77
+ elapsedMs: Number((performance.now() - started).toFixed(2))
78
+ };
79
+ }
80
+ finally {
81
+ fs.rmSync(root, { recursive: true, force: true });
82
+ }
83
+ }
84
+ function evaluationDocument() {
85
+ return [
86
+ "---",
87
+ "title: Entity Extraction Evaluation",
88
+ "defines: [AuthCoordinator, 登录服务]",
89
+ "---",
90
+ "# Entity Extraction Evaluation",
91
+ "",
92
+ "Ordinary prose says The, When, Note, Design, and Should without declaring symbols.",
93
+ "",
94
+ "## Runtime Signals",
95
+ "",
96
+ "Use `AuthService`, `GET /api/auth/login`, `JWT_SECRET`, `src/auth/session.ts`, `RedisTimeoutError`, and `loadSession()`.",
97
+ "CJK code references `登录服务`, `POST /接口/登录`, `登录.认证.重试`, `验证登录()`, and `認証を確認()`.",
98
+ "",
99
+ "```ts",
100
+ "Do Prefer Use Fall Include Start Reason",
101
+ "class SessionRepository {}",
102
+ "interface AuthAdapter {}",
103
+ "function rotateToken() {}",
104
+ "function 验证会话() {}",
105
+ "```",
106
+ ""
107
+ ].join("\n");
108
+ }
109
+ function uniqueEntities(values) {
110
+ return [...new Map(values.map((entity) => [entityKey(entity), entity])).values()]
111
+ .sort((left, right) => entityKey(left).localeCompare(entityKey(right)));
112
+ }
113
+ function entityKey(entity) {
114
+ return `${entity.kind}:${normalizeEntityName(entity.name)}`;
115
+ }
116
+ function ratio(numerator, denominator) {
117
+ return denominator ? Number((numerator / denominator).toFixed(4)) : 0;
118
+ }
@@ -0,0 +1,70 @@
1
+ export declare const HISTORICAL_BASELINE_VERSION = 1;
2
+ export interface SynonymRetrievalBaselineCase {
3
+ id: string;
4
+ query: string;
5
+ expectedDocument: string;
6
+ title: string;
7
+ content: string;
8
+ }
9
+ export interface WatcherFailureBaselineCase {
10
+ code: "ENOSPC" | "EMFILE" | "EACCES" | "INDEX_ERROR";
11
+ phase: "startup" | "runtime" | "indexing";
12
+ expectedFuturePolicy: "fatal" | "degraded";
13
+ reason: string;
14
+ }
15
+ export interface HistoricalBaselineReport {
16
+ baselineVersion: typeof HISTORICAL_BASELINE_VERSION;
17
+ runtime: {
18
+ nodeVersion: string;
19
+ platform: NodeJS.Platform;
20
+ architecture: string;
21
+ };
22
+ semantic: {
23
+ provider: "local-hash";
24
+ dimensions: number;
25
+ cases: Array<{
26
+ id: string;
27
+ query: string;
28
+ expectedDocument: string;
29
+ keywordRank: number | null;
30
+ localHashRank: number | null;
31
+ }>;
32
+ keywordRecallAt5: number;
33
+ localHashRecallAt5: number;
34
+ elapsedMs: number;
35
+ };
36
+ entities: {
37
+ expected: string[];
38
+ extracted: string[];
39
+ truePositives: string[];
40
+ falsePositives: string[];
41
+ falseNegatives: string[];
42
+ precision: number;
43
+ recall: number;
44
+ elapsedMs: number;
45
+ };
46
+ context: {
47
+ packingStrategy: "mmr-style-document-round-robin";
48
+ itemCount: number;
49
+ uniqueDocuments: number;
50
+ diversityRatio: number;
51
+ averagePairwiseJaccard: number;
52
+ maximumPairwiseJaccard: number;
53
+ nearDuplicatePairs: number;
54
+ elapsedMs: number;
55
+ };
56
+ watch: {
57
+ cases: WatcherFailureBaselineCase[];
58
+ currentPolicy: {
59
+ errorSignal: "onError_callback";
60
+ persistentHealth: false;
61
+ fatalRuntimeErrors: false;
62
+ pollingFallback: false;
63
+ };
64
+ };
65
+ }
66
+ export declare const SYNONYM_RETRIEVAL_BASELINE_CASES: SynonymRetrievalBaselineCase[];
67
+ export declare const ENTITY_EXTRACTION_BASELINE_EXPECTED: readonly ["AuthCoordinator", "AuthService", "GET /api/auth/login", "JWT_SECRET", "RedisTimeoutError", "SessionRepository", "loadSession()", "rotateToken()", "src/auth/session.ts"];
68
+ export declare const ENTITY_EXTRACTION_BASELINE_FALSE_POSITIVES: readonly ["/auth/session.ts", "Do", "Fall", "GET", "Include", "Prefer", "Reason", "Start", "Use"];
69
+ export declare const WATCHER_FAILURE_BASELINE_CASES: WatcherFailureBaselineCase[];
70
+ export declare function runHistoricalBaseline(): Promise<HistoricalBaselineReport>;
@@ -0,0 +1,278 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+ import { DEFAULT_CONFIG } from "../config/load-config.js";
6
+ import { openDatabase } from "../db/connection.js";
7
+ import { GraphRepository } from "../db/repositories.js";
8
+ import { indexProject } from "../indexer.js";
9
+ import { buildContext } from "../query/context-builder.js";
10
+ import { searchGraph } from "../query/search.js";
11
+ export const HISTORICAL_BASELINE_VERSION = 1;
12
+ export const SYNONYM_RETRIEVAL_BASELINE_CASES = [
13
+ {
14
+ id: "synonym-authentication",
15
+ query: "authentication login",
16
+ expectedDocument: "docs/identity-verification.md",
17
+ title: "Identity Verification",
18
+ content: "Credential validation checks secret material before granting a user session."
19
+ },
20
+ {
21
+ id: "synonym-cache-retry",
22
+ query: "redis timeout retry",
23
+ expectedDocument: "docs/cache-recovery.md",
24
+ title: "Cache Recovery",
25
+ content: "A transient datastore delay triggers another attempt with bounded backoff."
26
+ },
27
+ {
28
+ id: "synonym-rollback",
29
+ query: "rollback failed deploy",
30
+ expectedDocument: "docs/release-reversal.md",
31
+ title: "Release Reversal",
32
+ content: "Restore the previous release when production health deteriorates after rollout."
33
+ },
34
+ {
35
+ id: "synonym-key-rotation",
36
+ query: "renew jwt secret",
37
+ expectedDocument: "docs/signing-credential-lifecycle.md",
38
+ title: "Signing Credential Lifecycle",
39
+ content: "Replace token signing credentials on a regular schedule and retire old key material."
40
+ }
41
+ ];
42
+ export const ENTITY_EXTRACTION_BASELINE_EXPECTED = [
43
+ "AuthCoordinator",
44
+ "AuthService",
45
+ "GET /api/auth/login",
46
+ "JWT_SECRET",
47
+ "RedisTimeoutError",
48
+ "SessionRepository",
49
+ "loadSession()",
50
+ "rotateToken()",
51
+ "src/auth/session.ts"
52
+ ];
53
+ export const ENTITY_EXTRACTION_BASELINE_FALSE_POSITIVES = [
54
+ "/auth/session.ts",
55
+ "Do",
56
+ "Fall",
57
+ "GET",
58
+ "Include",
59
+ "Prefer",
60
+ "Reason",
61
+ "Start",
62
+ "Use"
63
+ ];
64
+ export const WATCHER_FAILURE_BASELINE_CASES = [
65
+ {
66
+ code: "ENOSPC",
67
+ phase: "startup",
68
+ expectedFuturePolicy: "fatal",
69
+ reason: "The operating-system watch limit prevents complete watcher registration."
70
+ },
71
+ {
72
+ code: "ENOSPC",
73
+ phase: "runtime",
74
+ expectedFuturePolicy: "degraded",
75
+ reason: "A running watcher may no longer cover the full project after resource exhaustion."
76
+ },
77
+ {
78
+ code: "EMFILE",
79
+ phase: "runtime",
80
+ expectedFuturePolicy: "degraded",
81
+ reason: "File-descriptor exhaustion makes subsequent watch coverage unreliable."
82
+ },
83
+ {
84
+ code: "EACCES",
85
+ phase: "startup",
86
+ expectedFuturePolicy: "fatal",
87
+ reason: "Unreadable configured paths make the initial watch set incomplete."
88
+ },
89
+ {
90
+ code: "INDEX_ERROR",
91
+ phase: "indexing",
92
+ expectedFuturePolicy: "degraded",
93
+ reason: "An indexing failure must remain visible until a later successful reindex."
94
+ }
95
+ ];
96
+ export async function runHistoricalBaseline() {
97
+ const [semantic, entities, context] = await Promise.all([
98
+ measureSemanticBaseline(),
99
+ measureEntityBaseline(),
100
+ measureContextBaseline()
101
+ ]);
102
+ return {
103
+ baselineVersion: HISTORICAL_BASELINE_VERSION,
104
+ runtime: {
105
+ nodeVersion: process.version,
106
+ platform: process.platform,
107
+ architecture: process.arch
108
+ },
109
+ semantic,
110
+ entities,
111
+ context,
112
+ watch: {
113
+ cases: WATCHER_FAILURE_BASELINE_CASES,
114
+ currentPolicy: {
115
+ errorSignal: "onError_callback",
116
+ persistentHealth: false,
117
+ fatalRuntimeErrors: false,
118
+ pollingFallback: false
119
+ }
120
+ }
121
+ };
122
+ }
123
+ async function measureSemanticBaseline() {
124
+ const started = performance.now();
125
+ const root = createTempProject("mdgraph-historical-semantic-");
126
+ try {
127
+ for (const item of SYNONYM_RETRIEVAL_BASELINE_CASES) {
128
+ writeMarkdown(root, item.expectedDocument, item.title, item.content);
129
+ }
130
+ await indexProject(root, { full: true, semantic: true });
131
+ const repository = new GraphRepository(openDatabase(root));
132
+ try {
133
+ const config = {
134
+ ...DEFAULT_CONFIG,
135
+ embedding: { ...DEFAULT_CONFIG.embedding, enabled: true }
136
+ };
137
+ const cases = SYNONYM_RETRIEVAL_BASELINE_CASES.map((item) => {
138
+ const keyword = searchGraph(repository, config, item.query, 5, { queryMode: "keyword" });
139
+ const localHash = searchGraph(repository, config, item.query, 5, { queryMode: "semantic" });
140
+ return {
141
+ id: item.id,
142
+ query: item.query,
143
+ expectedDocument: item.expectedDocument,
144
+ keywordRank: resultRank(keyword, item.expectedDocument),
145
+ localHashRank: resultRank(localHash, item.expectedDocument)
146
+ };
147
+ });
148
+ return {
149
+ provider: "local-hash",
150
+ dimensions: config.embedding.dimensions,
151
+ cases,
152
+ keywordRecallAt5: recallAt5(cases.map((item) => item.keywordRank)),
153
+ localHashRecallAt5: recallAt5(cases.map((item) => item.localHashRank)),
154
+ elapsedMs: elapsed(started)
155
+ };
156
+ }
157
+ finally {
158
+ repository.close();
159
+ }
160
+ }
161
+ finally {
162
+ fs.rmSync(root, { recursive: true, force: true });
163
+ }
164
+ }
165
+ async function measureEntityBaseline() {
166
+ const started = performance.now();
167
+ const expected = uniqueSorted([...ENTITY_EXTRACTION_BASELINE_EXPECTED]);
168
+ const falsePositives = uniqueSorted([...ENTITY_EXTRACTION_BASELINE_FALSE_POSITIVES]);
169
+ const extracted = uniqueSorted([...expected, ...falsePositives]);
170
+ // This versioned comparison point preserves results from before the current
171
+ // entity extractor instead of silently replacing them on every run.
172
+ return {
173
+ expected,
174
+ extracted,
175
+ truePositives: expected,
176
+ falsePositives,
177
+ falseNegatives: [],
178
+ precision: ratio(expected.length, extracted.length),
179
+ recall: 1,
180
+ elapsedMs: elapsed(started)
181
+ };
182
+ }
183
+ async function measureContextBaseline() {
184
+ const started = performance.now();
185
+ const root = createTempProject("mdgraph-historical-context-");
186
+ try {
187
+ writeMarkdown(root, "docs/recovery-details.md", "Recovery Details", [
188
+ "## First Attempt",
189
+ "",
190
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics.",
191
+ "",
192
+ "## Second Attempt",
193
+ "",
194
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics.",
195
+ "",
196
+ "## Third Attempt",
197
+ "",
198
+ "`SessionRecoveryPolicy` retries authentication sessions after cache failures and records recovery diagnostics."
199
+ ].join("\n"));
200
+ writeMarkdown(root, "docs/recovery-limits.md", "Recovery Limits", "`SessionRecoveryPolicy` caps retries before returning a terminal authentication response.");
201
+ writeMarkdown(root, "docs/recovery-operations.md", "Recovery Operations", "`SessionRecoveryPolicy` routes exhausted attempts to operational diagnostics and an incident runbook.");
202
+ await indexProject(root, { full: true });
203
+ const repository = new GraphRepository(openDatabase(root));
204
+ try {
205
+ const config = {
206
+ ...DEFAULT_CONFIG,
207
+ search: { ...DEFAULT_CONFIG.search, defaultLimit: 12, maxContextChars: 50_000 }
208
+ };
209
+ const context = buildContext(repository, config, "SessionRecoveryPolicy", {
210
+ debug: true,
211
+ searchLimit: 12,
212
+ maxChars: 50_000
213
+ });
214
+ const pairwise = pairwiseJaccard(context.items.map((item) => item.content));
215
+ return {
216
+ packingStrategy: "mmr-style-document-round-robin",
217
+ itemCount: context.items.length,
218
+ uniqueDocuments: new Set(context.items.map((item) => item.path)).size,
219
+ diversityRatio: context.debug?.packingDiversityRatio ?? 0,
220
+ averagePairwiseJaccard: average(pairwise),
221
+ maximumPairwiseJaccard: pairwise.length ? Math.max(...pairwise) : 0,
222
+ nearDuplicatePairs: pairwise.filter((value) => value >= 0.8).length,
223
+ elapsedMs: elapsed(started)
224
+ };
225
+ }
226
+ finally {
227
+ repository.close();
228
+ }
229
+ }
230
+ finally {
231
+ fs.rmSync(root, { recursive: true, force: true });
232
+ }
233
+ }
234
+ function createTempProject(prefix) {
235
+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
236
+ }
237
+ function writeMarkdown(root, relativePath, title, content) {
238
+ const target = path.join(root, relativePath);
239
+ fs.mkdirSync(path.dirname(target), { recursive: true });
240
+ fs.writeFileSync(target, `# ${title}\n\n${content}\n`, "utf8");
241
+ }
242
+ function resultRank(results, expectedDocument) {
243
+ const index = results.findIndex((result) => result.document.path === expectedDocument);
244
+ return index >= 0 ? index + 1 : null;
245
+ }
246
+ function recallAt5(ranks) {
247
+ return ratio(ranks.filter((rank) => rank !== null && rank <= 5).length, ranks.length);
248
+ }
249
+ function pairwiseJaccard(contents) {
250
+ const tokenSets = contents.map(tokensForSimilarity);
251
+ const similarities = [];
252
+ for (let left = 0; left < tokenSets.length; left += 1) {
253
+ for (let right = left + 1; right < tokenSets.length; right += 1) {
254
+ const union = new Set([...tokenSets[left], ...tokenSets[right]]);
255
+ const intersection = [...tokenSets[left]].filter((token) => tokenSets[right].has(token));
256
+ similarities.push(ratio(intersection.length, union.size));
257
+ }
258
+ }
259
+ return similarities;
260
+ }
261
+ function tokensForSimilarity(content) {
262
+ return new Set(content.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []);
263
+ }
264
+ function uniqueSorted(values) {
265
+ return [...new Set(values)].sort((left, right) => left.localeCompare(right));
266
+ }
267
+ function average(values) {
268
+ return values.length ? round(values.reduce((sum, value) => sum + value, 0) / values.length) : 0;
269
+ }
270
+ function ratio(numerator, denominator) {
271
+ return denominator ? round(numerator / denominator) : 0;
272
+ }
273
+ function elapsed(started) {
274
+ return Number((performance.now() - started).toFixed(2));
275
+ }
276
+ function round(value) {
277
+ return Number(value.toFixed(4));
278
+ }
@@ -0,0 +1,26 @@
1
+ export declare const RELATED_DOCUMENTS_EVALUATION_VERSION = 1;
2
+ export declare const RELATED_DOCUMENTS_GATES: {
3
+ readonly minimumPrecision: 0.9;
4
+ readonly minimumRecall: 0.8;
5
+ readonly requireCompleteProvenance: true;
6
+ readonly requireDeterministicReplacement: true;
7
+ };
8
+ export interface RelatedDocumentsEvaluationReport {
9
+ evaluationVersion: typeof RELATED_DOCUMENTS_EVALUATION_VERSION;
10
+ expectedPairs: string[];
11
+ observedPairs: string[];
12
+ truePositives: string[];
13
+ falsePositives: string[];
14
+ falseNegatives: string[];
15
+ precision: number;
16
+ recall: number;
17
+ completeProvenance: boolean;
18
+ deterministicReplacement: boolean;
19
+ relationshipPairs: number;
20
+ directedEdges: number;
21
+ qualityGate: string;
22
+ gates: typeof RELATED_DOCUMENTS_GATES;
23
+ passed: boolean;
24
+ elapsedMs: number;
25
+ }
26
+ export declare function runRelatedDocumentsEvaluation(): Promise<RelatedDocumentsEvaluationReport>;
@@ -0,0 +1,163 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+ import { loadConfig } from "../config/load-config.js";
6
+ import { openDatabase } from "../db/connection.js";
7
+ import { GraphRepository } from "../db/repositories.js";
8
+ import { indexProject } from "../indexer.js";
9
+ import { deriveRelatedRelationships } from "../relationships/derive-related.js";
10
+ import { registerEmbeddingProvider } from "../semantic/provider-registry.js";
11
+ export const RELATED_DOCUMENTS_EVALUATION_VERSION = 1;
12
+ export const RELATED_DOCUMENTS_GATES = {
13
+ minimumPrecision: 0.9,
14
+ minimumRecall: 0.8,
15
+ requireCompleteProvenance: true,
16
+ requireDeterministicReplacement: true
17
+ };
18
+ const EXPECTED_PAIRS = [
19
+ ["docs/auth-decision.md", "docs/auth-runbook.md"],
20
+ ["docs/cache-incident.md", "docs/cache-runbook.md"]
21
+ ];
22
+ export async function runRelatedDocumentsEvaluation() {
23
+ const started = performance.now();
24
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mdgraph-related-relationships-"));
25
+ const unregister = registerEmbeddingProvider("related-fixture-semantic", "semantic-model", (config) => ({
26
+ id: config.provider,
27
+ model: config.model,
28
+ dimensions: config.dimensions,
29
+ capability: "semantic-model",
30
+ locality: "in-process",
31
+ availability: async () => ({ status: "available" }),
32
+ embedDocuments: async (inputs) => inputs.map(fixtureVector),
33
+ embedQuery: async (input) => fixtureVector(input)
34
+ }));
35
+ try {
36
+ writeFixture(root);
37
+ await indexProject(root, { full: true });
38
+ const repository = new GraphRepository(openDatabase(root));
39
+ try {
40
+ const config = loadConfig(root);
41
+ const first = await deriveRelatedRelationships(repository, root, config, { threshold: 0.9 });
42
+ const firstEdges = repository.allEdges()
43
+ .filter((edge) => edge.kind === "RELATED_TO" && edge.provenance === "embedding_similarity")
44
+ .map((edge) => edge.id)
45
+ .sort();
46
+ const second = await deriveRelatedRelationships(repository, root, config, { threshold: 0.9 });
47
+ const secondEdges = repository.allEdges()
48
+ .filter((edge) => edge.kind === "RELATED_TO" && edge.provenance === "embedding_similarity");
49
+ const observedPairs = second.relationships.map((relationship) => pairKey(relationship.fromPath, relationship.toPath)).sort();
50
+ const expectedPairs = EXPECTED_PAIRS.map(([left, right]) => pairKey(left, right)).sort();
51
+ const expected = new Set(expectedPairs);
52
+ const observed = new Set(observedPairs);
53
+ const truePositives = observedPairs.filter((pair) => expected.has(pair));
54
+ const falsePositives = observedPairs.filter((pair) => !expected.has(pair));
55
+ const falseNegatives = expectedPairs.filter((pair) => !observed.has(pair));
56
+ const precision = ratio(truePositives.length, observedPairs.length);
57
+ const recall = ratio(truePositives.length, expectedPairs.length);
58
+ const completeProvenance = secondEdges.length === second.directedEdges && secondEdges.every((edge) => {
59
+ const metadata = edge.metadata ?? {};
60
+ const evidence = Array.isArray(metadata.evidenceSections) ? metadata.evidenceSections : [];
61
+ return metadata.provider === "related-fixture-semantic"
62
+ && metadata.model === "related-fixture-model"
63
+ && metadata.algorithmVersion === second.algorithmVersion
64
+ && metadata.qualityGate === second.qualityGate.id
65
+ && typeof metadata.threshold === "number"
66
+ && typeof metadata.generatedAt === "string"
67
+ && evidence.length >= 2;
68
+ });
69
+ const deterministicReplacement = firstEdges.length === secondEdges.length
70
+ && firstEdges.every((id, index) => id === secondEdges.map((edge) => edge.id).sort()[index])
71
+ && second.mutation.removed === first.directedEdges
72
+ && second.mutation.inserted === second.directedEdges;
73
+ const passed = precision >= RELATED_DOCUMENTS_GATES.minimumPrecision
74
+ && recall >= RELATED_DOCUMENTS_GATES.minimumRecall
75
+ && (!RELATED_DOCUMENTS_GATES.requireCompleteProvenance || completeProvenance)
76
+ && (!RELATED_DOCUMENTS_GATES.requireDeterministicReplacement || deterministicReplacement);
77
+ return {
78
+ evaluationVersion: RELATED_DOCUMENTS_EVALUATION_VERSION,
79
+ expectedPairs,
80
+ observedPairs,
81
+ truePositives,
82
+ falsePositives,
83
+ falseNegatives,
84
+ precision,
85
+ recall,
86
+ completeProvenance,
87
+ deterministicReplacement,
88
+ relationshipPairs: second.relationshipPairs,
89
+ directedEdges: second.directedEdges,
90
+ qualityGate: second.qualityGate.id,
91
+ gates: RELATED_DOCUMENTS_GATES,
92
+ passed,
93
+ elapsedMs: elapsed(started)
94
+ };
95
+ }
96
+ finally {
97
+ repository.close();
98
+ }
99
+ }
100
+ finally {
101
+ unregister();
102
+ fs.rmSync(root, { recursive: true, force: true });
103
+ }
104
+ }
105
+ function writeFixture(root) {
106
+ fs.mkdirSync(path.join(root, ".mdgraph"), { recursive: true });
107
+ fs.mkdirSync(path.join(root, "docs"), { recursive: true });
108
+ fs.writeFileSync(path.join(root, ".mdgraph", "config.json"), `${JSON.stringify({
109
+ docs: { include: ["docs/**/*.md"] },
110
+ embedding: {
111
+ enabled: true,
112
+ provider: "related-fixture-semantic",
113
+ model: "related-fixture-model",
114
+ dimensions: 4,
115
+ batchSize: 4
116
+ }
117
+ }, null, 2)}\n`, "utf8");
118
+ writeDocument(root, "auth-decision.md", "Auth Decision", "AUTH_CLUSTER", "AUTH_CLUSTER");
119
+ writeDocument(root, "auth-runbook.md", "Login Recovery", "AUTH_CLUSTER", "AUTH_CLUSTER");
120
+ writeDocument(root, "cache-incident.md", "Cache Incident", "CACHE_CLUSTER", "CACHE_CLUSTER");
121
+ writeDocument(root, "cache-runbook.md", "Cache Recovery", "CACHE_CLUSTER", "CACHE_CLUSTER");
122
+ writeDocument(root, "billing-guide.md", "Billing Guide", "BILLING_CLUSTER", "BILLING_CLUSTER");
123
+ writeDocument(root, "mixed-note.md", "Mixed Note", "AUTH_CLUSTER", "BILLING_CLUSTER");
124
+ }
125
+ function writeDocument(root, file, title, first, second) {
126
+ fs.writeFileSync(path.join(root, "docs", file), `---
127
+ title: ${title}
128
+ type: guide
129
+ status: active
130
+ ---
131
+ ## First evidence
132
+
133
+ ${first}
134
+
135
+ ## Second evidence
136
+
137
+ ${second}
138
+ `, "utf8");
139
+ }
140
+ function fixtureVector(input) {
141
+ if (input.includes("AUTH_CLUSTER") && input.includes("BILLING_CLUSTER")) {
142
+ return [1, 0, 1, 0];
143
+ }
144
+ if (input.includes("AUTH_CLUSTER")) {
145
+ return [1, 0, 0, 0];
146
+ }
147
+ if (input.includes("CACHE_CLUSTER")) {
148
+ return [0, 1, 0, 0];
149
+ }
150
+ if (input.includes("BILLING_CLUSTER")) {
151
+ return [0, 0, 1, 0];
152
+ }
153
+ return [0, 0, 0, 1];
154
+ }
155
+ function pairKey(left, right) {
156
+ return [left, right].sort().join(" <-> ");
157
+ }
158
+ function ratio(numerator, denominator) {
159
+ return denominator === 0 ? 0 : numerator / denominator;
160
+ }
161
+ function elapsed(started) {
162
+ return Number((performance.now() - started).toFixed(2));
163
+ }