@daogee/mdgraph 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README-ZH.md +54 -2
- package/README.md +73 -21
- package/dist/bin/mdgraph.js +136 -19
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/repositories.d.ts +27 -0
- package/dist/db/repositories.js +310 -6
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +14 -5
- package/dist/evaluation/retrieval-eval.js +44 -6
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +17 -4
- package/dist/index.js +9 -4
- package/dist/indexer.js +20 -2
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +16 -7
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +93 -9
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +31 -2
- package/dist/query/context-builder.js +162 -12
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +77 -13
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +131 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +75 -10
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/docs/EN/Agent_Integration.md +1 -1
- package/docs/EN/Architecture.md +39 -16
- package/docs/EN/Evaluation_Questions.md +21 -5
- package/docs/EN/Operations.md +91 -0
- package/docs/EN/Output_Contracts.md +41 -7
- package/docs/EN/Public_Contracts.md +23 -16
- package/docs/EN/Public_Contracts_1.0.md +28 -18
- package/docs/EN/README.md +23 -0
- package/docs/EN/Release_Checklist.md +26 -13
- package/docs/EN/Retrieval_and_Context.md +112 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +1 -1
- package/docs/ZH/Architecture.md +39 -19
- package/docs/ZH/Evaluation_Questions.md +22 -6
- package/docs/ZH/Operations.md +91 -0
- package/docs/ZH/Output_Contracts.md +41 -7
- package/docs/ZH/Public_Contracts.md +22 -15
- package/docs/ZH/Public_Contracts_1.0.md +27 -17
- package/docs/ZH/README.md +23 -0
- package/docs/ZH/Release_Checklist.md +26 -13
- package/docs/ZH/Retrieval_and_Context.md +112 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +44 -18
|
@@ -1,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 {
|
|
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;
|
|
@@ -67,8 +68,9 @@ export interface EvaluationCaseResult {
|
|
|
67
68
|
searchFusion: "rrf";
|
|
68
69
|
searchChannels: string[];
|
|
69
70
|
semanticActive: boolean;
|
|
70
|
-
optionalReranker:
|
|
71
|
-
|
|
71
|
+
optionalReranker: string;
|
|
72
|
+
semanticDiagnostic?: EmbeddingDiagnostic;
|
|
73
|
+
contextPackingStrategy: ContextPackingStrategy;
|
|
72
74
|
};
|
|
73
75
|
};
|
|
74
76
|
metrics: EvaluationMetrics;
|
|
@@ -87,12 +89,13 @@ export interface EvaluationSummary {
|
|
|
87
89
|
export interface EvaluationRankingReport {
|
|
88
90
|
queryMode: SearchQueryMode;
|
|
89
91
|
searchFusion: "rrf";
|
|
90
|
-
contextPackingStrategy:
|
|
91
|
-
optionalReranker:
|
|
92
|
+
contextPackingStrategy: ContextPackingStrategy;
|
|
93
|
+
optionalReranker: string;
|
|
92
94
|
semanticActiveCases: number;
|
|
93
95
|
searchChannels: string[];
|
|
94
96
|
rankingReasonCoverage: boolean;
|
|
95
97
|
averageContextDiversity: number;
|
|
98
|
+
semanticDiagnostics?: EmbeddingDiagnostic[];
|
|
96
99
|
}
|
|
97
100
|
export interface EvaluationReport {
|
|
98
101
|
querySet: string;
|
|
@@ -113,3 +116,9 @@ export declare function evaluateRetrieval(repository: GraphRepository, config: M
|
|
|
113
116
|
querySet?: string;
|
|
114
117
|
queryMode?: SearchQueryMode;
|
|
115
118
|
}): EvaluationReport;
|
|
119
|
+
export declare function evaluateRetrievalAsync(repository: GraphRepository, config: MDGraphConfig, options?: {
|
|
120
|
+
cases?: EvaluationCase[];
|
|
121
|
+
limit?: number;
|
|
122
|
+
querySet?: string;
|
|
123
|
+
queryMode?: SearchQueryMode;
|
|
124
|
+
}): Promise<EvaluationReport>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { performance } from "node:perf_hooks";
|
|
2
|
-
import { CONTEXT_PACKING_STRATEGY, buildContext } from "../query/context-builder.js";
|
|
3
|
-
import { explainSearchGraph } from "../query/search.js";
|
|
2
|
+
import { CONTEXT_PACKING_STRATEGY, buildContext, buildContextFromSearchResults } from "../query/context-builder.js";
|
|
3
|
+
import { explainSearchGraph, explainSearchGraphAsync } from "../query/search.js";
|
|
4
4
|
import { traceNodes } from "../query/trace.js";
|
|
5
5
|
import { slugifyHeading } from "../utils/text.js";
|
|
6
6
|
export const EVALUATION_QUERY_SET_NAMES = ["alpha", "cjk"];
|
|
@@ -243,12 +243,23 @@ export function evaluateRetrieval(repository, config, options = {}) {
|
|
|
243
243
|
function evaluateCase(repository, config, evaluationCase, limit, queryMode) {
|
|
244
244
|
const start = performance.now();
|
|
245
245
|
const searchExplanation = explainSearchGraph(repository, config, evaluationCase.query, limit, { queryMode });
|
|
246
|
-
const searchResults = searchExplanation.results;
|
|
247
246
|
const context = buildContext(repository, config, evaluationCase.query, { debug: true, searchOptions: { queryMode } });
|
|
248
247
|
const trace = evaluationCase.trace
|
|
249
248
|
? traceNodes(repository, evaluationCase.trace.from, evaluationCase.trace.to, evaluationCase.trace.depth ?? config.search.maxDepth)
|
|
250
249
|
: undefined;
|
|
251
|
-
|
|
250
|
+
return evaluationCaseResult(repository, evaluationCase, queryMode, searchExplanation, context, trace, performance.now() - start);
|
|
251
|
+
}
|
|
252
|
+
async function evaluateCaseAsync(repository, config, evaluationCase, limit, queryMode) {
|
|
253
|
+
const start = performance.now();
|
|
254
|
+
const searchExplanation = await explainSearchGraphAsync(repository, config, evaluationCase.query, limit, { queryMode });
|
|
255
|
+
const context = buildContextFromSearchResults(repository, config, evaluationCase.query, searchExplanation.results, { debug: true, searchOptions: { queryMode } }, searchExplanation.semanticDiagnostic);
|
|
256
|
+
const trace = evaluationCase.trace
|
|
257
|
+
? traceNodes(repository, evaluationCase.trace.from, evaluationCase.trace.to, evaluationCase.trace.depth ?? config.search.maxDepth)
|
|
258
|
+
: undefined;
|
|
259
|
+
return evaluationCaseResult(repository, evaluationCase, queryMode, searchExplanation, context, trace, performance.now() - start);
|
|
260
|
+
}
|
|
261
|
+
function evaluationCaseResult(repository, evaluationCase, queryMode, searchExplanation, context, trace, latencyMs) {
|
|
262
|
+
const searchResults = searchExplanation.results;
|
|
252
263
|
const searchDocuments = unique(searchResults.map((result) => result.document.path));
|
|
253
264
|
const contextItems = context.items.map((item) => ({ path: item.path, heading: item.heading, reason: item.reason }));
|
|
254
265
|
const matchedEntities = unique(searchResults.flatMap((result) => result.matchedEntities.map((entity) => entity.name)));
|
|
@@ -290,6 +301,7 @@ function evaluateCase(repository, config, evaluationCase, limit, queryMode) {
|
|
|
290
301
|
searchChannels: searchExplanation.ranking.channels,
|
|
291
302
|
semanticActive: searchExplanation.semanticActive,
|
|
292
303
|
optionalReranker: searchExplanation.ranking.optionalReranker,
|
|
304
|
+
semanticDiagnostic: searchExplanation.semanticDiagnostic,
|
|
293
305
|
contextPackingStrategy: context.debug?.packingStrategy ?? CONTEXT_PACKING_STRATEGY
|
|
294
306
|
}
|
|
295
307
|
},
|
|
@@ -327,6 +339,24 @@ function calculateMetrics(input) {
|
|
|
327
339
|
contextDiversity: input.context.debug?.packingDiversityRatio ?? 0
|
|
328
340
|
};
|
|
329
341
|
}
|
|
342
|
+
export async function evaluateRetrievalAsync(repository, config, options = {}) {
|
|
343
|
+
const querySet = options.querySet ?? "alpha";
|
|
344
|
+
const queryMode = options.queryMode ?? "auto";
|
|
345
|
+
const cases = options.cases ?? evaluationCasesForQuerySet(querySet);
|
|
346
|
+
const limit = options.limit ?? config.search.defaultLimit;
|
|
347
|
+
const results = [];
|
|
348
|
+
for (const evaluationCase of cases) {
|
|
349
|
+
results.push(await evaluateCaseAsync(repository, config, evaluationCase, limit, queryMode));
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
querySet,
|
|
353
|
+
limit,
|
|
354
|
+
ranking: summarizeRanking(results, queryMode),
|
|
355
|
+
generatedAt: new Date().toISOString(),
|
|
356
|
+
summary: summarize(results),
|
|
357
|
+
cases: results
|
|
358
|
+
};
|
|
359
|
+
}
|
|
330
360
|
function summarize(results) {
|
|
331
361
|
const count = results.length || 1;
|
|
332
362
|
return {
|
|
@@ -345,16 +375,24 @@ function summarizeRanking(results, queryMode) {
|
|
|
345
375
|
const count = results.length || 1;
|
|
346
376
|
const rerankers = results.map((result) => result.observed.ranking.optionalReranker);
|
|
347
377
|
const channels = results.flatMap((result) => result.observed.ranking.searchChannels);
|
|
348
|
-
|
|
378
|
+
const semanticDiagnostics = uniqueDiagnostics(results.flatMap((result) => (result.observed.ranking.semanticDiagnostic ? [result.observed.ranking.semanticDiagnostic] : [])));
|
|
379
|
+
const report = {
|
|
349
380
|
queryMode,
|
|
350
381
|
searchFusion: "rrf",
|
|
351
382
|
contextPackingStrategy: CONTEXT_PACKING_STRATEGY,
|
|
352
|
-
optionalReranker: rerankers.
|
|
383
|
+
optionalReranker: rerankers.find((reranker) => reranker !== "none") ?? "none",
|
|
353
384
|
semanticActiveCases: results.filter((result) => result.observed.ranking.semanticActive).length,
|
|
354
385
|
searchChannels: [...new Set(channels)].sort(),
|
|
355
386
|
rankingReasonCoverage: results.every((result) => result.metrics.rankingReasonCoverage),
|
|
356
387
|
averageContextDiversity: average(results.map((result) => result.metrics.contextDiversity), count)
|
|
357
388
|
};
|
|
389
|
+
return semanticDiagnostics.length ? { ...report, semanticDiagnostics } : report;
|
|
390
|
+
}
|
|
391
|
+
function uniqueDiagnostics(diagnostics) {
|
|
392
|
+
return [...new Map(diagnostics.map((diagnostic) => [
|
|
393
|
+
`${diagnostic.provider}:${diagnostic.code}:${diagnostic.message}`,
|
|
394
|
+
diagnostic
|
|
395
|
+
])).values()];
|
|
358
396
|
}
|
|
359
397
|
function casePassed(metrics) {
|
|
360
398
|
return metrics.topKDocumentRecall === 1
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare const STRUCTURED_QUERY_EVALUATION_VERSION = 1;
|
|
2
|
+
export declare const STRUCTURED_QUERY_GATES: {
|
|
3
|
+
readonly minimumCaseAccuracy: 1;
|
|
4
|
+
readonly requireParameterizedExecution: true;
|
|
5
|
+
readonly requireInjectionIsolation: true;
|
|
6
|
+
};
|
|
7
|
+
export interface StructuredQueryEvaluationReport {
|
|
8
|
+
evaluationVersion: typeof STRUCTURED_QUERY_EVALUATION_VERSION;
|
|
9
|
+
cases: Array<{
|
|
10
|
+
id: string;
|
|
11
|
+
query: string;
|
|
12
|
+
expectedPaths: string[];
|
|
13
|
+
observedPaths: string[];
|
|
14
|
+
strategy: "parameterized-sql" | "parameterized-hybrid-doctor";
|
|
15
|
+
parameterCount: number;
|
|
16
|
+
passed: boolean;
|
|
17
|
+
latencyMs: number;
|
|
18
|
+
}>;
|
|
19
|
+
caseAccuracy: number;
|
|
20
|
+
parameterizedExecution: boolean;
|
|
21
|
+
injectionIsolation: boolean;
|
|
22
|
+
maximumLatencyMs: number;
|
|
23
|
+
gates: typeof STRUCTURED_QUERY_GATES;
|
|
24
|
+
passed: boolean;
|
|
25
|
+
elapsedMs: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function runStructuredQueryEvaluation(): Promise<StructuredQueryEvaluationReport>;
|
|
@@ -0,0 +1,156 @@
|
|
|
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 { openDatabase } from "../db/connection.js";
|
|
6
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
7
|
+
import { indexProject } from "../indexer.js";
|
|
8
|
+
import { executeStructuredQuery } from "../query/structured-query-executor.js";
|
|
9
|
+
export const STRUCTURED_QUERY_EVALUATION_VERSION = 1;
|
|
10
|
+
export const STRUCTURED_QUERY_GATES = {
|
|
11
|
+
minimumCaseAccuracy: 1,
|
|
12
|
+
requireParameterizedExecution: true,
|
|
13
|
+
requireInjectionIsolation: true
|
|
14
|
+
};
|
|
15
|
+
const CASES = [
|
|
16
|
+
{
|
|
17
|
+
id: "accepted-auth-adr",
|
|
18
|
+
query: "type:adr AND status:accepted AND edge.IMPLEMENTS ~ auth",
|
|
19
|
+
expectedPaths: ["docs/adrs/auth.md"],
|
|
20
|
+
expectedStrategy: "parameterized-sql"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "active-dead-link-runbook",
|
|
24
|
+
query: "type:runbook AND status:active AND health:dead_link",
|
|
25
|
+
expectedPaths: ["docs/runbooks/auth.md"],
|
|
26
|
+
expectedStrategy: "parameterized-hybrid-doctor"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
id: "recent-documents",
|
|
30
|
+
query: "updated >= 2026-07-01 ORDER BY updated ASC, path ASC",
|
|
31
|
+
expectedPaths: ["docs/adrs/auth.md", "docs/runbooks/auth.md"],
|
|
32
|
+
expectedStrategy: "parameterized-sql"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: "boolean-union",
|
|
36
|
+
query: "status:accepted OR health:dead_link ORDER BY path",
|
|
37
|
+
expectedPaths: ["docs/adrs/auth.md", "docs/runbooks/auth.md"],
|
|
38
|
+
expectedStrategy: "parameterized-hybrid-doctor"
|
|
39
|
+
}
|
|
40
|
+
];
|
|
41
|
+
export async function runStructuredQueryEvaluation() {
|
|
42
|
+
const started = performance.now();
|
|
43
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mdgraph-structured-query-eval-"));
|
|
44
|
+
try {
|
|
45
|
+
writeEvaluationFixture(root);
|
|
46
|
+
await indexProject(root, { full: true });
|
|
47
|
+
const repository = new GraphRepository(openDatabase(root));
|
|
48
|
+
try {
|
|
49
|
+
const cases = [];
|
|
50
|
+
for (const evaluationCase of CASES) {
|
|
51
|
+
const caseStarted = performance.now();
|
|
52
|
+
const result = await executeStructuredQuery(repository, root, evaluationCase.query);
|
|
53
|
+
const observedPaths = result.items.map((item) => item.document.path);
|
|
54
|
+
cases.push({
|
|
55
|
+
id: evaluationCase.id,
|
|
56
|
+
query: evaluationCase.query,
|
|
57
|
+
expectedPaths: evaluationCase.expectedPaths,
|
|
58
|
+
observedPaths,
|
|
59
|
+
strategy: result.execution.strategy,
|
|
60
|
+
parameterCount: result.execution.parameterCount,
|
|
61
|
+
passed: arraysEqual(observedPaths, evaluationCase.expectedPaths)
|
|
62
|
+
&& result.execution.strategy === evaluationCase.expectedStrategy,
|
|
63
|
+
latencyMs: elapsed(caseStarted)
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const countsBeforeInjection = repository.counts();
|
|
67
|
+
const injection = await executeStructuredQuery(repository, root, "title = '\" OR 1=1 --'");
|
|
68
|
+
const injectionIsolation = injection.total === 0
|
|
69
|
+
&& JSON.stringify(repository.counts()) === JSON.stringify(countsBeforeInjection);
|
|
70
|
+
const caseAccuracy = ratio(cases.filter((item) => item.passed).length, cases.length);
|
|
71
|
+
const parameterizedExecution = cases.every((item) => item.parameterCount > 0);
|
|
72
|
+
const maximumLatencyMs = Math.max(...cases.map((item) => item.latencyMs), 0);
|
|
73
|
+
const passed = caseAccuracy >= STRUCTURED_QUERY_GATES.minimumCaseAccuracy
|
|
74
|
+
&& (!STRUCTURED_QUERY_GATES.requireParameterizedExecution || parameterizedExecution)
|
|
75
|
+
&& (!STRUCTURED_QUERY_GATES.requireInjectionIsolation || injectionIsolation);
|
|
76
|
+
return {
|
|
77
|
+
evaluationVersion: STRUCTURED_QUERY_EVALUATION_VERSION,
|
|
78
|
+
cases,
|
|
79
|
+
caseAccuracy,
|
|
80
|
+
parameterizedExecution,
|
|
81
|
+
injectionIsolation,
|
|
82
|
+
maximumLatencyMs,
|
|
83
|
+
gates: STRUCTURED_QUERY_GATES,
|
|
84
|
+
passed,
|
|
85
|
+
elapsedMs: elapsed(started)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
repository.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function writeEvaluationFixture(root) {
|
|
97
|
+
writeDocument(root, "docs/adrs/auth.md", "2026-07-01T00:00:00.000Z", `---
|
|
98
|
+
title: Auth Decision
|
|
99
|
+
type: adr
|
|
100
|
+
status: accepted
|
|
101
|
+
tags: [security, auth]
|
|
102
|
+
defines: [AuthDecision]
|
|
103
|
+
implements: [src/auth/service.ts]
|
|
104
|
+
---
|
|
105
|
+
# Auth Decision
|
|
106
|
+
|
|
107
|
+
Accepted authentication architecture.
|
|
108
|
+
`);
|
|
109
|
+
writeDocument(root, "docs/adrs/next.md", "2026-06-01T00:00:00.000Z", `---
|
|
110
|
+
title: Next Decision
|
|
111
|
+
type: adr
|
|
112
|
+
status: proposed
|
|
113
|
+
defines: [NextDecision]
|
|
114
|
+
---
|
|
115
|
+
# Next Decision
|
|
116
|
+
|
|
117
|
+
Proposed architecture.
|
|
118
|
+
`);
|
|
119
|
+
writeDocument(root, "docs/runbooks/auth.md", "2026-07-15T00:00:00.000Z", `---
|
|
120
|
+
title: Auth Runbook
|
|
121
|
+
type: runbook
|
|
122
|
+
status: active
|
|
123
|
+
defines: [AuthRunbook]
|
|
124
|
+
---
|
|
125
|
+
# Auth Runbook
|
|
126
|
+
|
|
127
|
+
[Missing recovery details](../missing.md)
|
|
128
|
+
`);
|
|
129
|
+
writeDocument(root, "docs/runbooks/healthy.md", "2026-05-01T00:00:00.000Z", `---
|
|
130
|
+
title: Healthy Runbook
|
|
131
|
+
type: runbook
|
|
132
|
+
status: active
|
|
133
|
+
defines: [HealthyRunbook]
|
|
134
|
+
depends_on: [Auth Decision]
|
|
135
|
+
---
|
|
136
|
+
# Healthy Runbook
|
|
137
|
+
|
|
138
|
+
See [[Auth Decision]].
|
|
139
|
+
`);
|
|
140
|
+
}
|
|
141
|
+
function writeDocument(root, relativePath, modifiedAt, content) {
|
|
142
|
+
const target = path.join(root, relativePath);
|
|
143
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
144
|
+
fs.writeFileSync(target, content, "utf8");
|
|
145
|
+
const modified = new Date(modifiedAt);
|
|
146
|
+
fs.utimesSync(target, modified, modified);
|
|
147
|
+
}
|
|
148
|
+
function arraysEqual(left, right) {
|
|
149
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
150
|
+
}
|
|
151
|
+
function ratio(numerator, denominator) {
|
|
152
|
+
return denominator ? Number((numerator / denominator).toFixed(4)) : 0;
|
|
153
|
+
}
|
|
154
|
+
function elapsed(started) {
|
|
155
|
+
return Number((performance.now() - started).toFixed(2));
|
|
156
|
+
}
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { normalizeEntityName, uniqueStrings } from "../utils/text.js";
|
|
2
|
-
const apiRoutePattern = /\b(?:GET|POST|PUT|PATCH|DELETE)\s+\/[
|
|
2
|
+
const apiRoutePattern = /\b(?:GET|POST|PUT|PATCH|DELETE)\s+\/[\p{L}\p{N}_./:{}-]+|(?<![\p{L}\p{N}_@.:\/-])\/[\p{L}\p{N}_./:{}-]+/gu;
|
|
3
3
|
const errorCodePattern = /\b(?:[A-Z][A-Za-z0-9]+Error|ERR_[A-Z0-9_]+|[A-Z]+_[0-9]{3,}|[A-Z]+_[A-Z0-9_]*ERROR[A-Z0-9_]*)\b/g;
|
|
4
|
-
const
|
|
5
|
-
const
|
|
4
|
+
const proseConfigKeyPattern = /(?<![\p{L}\p{N}_])(?:[A-Z][A-Z0-9]*_[A-Z0-9_]+|[A-Z](?=[A-Z0-9_]{2,}(?![\p{L}\p{N}_]))[A-Z0-9_]*\d[A-Z0-9_]*|[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,}|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+(?:[._][\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+)+)(?![\p{L}\p{N}_])/gu;
|
|
5
|
+
const structuredConfigKeyPattern = /(?<![\p{L}\p{N}_])(?:[A-Z][A-Z0-9_]{2,}|[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,}|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+(?:[._][\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+)+)(?![\p{L}\p{N}_])/gu;
|
|
6
|
+
const filePathPattern = /(?:^|\s)([\p{L}\p{N}_@.-]+\/[\p{L}\p{N}_@./-]+\.(?:ts|tsx|js|jsx|md|mdx|json|yaml|yml|toml|rs|go|py|java|cs|sql))/gu;
|
|
6
7
|
const commandPattern = /\b(?:npm|pnpm|yarn|go|cargo|docker|kubectl|node|npx)\s+[^\n`]+/g;
|
|
7
|
-
const functionPattern =
|
|
8
|
-
const
|
|
8
|
+
const functionPattern = /(?<![\p{L}\p{N}_$])[\p{L}_$][\p{L}\p{N}\p{M}_$]*(?:\.[\p{L}_$][\p{L}\p{N}\p{M}_$]*)?\(\)/gu;
|
|
9
|
+
const codeDeclarationPattern = /\b(?:class|interface|type|enum|namespace|module)\s+([\p{L}_$][\p{L}\p{N}\p{M}_$]*)/gu;
|
|
10
|
+
const codeTypeReferencePattern = /\b(?:new|extends|implements|instanceof)\s+([\p{L}_$][\p{L}\p{N}\p{M}_$]*)/gu;
|
|
11
|
+
const latinSymbolNamePattern = /^[A-Z][A-Za-z0-9]+(?:\.[A-Za-z_$][\w$]*)?$/;
|
|
12
|
+
const cjkSymbolNamePattern = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}][\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{N}_-]{1,63}$/u;
|
|
13
|
+
const apiRouteNamePattern = /^(?:(?:GET|POST|PUT|PATCH|DELETE)\s+)?\/[\p{L}\p{N}_./:{}-]+$/u;
|
|
14
|
+
const configKeyNamePattern = /^(?:[A-Z][A-Z0-9_]{2,}|[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*){2,}|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+(?:[._][\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+)+)$/u;
|
|
15
|
+
const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
|
9
16
|
export function extractEntities(document, config) {
|
|
10
17
|
const stopEntities = new Set(config.entities.stopEntities.map(normalizeEntityName));
|
|
11
18
|
const entities = [];
|
|
@@ -26,17 +33,17 @@ export function extractEntities(document, config) {
|
|
|
26
33
|
}
|
|
27
34
|
}
|
|
28
35
|
for (const snippet of document.inlineCode) {
|
|
29
|
-
for (const name of extractStructuredNames(snippet.value,
|
|
36
|
+
for (const name of extractStructuredNames(snippet.value, "inline")) {
|
|
30
37
|
pushEntity(entities, name, "reference", "inline_code", 0.75, snippet.sectionId, stopEntities, false);
|
|
31
38
|
}
|
|
32
39
|
}
|
|
33
40
|
for (const snippet of document.codeBlocks) {
|
|
34
|
-
for (const name of extractStructuredNames(snippet.value,
|
|
41
|
+
for (const name of extractStructuredNames(snippet.value, "code")) {
|
|
35
42
|
pushEntity(entities, name, "reference", "code_block", 0.7, snippet.sectionId, stopEntities, false);
|
|
36
43
|
}
|
|
37
44
|
}
|
|
38
45
|
for (const link of document.markdownLinks) {
|
|
39
|
-
for (const name of extractStructuredNames(`${link.text} ${link.url}`,
|
|
46
|
+
for (const name of extractStructuredNames(`${link.text} ${link.url}`, "link")) {
|
|
40
47
|
pushEntity(entities, name, "reference", "markdown_link", 0.7, link.sectionId, stopEntities, false);
|
|
41
48
|
}
|
|
42
49
|
}
|
|
@@ -50,7 +57,7 @@ export function extractEntities(document, config) {
|
|
|
50
57
|
}
|
|
51
58
|
export function inferEntityKind(name) {
|
|
52
59
|
const trimmed = name.trim();
|
|
53
|
-
if (
|
|
60
|
+
if (apiRouteNamePattern.test(trimmed)) {
|
|
54
61
|
return "api_route";
|
|
55
62
|
}
|
|
56
63
|
if (filePathPattern.test(` ${trimmed}`)) {
|
|
@@ -66,7 +73,7 @@ export function inferEntityKind(name) {
|
|
|
66
73
|
return "error_code";
|
|
67
74
|
}
|
|
68
75
|
errorCodePattern.lastIndex = 0;
|
|
69
|
-
if (
|
|
76
|
+
if (configKeyNamePattern.test(trimmed)) {
|
|
70
77
|
return "config_key";
|
|
71
78
|
}
|
|
72
79
|
if (/^@?[a-z0-9_.-]+\/[a-z0-9_.-]+$/.test(trimmed)) {
|
|
@@ -83,7 +90,7 @@ function pushEntity(target, rawName, role, provenance, confidence, sectionId, st
|
|
|
83
90
|
return;
|
|
84
91
|
}
|
|
85
92
|
const kind = inferEntityKind(name);
|
|
86
|
-
if (!allowStopEntity &&
|
|
93
|
+
if (!allowStopEntity && stopEntities.has(normalizeEntityName(name))) {
|
|
87
94
|
return;
|
|
88
95
|
}
|
|
89
96
|
target.push({ name, kind, role, provenance, confidence, sectionId });
|
|
@@ -93,7 +100,7 @@ function extractDeclaredDefinitionNames(content) {
|
|
|
93
100
|
for (const match of content.matchAll(/[-*]\s+`([^`]+)`/g)) {
|
|
94
101
|
names.push(match[1]);
|
|
95
102
|
}
|
|
96
|
-
for (const match of content.matchAll(/^[-*]\s+([
|
|
103
|
+
for (const match of content.matchAll(/^[-*]\s+([\p{L}\p{N}_.:/-]+)\s*:/gmu)) {
|
|
97
104
|
names.push(match[1]);
|
|
98
105
|
}
|
|
99
106
|
return uniqueStrings(names);
|
|
@@ -102,23 +109,30 @@ function extractHighConfidenceReferences(content) {
|
|
|
102
109
|
return uniqueStrings([
|
|
103
110
|
...matches(content, apiRoutePattern),
|
|
104
111
|
...matches(content, errorCodePattern),
|
|
105
|
-
...
|
|
112
|
+
...extractConfigKeys(content, proseConfigKeyPattern)
|
|
106
113
|
]);
|
|
107
114
|
}
|
|
108
|
-
function extractStructuredNames(content,
|
|
115
|
+
function extractStructuredNames(content, source) {
|
|
109
116
|
const names = [
|
|
110
117
|
...matches(content, apiRoutePattern),
|
|
111
118
|
...matches(content, errorCodePattern),
|
|
112
|
-
...
|
|
119
|
+
...extractConfigKeys(content, structuredConfigKeyPattern),
|
|
113
120
|
...matches(content, commandPattern),
|
|
114
121
|
...matches(content, functionPattern),
|
|
115
122
|
...matches(content, filePathPattern, 1)
|
|
116
123
|
];
|
|
117
|
-
if (
|
|
118
|
-
names.push(
|
|
124
|
+
if (source === "inline" && isStandaloneInlineSymbol(content)) {
|
|
125
|
+
names.push(cleanupName(content));
|
|
126
|
+
}
|
|
127
|
+
if (source === "code") {
|
|
128
|
+
names.push(...matches(content, codeDeclarationPattern, 1));
|
|
129
|
+
names.push(...matches(content, codeTypeReferencePattern, 1));
|
|
119
130
|
}
|
|
120
131
|
return uniqueStrings(names);
|
|
121
132
|
}
|
|
133
|
+
function extractConfigKeys(content, pattern) {
|
|
134
|
+
return matches(content, pattern).filter((name) => !HTTP_METHODS.has(name));
|
|
135
|
+
}
|
|
122
136
|
function matches(content, pattern, group = 0) {
|
|
123
137
|
pattern.lastIndex = 0;
|
|
124
138
|
const result = [...content.matchAll(pattern)].map((match) => match[group] ?? match[0]);
|
|
@@ -130,11 +144,17 @@ function isDefinesHeading(heading) {
|
|
|
130
144
|
}
|
|
131
145
|
function looksLikeEntity(value) {
|
|
132
146
|
const trimmed = cleanupName(value);
|
|
133
|
-
return Boolean(trimmed) && (
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
147
|
+
return Boolean(trimmed) && (apiRouteNamePattern.test(trimmed) ||
|
|
148
|
+
latinSymbolNamePattern.test(trimmed) ||
|
|
149
|
+
configKeyNamePattern.test(trimmed) ||
|
|
150
|
+
functionPatternMatches(trimmed));
|
|
151
|
+
}
|
|
152
|
+
function isStandaloneInlineSymbol(value) {
|
|
153
|
+
const trimmed = cleanupName(value);
|
|
154
|
+
return latinSymbolNamePattern.test(trimmed) || cjkSymbolNamePattern.test(trimmed);
|
|
155
|
+
}
|
|
156
|
+
function functionPatternMatches(value) {
|
|
157
|
+
return matches(value, functionPattern).some((match) => match === value);
|
|
138
158
|
}
|
|
139
159
|
function cleanupName(value) {
|
|
140
160
|
return value.trim().replace(/^`|`$/g, "").replace(/[.,;:]$/g, "");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { EDGE_WEIGHTS } from "../types.js";
|
|
2
2
|
import { LinkResolver } from "../resolution/link-resolver.js";
|
|
3
|
-
import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
|
|
4
3
|
import { stableId } from "../utils/id.js";
|
|
5
4
|
import { estimateTokens, normalizeEntityName, normalizePath } from "../utils/text.js";
|
|
6
5
|
import { extractEntities, inferEntityKind } from "./entity-extractor.js";
|
|
@@ -13,10 +12,8 @@ export function buildGraphRecords(documents, config) {
|
|
|
13
12
|
const entities = [];
|
|
14
13
|
const sourceRefs = [];
|
|
15
14
|
const edges = [];
|
|
16
|
-
const vectors = [];
|
|
17
15
|
const entityByKey = new Map();
|
|
18
16
|
const sourceRefByPath = new Map();
|
|
19
|
-
const shouldEmbed = supportsLocalEmbedding(config);
|
|
20
17
|
for (const document of documents) {
|
|
21
18
|
graphDocuments.push({
|
|
22
19
|
id: document.id,
|
|
@@ -26,7 +23,7 @@ export function buildGraphRecords(documents, config) {
|
|
|
26
23
|
status: document.frontmatter.status ?? "active",
|
|
27
24
|
hash: document.hash,
|
|
28
25
|
trustTier: document.frontmatter.trust_tier ?? "authored",
|
|
29
|
-
updatedAt:
|
|
26
|
+
updatedAt: document.updatedAt,
|
|
30
27
|
indexedAt: now,
|
|
31
28
|
metadata: {
|
|
32
29
|
declaredTrustTier: document.frontmatter.trust_tier,
|
|
@@ -46,16 +43,6 @@ export function buildGraphRecords(documents, config) {
|
|
|
46
43
|
metadata: { heading: section.heading, anchor: section.anchor }
|
|
47
44
|
};
|
|
48
45
|
chunks.push(chunk);
|
|
49
|
-
if (shouldEmbed) {
|
|
50
|
-
vectors.push({
|
|
51
|
-
chunkId: chunk.id,
|
|
52
|
-
provider: config.embedding.provider,
|
|
53
|
-
model: config.embedding.model,
|
|
54
|
-
dimensions: config.embedding.dimensions,
|
|
55
|
-
vector: embedTextLocal(chunk.content, config.embedding.dimensions),
|
|
56
|
-
createdAt: now
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
46
|
edges.push(makeEdge(section.id, chunk.id, "CONTAINS", "heading", 1, now));
|
|
60
47
|
}
|
|
61
48
|
for (const extracted of extractEntities(document, config)) {
|
|
@@ -88,7 +75,7 @@ export function buildGraphRecords(documents, config) {
|
|
|
88
75
|
sourceRefs: dedupeById(sourceRefs),
|
|
89
76
|
edges: dedupeEdges(edges),
|
|
90
77
|
chunks: dedupeById(chunks),
|
|
91
|
-
vectors:
|
|
78
|
+
vectors: []
|
|
92
79
|
};
|
|
93
80
|
}
|
|
94
81
|
function addSourceRefEdges(document, paths, kind, sourceRefs, sourceRefByPath, edges, now) {
|
|
@@ -163,6 +150,3 @@ function dedupeById(items) {
|
|
|
163
150
|
function dedupeEdges(edges) {
|
|
164
151
|
return [...new Map(edges.map((edge) => [`${edge.fromId}:${edge.toId}:${edge.kind}:${edge.provenance}`, edge])).values()];
|
|
165
152
|
}
|
|
166
|
-
function dedupeVectors(vectors) {
|
|
167
|
-
return [...new Map(vectors.map((vector) => [vector.chunkId, vector])).values()];
|
|
168
|
-
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export { createGraphBundle, verifyGraphBundle, sourceSnapshot, hashCanonical, ca
|
|
|
5
5
|
export { openDatabase } from "./db/connection.js";
|
|
6
6
|
export { GraphRepository } from "./db/repositories.js";
|
|
7
7
|
export { generateGraphDiff, formatGraphDiff } from "./diff/graph-diff.js";
|
|
8
|
-
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
8
|
+
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluateRetrievalAsync, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
9
9
|
export { buildMermaidTraceExport, formatTraceMermaid } from "./export/diagram.js";
|
|
10
10
|
export { buildGraphJsonExport, formatGraphJsonVerification, graphJsonHash, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "./export/graphjson.js";
|
|
11
11
|
export { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "./export/markdown-index.js";
|
|
@@ -16,13 +16,26 @@ export { indexProject } from "./indexer.js";
|
|
|
16
16
|
export { MCPServer, startStdioMcpServer } from "./mcp/server.js";
|
|
17
17
|
export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
18
18
|
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
|
-
export { buildContext } from "./query/context-builder.js";
|
|
20
|
-
export {
|
|
19
|
+
export { CONTEXT_PACKING_STRATEGIES, CONTEXT_PACKING_STRATEGY, DEFAULT_MMR_LAMBDA, buildContext, buildContextAsync } from "./query/context-builder.js";
|
|
20
|
+
export type { ContextBuildOptions, ContextDebug, ContextPackingInfo, ContextPackingSelection, ContextPackingSimilarity, ContextPackingStrategy, ContextResult } from "./query/context-builder.js";
|
|
21
|
+
export { explainSearchGraph, explainSearchGraphAsync, searchGraph, searchGraphAsync } from "./query/search.js";
|
|
21
22
|
export { traceNodes } from "./query/trace.js";
|
|
23
|
+
export { executeStructuredQuery, StructuredQueryExecutionError } from "./query/structured-query-executor.js";
|
|
24
|
+
export type { StructuredQueryExecutionStage, StructuredQueryItem, StructuredQueryResult } from "./query/structured-query-executor.js";
|
|
25
|
+
export { STRUCTURED_QUERY_DEFAULT_LIMIT, STRUCTURED_QUERY_HEALTH_VALUES, STRUCTURED_QUERY_MAX_LIMIT, StructuredQuerySyntaxError, formatStructuredQueryExpression, parseStructuredQuery, structuredQueryPredicates, structuredQueryUsesHealth, tokenizeStructuredQuery, validateStructuredQuery } from "./query/structured-query.js";
|
|
26
|
+
export type { StructuredQueryAST, StructuredQueryExpression, StructuredQueryField, StructuredQueryHealth, StructuredQueryLogicalExpression, StructuredQueryNotExpression, StructuredQueryOperator, StructuredQueryPredicate, StructuredQuerySort, StructuredQuerySortDirection, StructuredQueryToken, StructuredQueryTokenKind } from "./query/structured-query.js";
|
|
27
|
+
export { RELATED_TO_ALGORITHM_VERSION, RELATED_TO_DEFAULT_MAX_NEIGHBORS, RELATED_TO_DEFAULT_MIN_EVIDENCE, RELATED_TO_DEFAULT_THRESHOLD, RELATED_TO_MAX_CHUNKS_PER_DOCUMENT, RELATED_TO_MAX_COMPONENT_COMPARISONS, RELATED_TO_MAX_DOCUMENT_PAIRS, RELATED_TO_MAX_VECTOR_COMPARISONS, RELATED_TO_MIN_THRESHOLD, RELATED_TO_QUALITY_GATE, DerivedRelationshipError, deriveRelatedRelationships } from "./relationships/derive-related.js";
|
|
28
|
+
export type { DeriveRelatedRelationshipsOptions, DerivedRelationship, DerivedRelationshipErrorCode, DerivedRelationshipEvidence, DerivedRelationshipReport } from "./relationships/derive-related.js";
|
|
22
29
|
export { generateReport, formatReport } from "./reporting/report.js";
|
|
23
30
|
export { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
24
31
|
export { embedTextLocal } from "./semantic/local-embedding.js";
|
|
25
|
-
export {
|
|
32
|
+
export { createEmbeddingProvider, embeddingCapability, isSupportedEmbeddingProvider, registerEmbeddingProvider, supportsSynchronousEmbeddingProvider } from "./semantic/provider-registry.js";
|
|
33
|
+
export type { EmbeddingProviderFactory } from "./semantic/provider-registry.js";
|
|
34
|
+
export { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector } from "./semantic/provider.js";
|
|
35
|
+
export type { EmbeddingCapability, EmbeddingDiagnostic, EmbeddingProvider, EmbeddingProviderAvailability, EmbeddingProviderErrorCode, EmbeddingRuntimeStatus } from "./semantic/provider.js";
|
|
36
|
+
export { semanticStatusReport, semanticStatusReportAsync } from "./semantic/status.js";
|
|
26
37
|
export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-codec.js";
|
|
27
38
|
export { watchProject } from "./watcher/file-watcher.js";
|
|
39
|
+
export type { WatchHandle, WatchProjectOptions } from "./watcher/file-watcher.js";
|
|
40
|
+
export type { WatchFailureCode, WatchFailurePhase, WatchHealthError, WatchHealthSnapshot, WatchHealthState } from "./watcher/watch-health.js";
|
|
28
41
|
export * from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ export { createGraphBundle, verifyGraphBundle, sourceSnapshot, hashCanonical, ca
|
|
|
5
5
|
export { openDatabase } from "./db/connection.js";
|
|
6
6
|
export { GraphRepository } from "./db/repositories.js";
|
|
7
7
|
export { generateGraphDiff, formatGraphDiff } from "./diff/graph-diff.js";
|
|
8
|
-
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
8
|
+
export { ALPHA_EVALUATION_CASES, CJK_EVALUATION_CASES, EVALUATION_QUERY_SET_NAMES, evaluateRetrieval, evaluateRetrievalAsync, evaluationCasesForQuerySet } from "./evaluation/retrieval-eval.js";
|
|
9
9
|
export { buildMermaidTraceExport, formatTraceMermaid } from "./export/diagram.js";
|
|
10
10
|
export { buildGraphJsonExport, formatGraphJsonVerification, graphJsonHash, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "./export/graphjson.js";
|
|
11
11
|
export { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "./export/markdown-index.js";
|
|
@@ -16,13 +16,18 @@ export { indexProject } from "./indexer.js";
|
|
|
16
16
|
export { MCPServer, startStdioMcpServer } from "./mcp/server.js";
|
|
17
17
|
export { ToolHandler, tools as mcpTools } from "./mcp/tools.js";
|
|
18
18
|
export { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
19
|
-
export { buildContext } from "./query/context-builder.js";
|
|
20
|
-
export { explainSearchGraph, searchGraph } from "./query/search.js";
|
|
19
|
+
export { CONTEXT_PACKING_STRATEGIES, CONTEXT_PACKING_STRATEGY, DEFAULT_MMR_LAMBDA, buildContext, buildContextAsync } from "./query/context-builder.js";
|
|
20
|
+
export { explainSearchGraph, explainSearchGraphAsync, searchGraph, searchGraphAsync } from "./query/search.js";
|
|
21
21
|
export { traceNodes } from "./query/trace.js";
|
|
22
|
+
export { executeStructuredQuery, StructuredQueryExecutionError } from "./query/structured-query-executor.js";
|
|
23
|
+
export { STRUCTURED_QUERY_DEFAULT_LIMIT, STRUCTURED_QUERY_HEALTH_VALUES, STRUCTURED_QUERY_MAX_LIMIT, StructuredQuerySyntaxError, formatStructuredQueryExpression, parseStructuredQuery, structuredQueryPredicates, structuredQueryUsesHealth, tokenizeStructuredQuery, validateStructuredQuery } from "./query/structured-query.js";
|
|
24
|
+
export { RELATED_TO_ALGORITHM_VERSION, RELATED_TO_DEFAULT_MAX_NEIGHBORS, RELATED_TO_DEFAULT_MIN_EVIDENCE, RELATED_TO_DEFAULT_THRESHOLD, RELATED_TO_MAX_CHUNKS_PER_DOCUMENT, RELATED_TO_MAX_COMPONENT_COMPARISONS, RELATED_TO_MAX_DOCUMENT_PAIRS, RELATED_TO_MAX_VECTOR_COMPARISONS, RELATED_TO_MIN_THRESHOLD, RELATED_TO_QUALITY_GATE, DerivedRelationshipError, deriveRelatedRelationships } from "./relationships/derive-related.js";
|
|
22
25
|
export { generateReport, formatReport } from "./reporting/report.js";
|
|
23
26
|
export { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
24
27
|
export { embedTextLocal } from "./semantic/local-embedding.js";
|
|
25
|
-
export {
|
|
28
|
+
export { createEmbeddingProvider, embeddingCapability, isSupportedEmbeddingProvider, registerEmbeddingProvider, supportsSynchronousEmbeddingProvider } from "./semantic/provider-registry.js";
|
|
29
|
+
export { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector } from "./semantic/provider.js";
|
|
30
|
+
export { semanticStatusReport, semanticStatusReportAsync } from "./semantic/status.js";
|
|
26
31
|
export { decodeFloat32Vector, encodeFloat32Vector } from "./semantic/vector-codec.js";
|
|
27
32
|
export { watchProject } from "./watcher/file-watcher.js";
|
|
28
33
|
export * from "./types.js";
|
package/dist/indexer.js
CHANGED
|
@@ -4,6 +4,7 @@ import { GraphRepository } from "./db/repositories.js";
|
|
|
4
4
|
import { buildGraphRecords } from "./extraction/graph-builder.js";
|
|
5
5
|
import { parseMarkdownDocument } from "./parser/markdown-parser.js";
|
|
6
6
|
import { scanMarkdownFiles } from "./scanner/file-scanner.js";
|
|
7
|
+
import { embedChunks } from "./semantic/embed-chunks.js";
|
|
7
8
|
import { relativePathInsideRoot } from "./utils/path-safety.js";
|
|
8
9
|
export async function indexProject(projectRoot, options = {}) {
|
|
9
10
|
const config = effectiveConfig(loadConfig(projectRoot), options);
|
|
@@ -13,7 +14,10 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
13
14
|
const db = openDatabase(projectRoot);
|
|
14
15
|
try {
|
|
15
16
|
const repository = new GraphRepository(db);
|
|
16
|
-
|
|
17
|
+
const existingCounts = repository.counts();
|
|
18
|
+
const requiresCompleteEmbedding = config.embedding.enabled && !hasMatchingVectorCoverage(repository, config, existingCounts);
|
|
19
|
+
if (options.full || existingCounts.documents === 0 || requiresCompleteEmbedding) {
|
|
20
|
+
records.vectors = await embedChunks(records.chunks, config);
|
|
17
21
|
repository.replaceAll(records);
|
|
18
22
|
return {
|
|
19
23
|
files: files.length,
|
|
@@ -37,7 +41,9 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
37
41
|
const replacedDocumentIds = changedDocuments
|
|
38
42
|
.map((document) => existing.get(document.relativePath)?.id)
|
|
39
43
|
.filter((existingId) => typeof existingId === "string" && !changedIds.has(existingId));
|
|
40
|
-
|
|
44
|
+
const changedRecords = filterRecordsForDocuments(records, changedIds);
|
|
45
|
+
changedRecords.vectors = await embedChunks(changedRecords.chunks, config);
|
|
46
|
+
repository.replaceDocuments(changedRecords, [...changedIds], [...deletedDocumentIds, ...replacedDocumentIds]);
|
|
41
47
|
}
|
|
42
48
|
return {
|
|
43
49
|
files: files.length,
|
|
@@ -54,6 +60,18 @@ export async function indexProject(projectRoot, options = {}) {
|
|
|
54
60
|
db.close();
|
|
55
61
|
}
|
|
56
62
|
}
|
|
63
|
+
function hasMatchingVectorCoverage(repository, config, counts) {
|
|
64
|
+
if (counts.vectors !== counts.chunks) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
if (counts.chunks === 0) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
return repository.storageDiagnostics().vectors.providers.some((provider) => (provider.provider === config.embedding.provider
|
|
71
|
+
&& provider.model === config.embedding.model
|
|
72
|
+
&& provider.dimensions === config.embedding.dimensions
|
|
73
|
+
&& provider.vectors === counts.chunks));
|
|
74
|
+
}
|
|
57
75
|
function parseScannedFiles(projectRoot, files) {
|
|
58
76
|
const parsed = [];
|
|
59
77
|
const skippedFiles = [];
|