@daogee/mdgraph 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README-ZH.md +66 -4
  3. package/README.md +84 -22
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +3 -1
  6. package/agent-pack/prompts/wiki-authoring.md +12 -0
  7. package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
  8. package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
  9. package/dist/analysis/status-freshness.d.ts +8 -1
  10. package/dist/analysis/status-freshness.js +19 -6
  11. package/dist/bin/mdgraph.js +260 -25
  12. package/dist/config/limits.d.ts +2 -0
  13. package/dist/config/limits.js +3 -1
  14. package/dist/config/load-config.js +8 -2
  15. package/dist/db/connection.js +17 -1
  16. package/dist/db/repositories.d.ts +55 -4
  17. package/dist/db/repositories.js +458 -11
  18. package/dist/db/sqlite-adapter.js +8 -2
  19. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  20. package/dist/evaluation/context-packing-evaluation.js +134 -0
  21. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  22. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  23. package/dist/evaluation/historical-baseline.d.ts +70 -0
  24. package/dist/evaluation/historical-baseline.js +278 -0
  25. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  26. package/dist/evaluation/related-documents-evaluation.js +163 -0
  27. package/dist/evaluation/retrieval-eval.d.ts +25 -5
  28. package/dist/evaluation/retrieval-eval.js +79 -7
  29. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  30. package/dist/evaluation/structured-query-evaluation.js +156 -0
  31. package/dist/extraction/entity-extractor.js +42 -22
  32. package/dist/extraction/graph-builder.js +2 -18
  33. package/dist/index.d.ts +24 -4
  34. package/dist/index.js +12 -4
  35. package/dist/indexer.js +80 -4
  36. package/dist/mcp/server.d.ts +4 -0
  37. package/dist/mcp/server.js +21 -11
  38. package/dist/mcp/tools.d.ts +5 -1
  39. package/dist/mcp/tools.js +116 -18
  40. package/dist/parser/markdown-parser.js +2 -0
  41. package/dist/query/context-builder.d.ts +32 -2
  42. package/dist/query/context-builder.js +191 -12
  43. package/dist/query/knowledge-card.d.ts +90 -0
  44. package/dist/query/knowledge-card.js +676 -0
  45. package/dist/query/search.d.ts +5 -1
  46. package/dist/query/search.js +85 -16
  47. package/dist/query/structured-query-executor.d.ts +28 -0
  48. package/dist/query/structured-query-executor.js +138 -0
  49. package/dist/query/structured-query.d.ts +50 -0
  50. package/dist/query/structured-query.js +390 -0
  51. package/dist/relationships/derive-related.d.ts +86 -0
  52. package/dist/relationships/derive-related.js +322 -0
  53. package/dist/reporting/report.js +2 -2
  54. package/dist/semantic/embed-chunks.d.ts +2 -0
  55. package/dist/semantic/embed-chunks.js +31 -0
  56. package/dist/semantic/ollama-provider.d.ts +6 -0
  57. package/dist/semantic/ollama-provider.js +136 -0
  58. package/dist/semantic/provider-registry.d.ts +8 -0
  59. package/dist/semantic/provider-registry.js +66 -0
  60. package/dist/semantic/provider.d.ts +35 -0
  61. package/dist/semantic/provider.js +29 -0
  62. package/dist/semantic/status.d.ts +6 -1
  63. package/dist/semantic/status.js +49 -3
  64. package/dist/types.d.ts +7 -2
  65. package/dist/types.js +2 -1
  66. package/dist/utils/path-safety.d.ts +3 -0
  67. package/dist/utils/path-safety.js +27 -0
  68. package/dist/watcher/file-watcher.d.ts +4 -0
  69. package/dist/watcher/file-watcher.js +151 -17
  70. package/dist/watcher/watch-health.d.ts +34 -0
  71. package/dist/watcher/watch-health.js +75 -0
  72. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  73. package/dist/wiki/wiki-dependencies.js +45 -0
  74. package/dist/wiki/wiki-domains.d.ts +13 -0
  75. package/dist/wiki/wiki-domains.js +55 -0
  76. package/dist/wiki/wiki-evidence.d.ts +27 -0
  77. package/dist/wiki/wiki-evidence.js +112 -0
  78. package/dist/wiki/wiki-plan.d.ts +121 -0
  79. package/dist/wiki/wiki-plan.js +616 -0
  80. package/dist/wiki/wiki-status.d.ts +67 -0
  81. package/dist/wiki/wiki-status.js +451 -0
  82. package/docs/EN/Agent_Integration.md +15 -5
  83. package/docs/EN/Architecture.md +52 -16
  84. package/docs/EN/Evaluation_Questions.md +35 -5
  85. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  86. package/docs/EN/Operations.md +111 -0
  87. package/docs/EN/Output_Contracts.md +83 -10
  88. package/docs/EN/Public_Contracts.md +25 -16
  89. package/docs/EN/Public_Contracts_1.0.md +32 -18
  90. package/docs/EN/README.md +24 -0
  91. package/docs/EN/Release_Checklist.md +27 -13
  92. package/docs/EN/Retrieval_and_Context.md +118 -0
  93. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  94. package/docs/ZH/Agent_Integration.md +15 -5
  95. package/docs/ZH/Architecture.md +52 -21
  96. package/docs/ZH/Evaluation_Questions.md +36 -6
  97. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  98. package/docs/ZH/Operations.md +111 -0
  99. package/docs/ZH/Output_Contracts.md +83 -10
  100. package/docs/ZH/Public_Contracts.md +24 -15
  101. package/docs/ZH/Public_Contracts_1.0.md +31 -17
  102. package/docs/ZH/README.md +24 -0
  103. package/docs/ZH/Release_Checklist.md +27 -13
  104. package/docs/ZH/Retrieval_and_Context.md +118 -0
  105. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  106. package/package.json +50 -19
@@ -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
+ }
@@ -1,7 +1,8 @@
1
1
  import type { EdgeKind, SearchQueryMode } from "../types.js";
2
2
  import type { GraphRepository } from "../db/repositories.js";
3
3
  import type { MDGraphConfig } from "../types.js";
4
- import { CONTEXT_PACKING_STRATEGY } from "../query/context-builder.js";
4
+ import type { ContextPackingStrategy } from "../query/context-builder.js";
5
+ import type { EmbeddingDiagnostic } from "../semantic/provider.js";
5
6
  import { type TraceResult } from "../query/trace.js";
6
7
  export interface EvaluationSectionExpectation {
7
8
  path: string;
@@ -27,9 +28,16 @@ export interface EvaluationMetrics {
27
28
  topKDocumentRecall: number;
28
29
  expectedSectionRecall: number;
29
30
  contextPrecision: number;
31
+ /** Compatibility metric: entity existence across the index. */
30
32
  entityRecall: number;
33
+ /** Compatibility metric: source-reference existence across the index. */
31
34
  sourceRefRecall: number;
35
+ /** Compatibility metric: edge kinds across the index and trace. */
32
36
  edgeKindCoverage: number;
37
+ retrievedEntityRecall: number;
38
+ retrievedSourceRefRecall: number;
39
+ retrievedEdgeKindCoverage: number;
40
+ contextIrrelevantRatio: number;
33
41
  traceSuccess: boolean | null;
34
42
  latencyMs: number;
35
43
  returnedChars: number;
@@ -49,6 +57,7 @@ export interface EvaluationCaseResult {
49
57
  id: string;
50
58
  query: string;
51
59
  passed: boolean;
60
+ retrievalEvidencePassed: boolean;
52
61
  expected: Omit<EvaluationCase, "id" | "query" | "trace">;
53
62
  observed: {
54
63
  searchDocuments: string[];
@@ -61,14 +70,18 @@ export interface EvaluationCaseResult {
61
70
  resolvedEntities: string[];
62
71
  resolvedSourceRefs: string[];
63
72
  edgeKinds: EdgeKind[];
73
+ retrievedEntities: string[];
74
+ retrievedSourceRefs: string[];
75
+ retrievedEdgeKinds: EdgeKind[];
64
76
  trace?: TraceResult;
65
77
  ranking: {
66
78
  queryMode: SearchQueryMode;
67
79
  searchFusion: "rrf";
68
80
  searchChannels: string[];
69
81
  semanticActive: boolean;
70
- optionalReranker: "none" | "local-hash";
71
- contextPackingStrategy: typeof CONTEXT_PACKING_STRATEGY;
82
+ optionalReranker: string;
83
+ semanticDiagnostic?: EmbeddingDiagnostic;
84
+ contextPackingStrategy: ContextPackingStrategy;
72
85
  };
73
86
  };
74
87
  metrics: EvaluationMetrics;
@@ -87,12 +100,13 @@ export interface EvaluationSummary {
87
100
  export interface EvaluationRankingReport {
88
101
  queryMode: SearchQueryMode;
89
102
  searchFusion: "rrf";
90
- contextPackingStrategy: typeof CONTEXT_PACKING_STRATEGY;
91
- optionalReranker: "none" | "local-hash";
103
+ contextPackingStrategy: ContextPackingStrategy;
104
+ optionalReranker: string;
92
105
  semanticActiveCases: number;
93
106
  searchChannels: string[];
94
107
  rankingReasonCoverage: boolean;
95
108
  averageContextDiversity: number;
109
+ semanticDiagnostics?: EmbeddingDiagnostic[];
96
110
  }
97
111
  export interface EvaluationReport {
98
112
  querySet: string;
@@ -113,3 +127,9 @@ export declare function evaluateRetrieval(repository: GraphRepository, config: M
113
127
  querySet?: string;
114
128
  queryMode?: SearchQueryMode;
115
129
  }): EvaluationReport;
130
+ export declare function evaluateRetrievalAsync(repository: GraphRepository, config: MDGraphConfig, options?: {
131
+ cases?: EvaluationCase[];
132
+ limit?: number;
133
+ querySet?: string;
134
+ queryMode?: SearchQueryMode;
135
+ }): Promise<EvaluationReport>;