@daogee/mdgraph 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README-ZH.md +203 -0
  4. package/README.md +203 -0
  5. package/agent-pack/README.md +26 -0
  6. package/agent-pack/host-examples.md +71 -0
  7. package/agent-pack/mcp-config.example.json +14 -0
  8. package/agent-pack/mdgraph-agent-instructions.md +21 -0
  9. package/agent-pack/prompts/relationship-trace.md +12 -0
  10. package/agent-pack/prompts/status-doctor.md +13 -0
  11. package/agent-pack/prompts/task-start-context.md +15 -0
  12. package/dist/analysis/doctor-scope.d.ts +8 -0
  13. package/dist/analysis/doctor-scope.js +109 -0
  14. package/dist/analysis/doctor.d.ts +148 -0
  15. package/dist/analysis/doctor.js +919 -0
  16. package/dist/analysis/status-freshness.d.ts +13 -0
  17. package/dist/analysis/status-freshness.js +55 -0
  18. package/dist/benchmark/benchmark.d.ts +118 -0
  19. package/dist/benchmark/benchmark.js +357 -0
  20. package/dist/bin/mdgraph.d.ts +2 -0
  21. package/dist/bin/mdgraph.js +877 -0
  22. package/dist/bundle/bundle.d.ts +66 -0
  23. package/dist/bundle/bundle.js +320 -0
  24. package/dist/config/limits.d.ts +24 -0
  25. package/dist/config/limits.js +24 -0
  26. package/dist/config/load-config.d.ts +14 -0
  27. package/dist/config/load-config.js +177 -0
  28. package/dist/db/connection.d.ts +15 -0
  29. package/dist/db/connection.js +145 -0
  30. package/dist/db/repositories.d.ts +159 -0
  31. package/dist/db/repositories.js +929 -0
  32. package/dist/db/schema.sql +110 -0
  33. package/dist/db/sqlite-adapter.d.ts +18 -0
  34. package/dist/db/sqlite-adapter.js +60 -0
  35. package/dist/diff/graph-diff.d.ts +41 -0
  36. package/dist/diff/graph-diff.js +334 -0
  37. package/dist/evaluation/retrieval-eval.d.ts +115 -0
  38. package/dist/evaluation/retrieval-eval.js +399 -0
  39. package/dist/export/diagram.d.ts +11 -0
  40. package/dist/export/diagram.js +41 -0
  41. package/dist/export/graphjson.d.ts +89 -0
  42. package/dist/export/graphjson.js +299 -0
  43. package/dist/export/markdown-index.d.ts +21 -0
  44. package/dist/export/markdown-index.js +89 -0
  45. package/dist/export/source-bridge.d.ts +22 -0
  46. package/dist/export/source-bridge.js +83 -0
  47. package/dist/extraction/entity-extractor.d.ts +12 -0
  48. package/dist/extraction/entity-extractor.js +153 -0
  49. package/dist/extraction/graph-builder.d.ts +2 -0
  50. package/dist/extraction/graph-builder.js +168 -0
  51. package/dist/index.d.ts +28 -0
  52. package/dist/index.js +28 -0
  53. package/dist/indexer.d.ts +19 -0
  54. package/dist/indexer.js +100 -0
  55. package/dist/mcp/debug.d.ts +7 -0
  56. package/dist/mcp/debug.js +41 -0
  57. package/dist/mcp/server-instructions.d.ts +2 -0
  58. package/dist/mcp/server-instructions.js +40 -0
  59. package/dist/mcp/server.d.ts +28 -0
  60. package/dist/mcp/server.js +232 -0
  61. package/dist/mcp/tools.d.ts +31 -0
  62. package/dist/mcp/tools.js +506 -0
  63. package/dist/mcp/transport.d.ts +50 -0
  64. package/dist/mcp/transport.js +88 -0
  65. package/dist/parser/frontmatter.d.ts +10 -0
  66. package/dist/parser/frontmatter.js +191 -0
  67. package/dist/parser/links.d.ts +6 -0
  68. package/dist/parser/links.js +9 -0
  69. package/dist/parser/markdown-parser.d.ts +2 -0
  70. package/dist/parser/markdown-parser.js +267 -0
  71. package/dist/query/context-builder.d.ts +85 -0
  72. package/dist/query/context-builder.js +413 -0
  73. package/dist/query/search.d.ts +32 -0
  74. package/dist/query/search.js +237 -0
  75. package/dist/query/trace.d.ts +10 -0
  76. package/dist/query/trace.js +55 -0
  77. package/dist/reporting/report.d.ts +49 -0
  78. package/dist/reporting/report.js +143 -0
  79. package/dist/resolution/link-resolver.d.ts +17 -0
  80. package/dist/resolution/link-resolver.js +113 -0
  81. package/dist/scanner/file-scanner.d.ts +4 -0
  82. package/dist/scanner/file-scanner.js +144 -0
  83. package/dist/semantic/local-embedding.d.ts +4 -0
  84. package/dist/semantic/local-embedding.js +30 -0
  85. package/dist/semantic/status.d.ts +19 -0
  86. package/dist/semantic/status.js +70 -0
  87. package/dist/semantic/vector-codec.d.ts +3 -0
  88. package/dist/semantic/vector-codec.js +35 -0
  89. package/dist/types.d.ts +198 -0
  90. package/dist/types.js +15 -0
  91. package/dist/utils/bounded-json.d.ts +9 -0
  92. package/dist/utils/bounded-json.js +57 -0
  93. package/dist/utils/content-risk.d.ts +5 -0
  94. package/dist/utils/content-risk.js +20 -0
  95. package/dist/utils/fts.d.ts +3 -0
  96. package/dist/utils/fts.js +52 -0
  97. package/dist/utils/id.d.ts +2 -0
  98. package/dist/utils/id.js +8 -0
  99. package/dist/utils/path-safety.d.ts +4 -0
  100. package/dist/utils/path-safety.js +25 -0
  101. package/dist/utils/text.d.ts +7 -0
  102. package/dist/utils/text.js +36 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +11 -0
  105. package/dist/watcher/file-watcher.d.ts +11 -0
  106. package/dist/watcher/file-watcher.js +127 -0
  107. package/docs/EN/Agent_Integration.md +129 -0
  108. package/docs/EN/Architecture.md +135 -0
  109. package/docs/EN/Evaluation_Questions.md +68 -0
  110. package/docs/EN/Output_Contracts.md +274 -0
  111. package/docs/EN/Public_Contracts.md +88 -0
  112. package/docs/EN/Public_Contracts_1.0.md +234 -0
  113. package/docs/EN/Release_Checklist.md +82 -0
  114. package/docs/ZH/Agent_Integration.md +105 -0
  115. package/docs/ZH/Architecture.md +124 -0
  116. package/docs/ZH/Evaluation_Questions.md +66 -0
  117. package/docs/ZH/Output_Contracts.md +269 -0
  118. package/docs/ZH/Public_Contracts.md +81 -0
  119. package/docs/ZH/Public_Contracts_1.0.md +202 -0
  120. package/docs/ZH/Release_Checklist.md +83 -0
  121. package/package.json +94 -0
@@ -0,0 +1,413 @@
1
+ import { searchGraph } from "./search.js";
2
+ import { scanContentRiskLines } from "../utils/content-risk.js";
3
+ import { normalizePath, uniqueStrings } from "../utils/text.js";
4
+ const DEFAULT_MAX_CONTEXT_NODES = 16;
5
+ export const CONTEXT_PACKING_STRATEGY = "mmr-style-document-round-robin";
6
+ export function buildContext(repository, config, query, options = {}) {
7
+ const knownFiles = normalizeKnownFiles(options.knownFiles ?? []);
8
+ const maxChars = positiveIntegerOr(options.maxChars, config.search.maxContextChars);
9
+ const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
10
+ const maxDepth = positiveIntegerOr(options.maxDepth, config.search.maxDepth);
11
+ const results = searchGraph(repository, config, query, searchLimit, options.searchOptions);
12
+ const collection = collectContextCandidates(repository, config, results, maxDepth);
13
+ const candidates = knownFiles.length
14
+ ? mergeKnownFileCandidates(repository, collection.candidates, knownFiles)
15
+ : collection.candidates;
16
+ const packed = packContext(query, enrichContextCandidates(repository, candidates), maxChars, options.mode);
17
+ const result = addAgentHints(packed.result, knownFiles);
18
+ if (!options.debug) {
19
+ return result;
20
+ }
21
+ return {
22
+ ...result,
23
+ debug: {
24
+ ...collection.debug,
25
+ candidateCount: candidates.length,
26
+ directCandidates: candidates.filter((candidate) => candidate.direct).length,
27
+ expandedCandidates: candidates.filter((candidate) => !candidate.direct).length,
28
+ packingStrategy: CONTEXT_PACKING_STRATEGY,
29
+ packedItems: result.items.length,
30
+ packedUniqueDocuments: uniqueStrings(result.items.map((item) => item.path)).length,
31
+ packingDiversityRatio: result.items.length
32
+ ? Number((uniqueStrings(result.items.map((item) => item.path)).length / result.items.length).toFixed(4))
33
+ : 0,
34
+ budgetTruncatedItems: packed.budgetTruncatedItems,
35
+ budgetSkippedItems: packed.budgetSkippedItems
36
+ }
37
+ };
38
+ }
39
+ function mergeKnownFileCandidates(repository, candidates, knownFiles) {
40
+ const merged = new Map();
41
+ for (const candidate of candidates) {
42
+ addCandidate(merged, candidate);
43
+ }
44
+ knownFiles.forEach((knownFile, index) => {
45
+ for (const candidate of candidatesForKnownFile(repository, knownFile, index)) {
46
+ addCandidate(merged, candidate);
47
+ }
48
+ });
49
+ return orderContextCandidates([...merged.values()]);
50
+ }
51
+ function candidatesForKnownFile(repository, knownFile, index) {
52
+ const resolution = resolveKnownFile(repository, knownFile);
53
+ if (resolution?.kind !== "source_ref") {
54
+ const directRow = resolution ? repository.contextChunkForNode(resolution.id) : undefined;
55
+ return directRow ? [candidateFromKnownRow(directRow, `known file ${knownFile}`, index)] : [];
56
+ }
57
+ return repository.edgesForNode(resolution.id)
58
+ .map((edge) => {
59
+ const otherId = edge.fromId === resolution.id ? edge.toId : edge.fromId;
60
+ const row = repository.contextChunkForNode(otherId);
61
+ return row ? candidateFromKnownRow(row, `known file ${knownFile} via ${edge.kind}/${edge.provenance}`, index) : undefined;
62
+ })
63
+ .filter((candidate) => Boolean(candidate));
64
+ }
65
+ function resolveKnownFile(repository, knownFile) {
66
+ const queries = uniqueStrings([knownFile, normalizePath(knownFile)]);
67
+ for (const query of queries) {
68
+ const resolution = repository.resolveNodeDetailed(query);
69
+ if (resolution.status === "found") {
70
+ return resolution.node;
71
+ }
72
+ }
73
+ return undefined;
74
+ }
75
+ function candidateFromKnownRow(row, reason, index) {
76
+ return {
77
+ path: row.document.path,
78
+ title: row.document.title,
79
+ heading: row.section?.heading,
80
+ sectionId: row.section?.id,
81
+ anchor: row.section?.anchor,
82
+ lines: row.section ? { start: row.section.startLine, end: row.section.endLine } : undefined,
83
+ reason,
84
+ matchedEntities: [],
85
+ content: row.chunk.content,
86
+ nodeId: row.section?.id ?? row.document.id,
87
+ documentId: row.document.id,
88
+ documentStatus: row.document.status,
89
+ trustTier: row.document.trustTier,
90
+ trustTierDeclared: hasDeclaredTrustTier(row.document),
91
+ score: 10_000 - index,
92
+ direct: true
93
+ };
94
+ }
95
+ function addAgentHints(result, knownFiles) {
96
+ const suggestedNextQueries = suggestedQueries(result, knownFiles);
97
+ return {
98
+ ...result,
99
+ knownFiles: knownFiles.length ? knownFiles : undefined,
100
+ suggestedNextQueries: suggestedNextQueries.length ? suggestedNextQueries : undefined
101
+ };
102
+ }
103
+ function suggestedQueries(result, knownFiles) {
104
+ const paths = uniqueStrings(result.items.map((item) => item.path));
105
+ const entities = uniqueStrings(result.items.flatMap((item) => item.matchedEntities.map(entityNameOnly)));
106
+ const suggestions = [
107
+ paths[0] ? `mdgraph_node ${suggestedArgument(paths[0])}` : "",
108
+ knownFiles[0] && paths[0] ? `mdgraph_trace ${suggestedArgument(knownFiles[0])} ${suggestedArgument(paths[0])}` : "",
109
+ entities[0] ? `mdgraph_search ${suggestedArgument(entities[0])}` : ""
110
+ ];
111
+ return uniqueStrings(suggestions).slice(0, 3);
112
+ }
113
+ function suggestedArgument(value) {
114
+ return JSON.stringify(value);
115
+ }
116
+ function entityNameOnly(value) {
117
+ return value.replace(/\s+\([^)]*\)$/u, "");
118
+ }
119
+ function normalizeKnownFiles(values) {
120
+ return uniqueStrings(values.map((value) => normalizePath(value)));
121
+ }
122
+ function positiveIntegerOr(value, fallback) {
123
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
124
+ }
125
+ function collectContextCandidates(repository, config, results, maxDepth) {
126
+ let remainingExpansionNodes = Math.max(DEFAULT_MAX_CONTEXT_NODES, config.search.defaultLimit * 2);
127
+ const candidates = new Map();
128
+ const queue = [];
129
+ const visited = new Set();
130
+ const debug = {
131
+ seedNodes: 0,
132
+ visitedNodes: 0,
133
+ expandedEdges: 0,
134
+ skippedVisitedNodes: 0,
135
+ skippedByNodeLimit: 0,
136
+ skippedByDepth: 0
137
+ };
138
+ for (const result of results) {
139
+ addCandidate(candidates, candidateFromSearchResult(result));
140
+ for (const seed of seedsFromSearchResult(result)) {
141
+ if (visited.has(seed.nodeId)) {
142
+ debug.skippedVisitedNodes += 1;
143
+ continue;
144
+ }
145
+ visited.add(seed.nodeId);
146
+ debug.seedNodes += 1;
147
+ queue.push({ nodeId: seed.nodeId, depth: 0, score: result.score, path: [] });
148
+ }
149
+ }
150
+ while (queue.length) {
151
+ const current = queue.shift();
152
+ if (current.depth >= maxDepth) {
153
+ debug.skippedByDepth += 1;
154
+ continue;
155
+ }
156
+ const edges = repository.edgesForNode(current.nodeId)
157
+ .filter((edge) => edge.kind !== "CONTAINS")
158
+ .sort((left, right) => edgeScore(right) - edgeScore(left));
159
+ for (const edge of edges) {
160
+ const nextId = edge.fromId === current.nodeId ? edge.toId : edge.fromId;
161
+ if (visited.has(nextId)) {
162
+ debug.skippedVisitedNodes += 1;
163
+ continue;
164
+ }
165
+ if (remainingExpansionNodes <= 0) {
166
+ debug.skippedByNodeLimit += 1;
167
+ continue;
168
+ }
169
+ const step = expansionPathStep(repository, current.nodeId, edge);
170
+ const path = [...current.path, step];
171
+ const score = current.score + edgeScore(edge) - (current.depth + 1) * 2;
172
+ visited.add(nextId);
173
+ remainingExpansionNodes -= 1;
174
+ debug.expandedEdges += 1;
175
+ const row = repository.contextChunkForNode(nextId);
176
+ if (row) {
177
+ addCandidate(candidates, {
178
+ path: row.document.path,
179
+ title: row.document.title,
180
+ heading: row.section?.heading,
181
+ sectionId: row.section?.id,
182
+ anchor: row.section?.anchor,
183
+ lines: row.section ? { start: row.section.startLine, end: row.section.endLine } : undefined,
184
+ reason: `graph expansion via ${path.map(formatExpansionStep).join(" | ")}`,
185
+ matchedEntities: [],
186
+ edgePath: path,
187
+ content: row.chunk.content,
188
+ nodeId: row.section?.id ?? row.document.id,
189
+ documentId: row.document.id,
190
+ documentStatus: row.document.status,
191
+ trustTier: row.document.trustTier,
192
+ trustTierDeclared: hasDeclaredTrustTier(row.document),
193
+ score,
194
+ direct: false
195
+ });
196
+ }
197
+ queue.push({ nodeId: nextId, depth: current.depth + 1, score, path });
198
+ }
199
+ queue.sort((left, right) => right.score - left.score);
200
+ }
201
+ return {
202
+ candidates: orderContextCandidates([...candidates.values()]),
203
+ debug: {
204
+ ...debug,
205
+ visitedNodes: visited.size
206
+ }
207
+ };
208
+ }
209
+ function enrichContextCandidates(repository, candidates) {
210
+ return candidates.map((candidate) => {
211
+ const sourceRefs = sourceRefsForCandidate(repository, candidate);
212
+ const riskNotes = riskNotesForCandidate(candidate);
213
+ return {
214
+ ...candidate,
215
+ sourceRefs: sourceRefs.length ? sourceRefs : undefined,
216
+ riskNotes: riskNotes.length ? riskNotes : undefined
217
+ };
218
+ });
219
+ }
220
+ function sourceRefsForCandidate(repository, candidate) {
221
+ const edgeNodes = uniqueStrings([candidate.nodeId, candidate.documentId]);
222
+ const refs = new Map();
223
+ for (const nodeId of edgeNodes) {
224
+ for (const edge of repository.edgesForNode(nodeId)) {
225
+ if (edge.kind !== "IMPLEMENTS" && edge.kind !== "REFERENCES_SOURCE") {
226
+ continue;
227
+ }
228
+ const otherId = edge.fromId === nodeId ? edge.toId : edge.fromId;
229
+ const other = repository.getNode(otherId);
230
+ if (other?.kind !== "source_ref") {
231
+ continue;
232
+ }
233
+ const sourceRef = other.data;
234
+ const ref = {
235
+ path: sourceRef.path,
236
+ edgeKind: edge.kind,
237
+ provenance: edge.provenance,
238
+ confidence: edge.confidence
239
+ };
240
+ refs.set(`${ref.path}:${ref.edgeKind}`, ref);
241
+ }
242
+ }
243
+ return [...refs.values()].sort((left, right) => left.path.localeCompare(right.path) || left.edgeKind.localeCompare(right.edgeKind));
244
+ }
245
+ function riskNotesForCandidate(candidate) {
246
+ const notes = [];
247
+ const status = candidate.documentStatus.trim().toLowerCase();
248
+ if (status && status !== "active") {
249
+ notes.push(`document status: ${candidate.documentStatus}`);
250
+ }
251
+ if (candidate.trustTier !== "authored" && candidate.trustTier !== "validated") {
252
+ notes.push(`trust tier: ${candidate.trustTier}`);
253
+ }
254
+ if (candidate.trustTier === "validated" && candidate.trustTierDeclared) {
255
+ notes.push("trust tier: validated (front matter declared)");
256
+ }
257
+ for (const risk of scanContentRiskLines(candidate.content).slice(0, 3)) {
258
+ const line = candidate.lines ? candidate.lines.start + risk.line - 1 : risk.line;
259
+ notes.push(`content risk: ${risk.reason} at line ${line}`);
260
+ }
261
+ return notes;
262
+ }
263
+ function orderContextCandidates(candidates) {
264
+ return [
265
+ ...orderContextCandidatesByPath(candidates.filter((candidate) => candidate.direct).sort(compareContextCandidates)),
266
+ ...orderContextCandidatesByPath(candidates.filter((candidate) => !candidate.direct).sort(compareContextCandidates))
267
+ ];
268
+ }
269
+ function orderContextCandidatesByPath(sorted) {
270
+ const byPath = new Map();
271
+ for (const candidate of sorted) {
272
+ byPath.set(candidate.path, [...(byPath.get(candidate.path) ?? []), candidate]);
273
+ }
274
+ const ordered = [];
275
+ while (byPath.size) {
276
+ for (const [candidatePath, pathCandidates] of byPath) {
277
+ const [candidate, ...remaining] = pathCandidates;
278
+ if (candidate) {
279
+ ordered.push(candidate);
280
+ }
281
+ if (remaining.length) {
282
+ byPath.set(candidatePath, remaining);
283
+ }
284
+ else {
285
+ byPath.delete(candidatePath);
286
+ }
287
+ }
288
+ }
289
+ return ordered;
290
+ }
291
+ function compareContextCandidates(left, right) {
292
+ if (left.direct !== right.direct) {
293
+ return left.direct ? -1 : 1;
294
+ }
295
+ return right.score - left.score;
296
+ }
297
+ function packContext(query, candidates, maxChars, mode) {
298
+ const items = [];
299
+ let usedChars = 0;
300
+ let budgetTruncatedItems = 0;
301
+ let budgetSkippedItems = 0;
302
+ for (let index = 0; index < candidates.length; index += 1) {
303
+ const candidate = candidates[index];
304
+ const remaining = maxChars - usedChars;
305
+ if (remaining <= 0) {
306
+ budgetSkippedItems += candidates.length - index;
307
+ break;
308
+ }
309
+ const content = trimToBudget(candidate.content, remaining);
310
+ if (!content) {
311
+ budgetSkippedItems += 1;
312
+ continue;
313
+ }
314
+ if (content.length < candidate.content.length) {
315
+ budgetTruncatedItems += 1;
316
+ }
317
+ usedChars += content.length;
318
+ items.push({
319
+ nodeId: candidate.nodeId,
320
+ documentId: candidate.documentId,
321
+ sectionId: candidate.sectionId,
322
+ anchor: candidate.anchor,
323
+ path: candidate.path,
324
+ title: candidate.title,
325
+ heading: candidate.heading,
326
+ lines: candidate.lines,
327
+ reason: candidate.reason,
328
+ matchedEntities: candidate.matchedEntities,
329
+ edgePath: candidate.edgePath,
330
+ sourceRefs: candidate.sourceRefs,
331
+ riskNotes: candidate.riskNotes,
332
+ content
333
+ });
334
+ }
335
+ return { result: { query, maxChars, usedChars, mode, items }, budgetTruncatedItems, budgetSkippedItems };
336
+ }
337
+ function candidateFromSearchResult(result) {
338
+ return {
339
+ path: result.document.path,
340
+ title: result.document.title,
341
+ heading: result.section?.heading,
342
+ sectionId: result.section?.id,
343
+ anchor: result.section?.anchor,
344
+ lines: result.section ? { start: result.section.startLine, end: result.section.endLine } : undefined,
345
+ reason: result.reason,
346
+ matchedEntities: result.matchedEntities.map(formatMatchedEntity),
347
+ content: result.content,
348
+ nodeId: result.section?.id ?? result.document.id,
349
+ documentId: result.document.id,
350
+ documentStatus: result.document.status,
351
+ trustTier: result.document.trustTier,
352
+ trustTierDeclared: hasDeclaredTrustTier(result.document),
353
+ score: result.score,
354
+ direct: true
355
+ };
356
+ }
357
+ function seedsFromSearchResult(result) {
358
+ const seeds = new Set();
359
+ seeds.add(result.document.id);
360
+ if (result.section) {
361
+ seeds.add(result.section.id);
362
+ }
363
+ for (const entity of result.matchedEntities) {
364
+ seeds.add(entity.id);
365
+ }
366
+ return [...seeds].map((nodeId) => ({ nodeId }));
367
+ }
368
+ function addCandidate(candidates, candidate) {
369
+ const key = candidate.nodeId;
370
+ const existing = candidates.get(key);
371
+ if (!existing || candidate.score > existing.score || (candidate.direct && !existing.direct)) {
372
+ candidates.set(key, candidate);
373
+ }
374
+ }
375
+ function edgeScore(edge) {
376
+ return edge.weight * edge.confidence;
377
+ }
378
+ function expansionPathStep(repository, currentId, edge) {
379
+ const nextId = edge.fromId === currentId ? edge.toId : edge.fromId;
380
+ return {
381
+ fromId: currentId,
382
+ fromLabel: repository.getNode(currentId)?.label ?? currentId,
383
+ edgeFromId: edge.fromId,
384
+ edgeToId: edge.toId,
385
+ edgeKind: edge.kind,
386
+ toId: nextId,
387
+ toLabel: repository.getNode(nextId)?.label ?? nextId,
388
+ traversalDirection: edge.fromId === currentId ? "forward" : "reverse",
389
+ confidence: edge.confidence,
390
+ provenance: edge.provenance
391
+ };
392
+ }
393
+ function formatExpansionStep(step) {
394
+ const edgeLabel = `${step.edgeKind}/${step.provenance}/${step.confidence}`;
395
+ return step.traversalDirection === "forward"
396
+ ? `${step.fromLabel} --${edgeLabel}--> ${step.toLabel}`
397
+ : `${step.fromLabel} <--${edgeLabel}-- ${step.toLabel}`;
398
+ }
399
+ function formatMatchedEntity(entity) {
400
+ return `${entity.name} (${entity.kind})`;
401
+ }
402
+ function trimToBudget(content, maxChars) {
403
+ if (content.length <= maxChars) {
404
+ return content;
405
+ }
406
+ if (maxChars <= 3) {
407
+ return content.slice(0, maxChars);
408
+ }
409
+ return `${content.slice(0, maxChars - 3).trimEnd()}...`.slice(0, maxChars);
410
+ }
411
+ function hasDeclaredTrustTier(document) {
412
+ return typeof document.metadata?.declaredTrustTier === "string";
413
+ }
@@ -0,0 +1,32 @@
1
+ import type { GraphEntity, MDGraphConfig, SearchQueryMode, SearchResult } from "../types.js";
2
+ import { GraphRepository } from "../db/repositories.js";
3
+ type SearchChannel = "definition" | "fts" | "semantic";
4
+ export interface SearchOptions {
5
+ semantic?: boolean;
6
+ queryMode?: SearchQueryMode;
7
+ }
8
+ export interface SearchExplanation {
9
+ query: string;
10
+ limit: number;
11
+ queryMode: SearchQueryMode;
12
+ entityCandidates: string[];
13
+ ftsQuery: string;
14
+ semanticEnabled: boolean;
15
+ semanticActive: boolean;
16
+ ranking: {
17
+ fusion: "rrf";
18
+ fusionK: number;
19
+ channels: SearchChannel[];
20
+ optionalReranker: "none" | "local-hash";
21
+ };
22
+ matchedEntities: Array<{
23
+ name: string;
24
+ kind: GraphEntity["kind"];
25
+ documentFrequency: number;
26
+ }>;
27
+ results: SearchResult[];
28
+ }
29
+ export declare function searchGraph(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): SearchResult[];
30
+ export declare function explainSearchGraph(repository: GraphRepository, config: MDGraphConfig, query: string, limit?: number, options?: SearchOptions): SearchExplanation;
31
+ export declare function extractQueryEntityCandidates(query: string): string[];
32
+ export {};
@@ -0,0 +1,237 @@
1
+ import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
2
+ import { ftsQueryFor } from "../utils/fts.js";
3
+ import { normalizeEntityName } from "../utils/text.js";
4
+ const RRF_K = 60;
5
+ const RRF_SCORE_WEIGHT = 1_000;
6
+ export function searchGraph(repository, config, query, limit = config.search.defaultLimit, options = {}) {
7
+ const entityCandidates = extractQueryEntityCandidates(query);
8
+ const matchedEntities = repository.findEntitiesByNormalizedNames(entityCandidates.map(normalizeEntityName));
9
+ const entityDocumentFrequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
10
+ const definitionRows = repository.findEntityDefinitions(matchedEntities.map((entity) => entity.id));
11
+ const ftsQuery = ftsQueryFor(query);
12
+ const ftsRows = ftsQuery ? repository.searchChunks(ftsQuery, limit * 2) : [];
13
+ const mode = resolveSearchMode(config, options);
14
+ const semanticRows = mode.semanticActive
15
+ ? repository.searchSemanticChunks(embedTextLocal(query, config.embedding.dimensions), config.embedding.provider, config.embedding.model, limit * 2)
16
+ : [];
17
+ const results = [];
18
+ for (const [index, row] of definitionRows.entries()) {
19
+ const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
20
+ results.push({
21
+ channel: "definition",
22
+ rank: index + 1,
23
+ result: {
24
+ document: row.document,
25
+ section: row.section,
26
+ score: adjustScore(200 + row.rank, row.document),
27
+ reason: "definition matched an explicit query entity",
28
+ content: row.chunk.content,
29
+ matchedEntities: matched
30
+ }
31
+ });
32
+ }
33
+ for (const [index, row] of ftsRows.entries()) {
34
+ const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
35
+ const penalty = highFrequencyPenalty(matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold);
36
+ results.push({
37
+ channel: "fts",
38
+ rank: index + 1,
39
+ result: {
40
+ document: row.document,
41
+ section: row.section,
42
+ score: adjustScore(100 - row.rank, row.document, penalty),
43
+ reason: highFrequencyReason("FTS5 content match", matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold),
44
+ content: row.chunk.content,
45
+ matchedEntities: matched
46
+ }
47
+ });
48
+ }
49
+ for (const [index, row] of semanticRows.entries()) {
50
+ const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
51
+ const penalty = highFrequencyPenalty(matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold);
52
+ results.push({
53
+ channel: "semantic",
54
+ rank: index + 1,
55
+ result: {
56
+ document: row.document,
57
+ section: row.section,
58
+ score: adjustScore(80 + row.similarity * 50, row.document, penalty),
59
+ reason: highFrequencyReason(`local semantic vector match (${row.similarity.toFixed(3)})`, matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold),
60
+ content: row.chunk.content,
61
+ matchedEntities: matched,
62
+ semantic: {
63
+ source: "chunk_vector",
64
+ provider: config.embedding.provider,
65
+ model: config.embedding.model,
66
+ confidence: Number(row.similarity.toFixed(4))
67
+ }
68
+ }
69
+ });
70
+ }
71
+ return dedupeResults(applyReciprocalRankFusion(results))
72
+ .sort((a, b) => b.score - a.score)
73
+ .slice(0, limit);
74
+ }
75
+ export function explainSearchGraph(repository, config, query, limit = config.search.defaultLimit, options = {}) {
76
+ const entityCandidates = extractQueryEntityCandidates(query);
77
+ const matchedEntities = repository.findEntitiesByNormalizedNames(entityCandidates.map(normalizeEntityName));
78
+ const frequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
79
+ const mode = resolveSearchMode(config, options);
80
+ const results = searchGraph(repository, config, query, limit, options);
81
+ const channels = channelsForResults(results);
82
+ const semanticActive = mode.semanticActive && channels.includes("semantic");
83
+ return {
84
+ query,
85
+ limit,
86
+ queryMode: mode.queryMode,
87
+ entityCandidates,
88
+ ftsQuery: ftsQueryFor(query),
89
+ semanticEnabled: mode.semanticRequested,
90
+ semanticActive,
91
+ ranking: {
92
+ fusion: "rrf",
93
+ fusionK: RRF_K,
94
+ channels,
95
+ optionalReranker: semanticActive ? "local-hash" : "none"
96
+ },
97
+ matchedEntities: matchedEntities.map((entity) => ({
98
+ name: entity.name,
99
+ kind: entity.kind,
100
+ documentFrequency: frequencies.get(entity.id) ?? 0
101
+ })),
102
+ results
103
+ };
104
+ }
105
+ export function extractQueryEntityCandidates(query) {
106
+ const candidates = query.match(/`([^`]+)`|\b[A-Z][A-Za-z0-9_.]+\b|\b[A-Z][A-Z0-9_]{2,}\b|\/[A-Za-z0-9_./:{}-]+/g) ?? [];
107
+ return candidates.map((candidate) => candidate.replace(/^`|`$/g, "").trim()).filter(Boolean);
108
+ }
109
+ function matchedEntitiesForContent(entities, content) {
110
+ const lowerContent = content.toLowerCase();
111
+ return entities.filter((entity) => lowerContent.includes(entity.name.toLowerCase()) || lowerContent.includes(entity.normalizedName));
112
+ }
113
+ function adjustScore(score, document, entityFrequencyPenalty = 0) {
114
+ return score + trustTierBoost(document.trustTier) + statusBoost(document.status) + entityFrequencyPenalty;
115
+ }
116
+ function highFrequencyPenalty(entities, documentFrequencies, threshold) {
117
+ const highFrequencyCount = highFrequencyEntities(entities, documentFrequencies, threshold).length;
118
+ return highFrequencyCount ? -Math.min(60, highFrequencyCount * 20) : 0;
119
+ }
120
+ function highFrequencyReason(reason, entities, documentFrequencies, threshold) {
121
+ const highFrequency = highFrequencyEntities(entities, documentFrequencies, threshold);
122
+ if (!highFrequency.length) {
123
+ return reason;
124
+ }
125
+ const details = highFrequency
126
+ .map((entity) => `${entity.name} in ${documentFrequencies.get(entity.id) ?? 0} docs`)
127
+ .join(", ");
128
+ return `${reason}; down-ranked high-frequency entity match (${details})`;
129
+ }
130
+ function highFrequencyEntities(entities, documentFrequencies, threshold) {
131
+ return entities.filter((entity) => (documentFrequencies.get(entity.id) ?? 0) > threshold);
132
+ }
133
+ function trustTierBoost(trustTier) {
134
+ switch (trustTier) {
135
+ case "validated":
136
+ return 8;
137
+ case "authored":
138
+ return 5;
139
+ case "generated":
140
+ return -5;
141
+ case "external":
142
+ return -10;
143
+ case "untrusted":
144
+ return -30;
145
+ }
146
+ }
147
+ function statusBoost(status) {
148
+ const normalized = status.trim().toLowerCase();
149
+ if (!normalized || normalized === "active") {
150
+ return 0;
151
+ }
152
+ if (normalized === "deprecated" || normalized === "superseded") {
153
+ return -20;
154
+ }
155
+ if (normalized === "draft" || normalized === "archived") {
156
+ return -8;
157
+ }
158
+ return 0;
159
+ }
160
+ function resolveSearchMode(config, options) {
161
+ const queryMode = options.queryMode ?? (options.semantic ? "semantic" : "auto");
162
+ const semanticRequested = queryMode === "semantic" || (queryMode === "auto" && (options.semantic ?? config.embedding.enabled));
163
+ const semanticActive = semanticRequested && supportsLocalEmbedding({ ...config, embedding: { ...config.embedding, enabled: true } });
164
+ return { queryMode, semanticRequested, semanticActive };
165
+ }
166
+ function applyReciprocalRankFusion(results) {
167
+ const fusionByKey = new Map();
168
+ const seenChannelKeys = new Set();
169
+ for (const item of results) {
170
+ const key = resultKey(item.result);
171
+ const channelKey = `${item.channel}:${key}`;
172
+ if (seenChannelKeys.has(channelKey)) {
173
+ continue;
174
+ }
175
+ seenChannelKeys.add(channelKey);
176
+ const existing = fusionByKey.get(key) ?? { score: 0, channels: [] };
177
+ existing.score += 1 / (RRF_K + item.rank);
178
+ existing.channels.push({ channel: item.channel, rank: item.rank });
179
+ fusionByKey.set(key, existing);
180
+ }
181
+ return results.map((item) => {
182
+ const fusion = fusionByKey.get(resultKey(item.result));
183
+ if (!fusion) {
184
+ return item.result;
185
+ }
186
+ const boost = Number((fusion.score * RRF_SCORE_WEIGHT).toFixed(4));
187
+ return {
188
+ ...item.result,
189
+ score: Number((item.result.score + boost).toFixed(4)),
190
+ reason: mergeReasons(item.result.reason, formatRrfReason(fusion.channels))
191
+ };
192
+ });
193
+ }
194
+ function formatRrfReason(channels) {
195
+ const details = channels
196
+ .sort((left, right) => left.channel.localeCompare(right.channel) || left.rank - right.rank)
197
+ .map((item) => `${item.channel}#${item.rank}`)
198
+ .join(", ");
199
+ return `RRF fusion (${details})`;
200
+ }
201
+ function dedupeResults(results) {
202
+ const bestByKey = new Map();
203
+ for (const result of results) {
204
+ const key = resultKey(result);
205
+ const existing = bestByKey.get(key);
206
+ if (!existing) {
207
+ bestByKey.set(key, { ...result, matchedEntities: [...result.matchedEntities] });
208
+ continue;
209
+ }
210
+ const best = result.score > existing.score ? result : existing;
211
+ bestByKey.set(key, {
212
+ ...best,
213
+ score: Math.max(existing.score, result.score),
214
+ reason: mergeReasons(existing.reason, result.reason),
215
+ matchedEntities: mergeMatchedEntities(existing.matchedEntities, result.matchedEntities),
216
+ semantic: best.semantic ?? existing.semantic ?? result.semantic
217
+ });
218
+ }
219
+ return [...bestByKey.values()];
220
+ }
221
+ function resultKey(result) {
222
+ return result.section?.id ?? result.document.id;
223
+ }
224
+ function channelsForResults(results) {
225
+ const channels = results
226
+ .flatMap((result) => [...result.reason.matchAll(/RRF fusion \(([^)]+)\)/gu)])
227
+ .flatMap((match) => match[1].split(", "))
228
+ .map((detail) => detail.split("#")[0])
229
+ .filter((channel) => channel === "definition" || channel === "fts" || channel === "semantic");
230
+ return [...new Set(channels)];
231
+ }
232
+ function mergeReasons(left, right) {
233
+ return [...new Set([...left.split("; "), ...right.split("; ")].filter(Boolean))].join("; ");
234
+ }
235
+ function mergeMatchedEntities(left, right) {
236
+ return [...new Map([...left, ...right].map((entity) => [entity.id, entity])).values()];
237
+ }
@@ -0,0 +1,10 @@
1
+ import type { TraceStep } from "../types.js";
2
+ import { GraphRepository } from "../db/repositories.js";
3
+ export interface TraceResult {
4
+ from: string;
5
+ to: string;
6
+ found: boolean;
7
+ steps: TraceStep[];
8
+ message?: string;
9
+ }
10
+ export declare function traceNodes(repository: GraphRepository, fromQuery: string, toQuery: string, maxDepth?: number): TraceResult;