@esankhan3/anvil-knowledge-core 0.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/README.md +194 -0
- package/dist/__tests__/chunker.test.d.ts +10 -0
- package/dist/__tests__/chunker.test.d.ts.map +1 -0
- package/dist/__tests__/chunker.test.js +161 -0
- package/dist/__tests__/chunker.test.js.map +1 -0
- package/dist/__tests__/query-classifier.test.d.ts +5 -0
- package/dist/__tests__/query-classifier.test.d.ts.map +1 -0
- package/dist/__tests__/query-classifier.test.js +158 -0
- package/dist/__tests__/query-classifier.test.js.map +1 -0
- package/dist/__tests__/retriever-defaults.test.d.ts +12 -0
- package/dist/__tests__/retriever-defaults.test.d.ts.map +1 -0
- package/dist/__tests__/retriever-defaults.test.js +37 -0
- package/dist/__tests__/retriever-defaults.test.js.map +1 -0
- package/dist/__tests__/structural-hasher.test.d.ts +5 -0
- package/dist/__tests__/structural-hasher.test.d.ts.map +1 -0
- package/dist/__tests__/structural-hasher.test.js +185 -0
- package/dist/__tests__/structural-hasher.test.js.map +1 -0
- package/dist/ast-graph-builder.d.ts +38 -0
- package/dist/ast-graph-builder.d.ts.map +1 -0
- package/dist/ast-graph-builder.js +1041 -0
- package/dist/ast-graph-builder.js.map +1 -0
- package/dist/chunker.d.ts +47 -0
- package/dist/chunker.d.ts.map +1 -0
- package/dist/chunker.js +428 -0
- package/dist/chunker.js.map +1 -0
- package/dist/claude-runner.d.ts +10 -0
- package/dist/claude-runner.d.ts.map +1 -0
- package/dist/claude-runner.js +10 -0
- package/dist/claude-runner.js.map +1 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +83 -0
- package/dist/config.js.map +1 -0
- package/dist/cross-repo-detector.d.ts +7 -0
- package/dist/cross-repo-detector.d.ts.map +1 -0
- package/dist/cross-repo-detector.js +990 -0
- package/dist/cross-repo-detector.js.map +1 -0
- package/dist/embedder.d.ts +84 -0
- package/dist/embedder.d.ts.map +1 -0
- package/dist/embedder.js +378 -0
- package/dist/embedder.js.map +1 -0
- package/dist/file-walker.d.ts +18 -0
- package/dist/file-walker.d.ts.map +1 -0
- package/dist/file-walker.js +221 -0
- package/dist/file-walker.js.map +1 -0
- package/dist/git-diff.d.ts +32 -0
- package/dist/git-diff.d.ts.map +1 -0
- package/dist/git-diff.js +145 -0
- package/dist/git-diff.js.map +1 -0
- package/dist/graph-metrics.d.ts +31 -0
- package/dist/graph-metrics.d.ts.map +1 -0
- package/dist/graph-metrics.js +277 -0
- package/dist/graph-metrics.js.map +1 -0
- package/dist/graph-query.d.ts +8 -0
- package/dist/graph-query.d.ts.map +1 -0
- package/dist/graph-query.js +79 -0
- package/dist/graph-query.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +1 -0
- package/dist/indexer.d.ts +98 -0
- package/dist/indexer.d.ts.map +1 -0
- package/dist/indexer.js +635 -0
- package/dist/indexer.js.map +1 -0
- package/dist/project-graph-builder-core.d.ts +48 -0
- package/dist/project-graph-builder-core.d.ts.map +1 -0
- package/dist/project-graph-builder-core.js +213 -0
- package/dist/project-graph-builder-core.js.map +1 -0
- package/dist/project-graph-builder.d.ts +39 -0
- package/dist/project-graph-builder.d.ts.map +1 -0
- package/dist/project-graph-builder.js +640 -0
- package/dist/project-graph-builder.js.map +1 -0
- package/dist/query-classifier.d.ts +38 -0
- package/dist/query-classifier.d.ts.map +1 -0
- package/dist/query-classifier.js +199 -0
- package/dist/query-classifier.js.map +1 -0
- package/dist/query-router.d.ts +82 -0
- package/dist/query-router.d.ts.map +1 -0
- package/dist/query-router.js +278 -0
- package/dist/query-router.js.map +1 -0
- package/dist/rag-evaluator.d.ts +53 -0
- package/dist/rag-evaluator.d.ts.map +1 -0
- package/dist/rag-evaluator.js +217 -0
- package/dist/rag-evaluator.js.map +1 -0
- package/dist/repo-profiler.d.ts +62 -0
- package/dist/repo-profiler.d.ts.map +1 -0
- package/dist/repo-profiler.js +488 -0
- package/dist/repo-profiler.js.map +1 -0
- package/dist/reranker.d.ts +8 -0
- package/dist/reranker.d.ts.map +1 -0
- package/dist/reranker.js +250 -0
- package/dist/reranker.js.map +1 -0
- package/dist/retriever.d.ts +42 -0
- package/dist/retriever.d.ts.map +1 -0
- package/dist/retriever.js +320 -0
- package/dist/retriever.js.map +1 -0
- package/dist/semantic-edge-detector.d.ts +28 -0
- package/dist/semantic-edge-detector.d.ts.map +1 -0
- package/dist/semantic-edge-detector.js +191 -0
- package/dist/semantic-edge-detector.js.map +1 -0
- package/dist/service-mesh-inferrer.d.ts +57 -0
- package/dist/service-mesh-inferrer.d.ts.map +1 -0
- package/dist/service-mesh-inferrer.js +322 -0
- package/dist/service-mesh-inferrer.js.map +1 -0
- package/dist/structural-hasher.d.ts +57 -0
- package/dist/structural-hasher.d.ts.map +1 -0
- package/dist/structural-hasher.js +350 -0
- package/dist/structural-hasher.js.map +1 -0
- package/dist/tree-sitter-parser.d.ts +71 -0
- package/dist/tree-sitter-parser.d.ts.map +1 -0
- package/dist/tree-sitter-parser.js +633 -0
- package/dist/tree-sitter-parser.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/vector-store.d.ts +56 -0
- package/dist/vector-store.d.ts.map +1 -0
- package/dist/vector-store.js +299 -0
- package/dist/vector-store.js.map +1 -0
- package/dist/workspace-detector.d.ts +11 -0
- package/dist/workspace-detector.d.ts.map +1 -0
- package/dist/workspace-detector.js +587 -0
- package/dist/workspace-detector.js.map +1 -0
- package/package.json +41 -0
package/dist/indexer.js
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { execSync } from 'node:child_process';
|
|
3
|
+
import { join, basename } from 'node:path';
|
|
4
|
+
import { chunkRepo, chunkChangedFiles } from '@esankhan3/anvil-knowledge-core';
|
|
5
|
+
import { buildAstGraph, generateGraphReport, incrementalGraphUpdate } from '@esankhan3/anvil-knowledge-core';
|
|
6
|
+
import { getAllChanges, getChangedFilesList, getDeletedFilesList } from '@esankhan3/anvil-knowledge-core';
|
|
7
|
+
import { createEmbeddingProvider } from '@esankhan3/anvil-knowledge-core';
|
|
8
|
+
import { VectorStore } from '@esankhan3/anvil-knowledge-core';
|
|
9
|
+
import { ProjectGraphBuilder } from '@esankhan3/anvil-knowledge-core';
|
|
10
|
+
import { detectCrossRepoEdges } from '@esankhan3/anvil-knowledge-core';
|
|
11
|
+
import { detectWorkspace } from '@esankhan3/anvil-knowledge-core';
|
|
12
|
+
import { HybridRetriever } from './retriever.js';
|
|
13
|
+
import { loadKnowledgeConfig, getKnowledgeBasePath, DEFAULT_CONFIG } from '@esankhan3/anvil-knowledge-core';
|
|
14
|
+
import { profileProject, loadAllProfiles } from '@esankhan3/anvil-knowledge-core';
|
|
15
|
+
import { inferServiceMesh } from '@esankhan3/anvil-knowledge-core';
|
|
16
|
+
import { deduplicateByStructure } from '@esankhan3/anvil-knowledge-core';
|
|
17
|
+
import { createQueryRouter } from '@esankhan3/anvil-knowledge-core';
|
|
18
|
+
function getRepoSha(repoPath) {
|
|
19
|
+
try {
|
|
20
|
+
return execSync('git rev-parse HEAD', { cwd: repoPath, stdio: 'pipe', encoding: 'utf-8', timeout: 5000 }).trim();
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function readRepoIndexMeta(basePath, repoName) {
|
|
27
|
+
const metaPath = join(basePath, repoName, 'index_meta.json');
|
|
28
|
+
if (!existsSync(metaPath))
|
|
29
|
+
return null;
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(readFileSync(metaPath, 'utf-8'));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function writeRepoIndexMeta(basePath, repoName, meta) {
|
|
38
|
+
const dir = join(basePath, repoName);
|
|
39
|
+
mkdirSync(dir, { recursive: true });
|
|
40
|
+
writeFileSync(join(dir, 'index_meta.json'), JSON.stringify(meta, null, 2), 'utf-8');
|
|
41
|
+
}
|
|
42
|
+
export class KnowledgeIndexer {
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// BUILD KB — fast, static, no embedding. Profiles + chunks + graphs + edges.
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
async buildKB(project, repos, config, opts) {
|
|
47
|
+
const log = opts?.onProgress ?? (() => { });
|
|
48
|
+
const report = opts?.onDetailedProgress ?? (() => { });
|
|
49
|
+
const startTime = Date.now();
|
|
50
|
+
const basePath = getKnowledgeBasePath(project);
|
|
51
|
+
mkdirSync(basePath, { recursive: true });
|
|
52
|
+
// 1. Determine which repos need re-indexing (SHA check)
|
|
53
|
+
const reposToIndex = [];
|
|
54
|
+
const skippedRepos = [];
|
|
55
|
+
for (const repo of repos) {
|
|
56
|
+
if (opts?.force) {
|
|
57
|
+
reposToIndex.push(repo);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const currentSha = getRepoSha(repo.path);
|
|
61
|
+
const meta = readRepoIndexMeta(basePath, repo.name);
|
|
62
|
+
if (meta && currentSha && meta.lastIndexedSha === currentSha) {
|
|
63
|
+
skippedRepos.push(repo.name);
|
|
64
|
+
log(`Skipping ${repo.name} — unchanged (${currentSha.slice(0, 7)})`);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
reposToIndex.push(repo);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (reposToIndex.length === 0) {
|
|
71
|
+
log('All repos up to date — nothing to build.');
|
|
72
|
+
report({ phase: 'done', message: 'All repos up to date', percent: 100, etaSeconds: 0, skippedRepos });
|
|
73
|
+
return { project, repos: [], totalChunks: 0, totalTokens: 0, crossRepoEdges: 0, durationMs: 0, chunksPath: join(basePath, 'chunks.json') };
|
|
74
|
+
}
|
|
75
|
+
// 2. LLM Repo Profiling (WS-1) — skipped if LLM_MODE=none
|
|
76
|
+
const { isLlmAvailable } = await import('./claude-runner.js');
|
|
77
|
+
if (isLlmAvailable()) {
|
|
78
|
+
report({ phase: 'profiling', message: `Profiling ${repos.length} repos with LLM...`, percent: 3, etaSeconds: -1, reposTotal: repos.length, reposProcessed: 0 });
|
|
79
|
+
log(`Profiling ${repos.length} repos with LLM...`);
|
|
80
|
+
try {
|
|
81
|
+
const profiles = await profileProject(project, repos, {
|
|
82
|
+
force: opts?.force,
|
|
83
|
+
onProgress: (m) => {
|
|
84
|
+
log(m);
|
|
85
|
+
report({ phase: 'profiling', message: m, percent: 5, etaSeconds: -1 });
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
log(`Profiled ${profiles.length} repos`);
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
92
|
+
log(`Warning: Repo profiling skipped: ${errMsg}`);
|
|
93
|
+
report({ phase: 'profiling', message: `Profiling skipped: ${errMsg.slice(0, 100)}`, percent: 8, etaSeconds: -1 });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
log('LLM profiling disabled (CODE_SEARCH_LLM_MODE=none) — skipping');
|
|
98
|
+
report({ phase: 'profiling', message: 'Skipped (LLM disabled)', percent: 8, etaSeconds: -1 });
|
|
99
|
+
}
|
|
100
|
+
// 3. Chunk repos — use git diff for incremental detection
|
|
101
|
+
report({ phase: 'chunking', message: `Chunking ${reposToIndex.length} repos...`, percent: 10, etaSeconds: -1, reposTotal: repos.length, reposProcessed: skippedRepos.length, skippedRepos });
|
|
102
|
+
log(`Chunking ${reposToIndex.length} repos (${skippedRepos.length} skipped — unchanged)...`);
|
|
103
|
+
const allChunks = [];
|
|
104
|
+
const repoStats = [];
|
|
105
|
+
const repoChunkResults = new Map();
|
|
106
|
+
const repoDiffs = new Map();
|
|
107
|
+
for (const repo of reposToIndex) {
|
|
108
|
+
const meta = opts?.force ? null : readRepoIndexMeta(basePath, repo.name);
|
|
109
|
+
// Use git diff for incremental change detection (O(1) via git's Merkle DAG)
|
|
110
|
+
const diff = opts?.force ? null : (meta?.lastIndexedSha ? getAllChanges(repo.path, meta.lastIndexedSha) : null);
|
|
111
|
+
const useIncremental = diff && !diff.fallbackToFull && (diff.added.length + diff.modified.length + diff.deleted.length) > 0;
|
|
112
|
+
let result;
|
|
113
|
+
if (useIncremental) {
|
|
114
|
+
const changedCount = diff.added.length + diff.modified.length;
|
|
115
|
+
const deletedCount = diff.deleted.length;
|
|
116
|
+
log(` ${repo.name}: git diff → ${changedCount} changed, ${deletedCount} deleted (incremental)`);
|
|
117
|
+
result = await chunkChangedFiles(repo.path, repo.name, project, config.chunking, diff);
|
|
118
|
+
repoDiffs.set(repo.name, diff);
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
// Full re-chunk (first index or force)
|
|
122
|
+
result = await chunkRepo(repo.path, repo.name, project, config.chunking, meta?.files ?? undefined);
|
|
123
|
+
}
|
|
124
|
+
allChunks.push(...result.chunks);
|
|
125
|
+
repoChunkResults.set(repo.name, result);
|
|
126
|
+
const totalChunkCount = Object.values(result.fileIndex).reduce((sum, f) => sum + f.chunkCount, 0);
|
|
127
|
+
repoStats.push({ name: repo.name, chunkCount: totalChunkCount, language: repo.language });
|
|
128
|
+
}
|
|
129
|
+
for (const name of skippedRepos) {
|
|
130
|
+
const meta = readRepoIndexMeta(basePath, name);
|
|
131
|
+
repoStats.push({ name, chunkCount: meta?.chunkCount ?? 0, language: '' });
|
|
132
|
+
}
|
|
133
|
+
log(`Chunked ${allChunks.length} chunks from ${reposToIndex.length} repos`);
|
|
134
|
+
// 4. Structural dedup (WS-6)
|
|
135
|
+
report({ phase: 'dedup', message: 'Deduplicating chunks by structure...', percent: 25, etaSeconds: -1 });
|
|
136
|
+
const dedupResult = deduplicateByStructure(allChunks);
|
|
137
|
+
const uniqueChunks = dedupResult.unique;
|
|
138
|
+
if (dedupResult.savings.chunks > 0) {
|
|
139
|
+
log(`Structural dedup: ${dedupResult.savings.chunks} duplicates removed`);
|
|
140
|
+
}
|
|
141
|
+
// 5. Detect workspace structures
|
|
142
|
+
const workspaceMaps = new Map();
|
|
143
|
+
for (const repo of repos) {
|
|
144
|
+
try {
|
|
145
|
+
const wsMap = detectWorkspace(repo.path);
|
|
146
|
+
if (wsMap.packages.length > 0) {
|
|
147
|
+
workspaceMaps.set(repo.name, wsMap);
|
|
148
|
+
log(`Detected workspace in ${repo.name}: ${wsMap.packages.length} packages`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
log(`Warning: Workspace detection failed for ${repo.name}: ${err}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// 6. Build AST graphs — incremental when possible via git diff
|
|
156
|
+
report({ phase: 'graphing', message: 'Building AST graphs...', percent: 40, etaSeconds: -1 });
|
|
157
|
+
const graphBuilder = new ProjectGraphBuilder();
|
|
158
|
+
await graphBuilder.init();
|
|
159
|
+
for (const repo of repos) {
|
|
160
|
+
try {
|
|
161
|
+
const repoKbDir = join(basePath, repo.name);
|
|
162
|
+
mkdirSync(repoKbDir, { recursive: true });
|
|
163
|
+
const existingGraphPath = join(repoKbDir, 'graph.json');
|
|
164
|
+
const diff = repoDiffs.get(repo.name);
|
|
165
|
+
let graph;
|
|
166
|
+
if (diff && !diff.fallbackToFull && existsSync(existingGraphPath)) {
|
|
167
|
+
// Incremental graph update — only re-parse changed files
|
|
168
|
+
const existingGraph = JSON.parse(readFileSync(existingGraphPath, 'utf-8'));
|
|
169
|
+
graph = await incrementalGraphUpdate(existingGraph, getChangedFilesList(diff), getDeletedFilesList(diff), repo.path, { workspaceMap: workspaceMaps.get(repo.name) });
|
|
170
|
+
log(`Updated AST graph for ${repo.name} incrementally (${diff.added.length + diff.modified.length} files changed)`);
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
// Full rebuild
|
|
174
|
+
graph = await buildAstGraph(repo.path, { workspaceMap: workspaceMaps.get(repo.name) });
|
|
175
|
+
log(`Built AST graph for ${repo.name} (${graph.nodes.length} nodes, ${graph.links.length} edges)`);
|
|
176
|
+
}
|
|
177
|
+
graphBuilder.addRepoGraph(repo.name, graph);
|
|
178
|
+
writeFileSync(join(repoKbDir, 'graph.json'), JSON.stringify(graph));
|
|
179
|
+
writeFileSync(join(repoKbDir, 'GRAPH_REPORT.md'), generateGraphReport(repo.name, graph));
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
log(`Warning: AST graph build failed for ${repo.name}: ${err}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// 7. Detect cross-repo edges (14 strategies)
|
|
186
|
+
report({ phase: 'graphing', message: 'Detecting cross-repo edges...', percent: 70, etaSeconds: -1 });
|
|
187
|
+
let crossRepoEdgeCount = 0;
|
|
188
|
+
const hasWorkspaces = workspaceMaps.size > 0;
|
|
189
|
+
if (repos.length > 1 || hasWorkspaces) {
|
|
190
|
+
const crossEdges = await detectCrossRepoEdges(repos, workspaceMaps);
|
|
191
|
+
graphBuilder.addCrossRepoEdges(crossEdges);
|
|
192
|
+
crossRepoEdgeCount = crossEdges.length;
|
|
193
|
+
log(`Detected ${crossEdges.length} cross-repo edges`);
|
|
194
|
+
}
|
|
195
|
+
// 8. LLM Service Mesh Inference (WS-2) — skipped if LLM_MODE=none
|
|
196
|
+
if (isLlmAvailable()) {
|
|
197
|
+
report({ phase: 'service-mesh', message: 'Inferring service mesh from profiles...', percent: 80, etaSeconds: -1 });
|
|
198
|
+
try {
|
|
199
|
+
const profiles = loadAllProfiles(project);
|
|
200
|
+
if (profiles.length > 0) {
|
|
201
|
+
log(`Inferring service mesh from ${profiles.length} profiles...`);
|
|
202
|
+
const meshEdges = await inferServiceMesh(profiles, {
|
|
203
|
+
onProgress: (m) => {
|
|
204
|
+
log(m);
|
|
205
|
+
report({ phase: 'service-mesh', message: m, percent: 82, etaSeconds: -1 });
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
if (meshEdges.length > 0) {
|
|
209
|
+
graphBuilder.addCrossRepoEdges(meshEdges);
|
|
210
|
+
crossRepoEdgeCount += meshEdges.length;
|
|
211
|
+
log(`Service mesh: ${meshEdges.length} edges inferred`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
log('No profiles found — skipping service mesh inference');
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
log(`Warning: Service mesh inference failed (non-fatal): ${err}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
log('LLM service mesh inference disabled — skipping');
|
|
224
|
+
report({ phase: 'service-mesh', message: 'Skipped (LLM disabled)', percent: 85, etaSeconds: -1 });
|
|
225
|
+
}
|
|
226
|
+
// 9. Community detection
|
|
227
|
+
report({ phase: 'graphing', message: 'Detecting communities...', percent: 90, etaSeconds: -1 });
|
|
228
|
+
graphBuilder.detectCommunities();
|
|
229
|
+
// 10. Save project graph
|
|
230
|
+
const graphOutputPath = join(basePath, 'system_graph_v2.json');
|
|
231
|
+
writeFileSync(graphOutputPath, JSON.stringify(graphBuilder.exportJson(), null, 2));
|
|
232
|
+
log(`Saved project graph to ${graphOutputPath}`);
|
|
233
|
+
// 11. Save chunks to disk (for later embedding)
|
|
234
|
+
const chunksPath = join(basePath, 'chunks.json');
|
|
235
|
+
writeFileSync(chunksPath, JSON.stringify(uniqueChunks));
|
|
236
|
+
log(`Saved ${uniqueChunks.length} chunks to ${chunksPath}`);
|
|
237
|
+
// 11b. Save deleted files list (for incremental embedding cleanup)
|
|
238
|
+
const allDeletedFiles = [];
|
|
239
|
+
for (const repo of reposToIndex) {
|
|
240
|
+
const result = repoChunkResults.get(repo.name);
|
|
241
|
+
if (result?.deletedFiles) {
|
|
242
|
+
for (const f of result.deletedFiles) {
|
|
243
|
+
allDeletedFiles.push({ repoName: repo.name, filePath: f });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const deletedPath = join(basePath, 'deleted_files.json');
|
|
248
|
+
writeFileSync(deletedPath, JSON.stringify(allDeletedFiles));
|
|
249
|
+
// 12. Save per-repo metadata
|
|
250
|
+
for (const repo of reposToIndex) {
|
|
251
|
+
const sha = getRepoSha(repo.path);
|
|
252
|
+
const result = repoChunkResults.get(repo.name);
|
|
253
|
+
const totalChunkCount = result ? Object.values(result.fileIndex).reduce((sum, f) => sum + f.chunkCount, 0) : 0;
|
|
254
|
+
if (sha) {
|
|
255
|
+
writeRepoIndexMeta(basePath, repo.name, {
|
|
256
|
+
lastIndexedSha: sha,
|
|
257
|
+
lastIndexedAt: new Date().toISOString(),
|
|
258
|
+
chunkCount: totalChunkCount,
|
|
259
|
+
embeddingProvider: 'pending',
|
|
260
|
+
files: result?.fileIndex,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const durationMs = Date.now() - startTime;
|
|
265
|
+
report({ phase: 'done', message: `KB built: ${uniqueChunks.length} chunks, ${crossRepoEdgeCount} edges in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0, skippedRepos });
|
|
266
|
+
return {
|
|
267
|
+
project,
|
|
268
|
+
repos: repoStats,
|
|
269
|
+
totalChunks: uniqueChunks.length,
|
|
270
|
+
totalTokens: uniqueChunks.reduce((sum, c) => sum + c.tokens, 0),
|
|
271
|
+
crossRepoEdges: crossRepoEdgeCount,
|
|
272
|
+
durationMs,
|
|
273
|
+
chunksPath,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// ---------------------------------------------------------------------------
|
|
277
|
+
// EMBED — incremental: only embeds new/changed chunks, preserves existing.
|
|
278
|
+
// ---------------------------------------------------------------------------
|
|
279
|
+
async embedChunks(project, config, opts) {
|
|
280
|
+
const log = opts?.onProgress ?? (() => { });
|
|
281
|
+
const report = opts?.onDetailedProgress ?? (() => { });
|
|
282
|
+
const startTime = Date.now();
|
|
283
|
+
const basePath = getKnowledgeBasePath(project);
|
|
284
|
+
// Load chunks from disk (only new/changed chunks from buildKB)
|
|
285
|
+
const chunksPath = join(basePath, 'chunks.json');
|
|
286
|
+
if (!existsSync(chunksPath)) {
|
|
287
|
+
throw new Error(`No chunks found — run Build KB first. Expected: ${chunksPath}`);
|
|
288
|
+
}
|
|
289
|
+
const chunks = JSON.parse(readFileSync(chunksPath, 'utf-8'));
|
|
290
|
+
log(`Loaded ${chunks.length} chunks from ${chunksPath}`);
|
|
291
|
+
// Open vector store
|
|
292
|
+
const dbPath = join(basePath, 'lancedb');
|
|
293
|
+
const vectorStore = new VectorStore(dbPath);
|
|
294
|
+
await vectorStore.init();
|
|
295
|
+
// Determine which chunks actually need embedding by checking existing IDs
|
|
296
|
+
const existingIds = new Set();
|
|
297
|
+
try {
|
|
298
|
+
const stats = await vectorStore.getStats();
|
|
299
|
+
if (stats && stats.rowCount > 0) {
|
|
300
|
+
// Load existing chunk IDs from the store
|
|
301
|
+
const existingChunks = await vectorStore.getChunkIds(project);
|
|
302
|
+
for (const id of existingChunks)
|
|
303
|
+
existingIds.add(id);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
catch { /* first run — no existing data */ }
|
|
307
|
+
const newChunks = chunks.filter((c) => !existingIds.has(c.id));
|
|
308
|
+
const deletedFiles = this.getDeletedFiles(basePath);
|
|
309
|
+
if (newChunks.length === 0 && deletedFiles.length === 0) {
|
|
310
|
+
log('All chunks already embedded — nothing to do.');
|
|
311
|
+
report({ phase: 'done', message: 'All chunks already embedded', percent: 100, etaSeconds: 0 });
|
|
312
|
+
const repoNames = [...new Set(chunks.map((c) => c.repoName))];
|
|
313
|
+
return {
|
|
314
|
+
project,
|
|
315
|
+
repos: repoNames.map((n) => ({ name: n, chunkCount: chunks.filter((c) => c.repoName === n).length, language: '' })),
|
|
316
|
+
totalChunks: chunks.length,
|
|
317
|
+
totalTokens: chunks.reduce((sum, c) => sum + c.tokens, 0),
|
|
318
|
+
embeddingProvider: 'cached',
|
|
319
|
+
embeddingDimensions: 0,
|
|
320
|
+
crossRepoEdges: 0,
|
|
321
|
+
lastIndexed: new Date().toISOString(),
|
|
322
|
+
indexDurationMs: Date.now() - startTime,
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
// Delete chunks for files that were removed — use file path matching, not chunk IDs
|
|
326
|
+
if (deletedFiles.length > 0) {
|
|
327
|
+
// Group by repo for efficient deletion
|
|
328
|
+
const byRepo = new Map();
|
|
329
|
+
for (const d of deletedFiles) {
|
|
330
|
+
const list = byRepo.get(d.repoName) ?? [];
|
|
331
|
+
list.push(d.filePath);
|
|
332
|
+
byRepo.set(d.repoName, list);
|
|
333
|
+
}
|
|
334
|
+
for (const [repoName, filePaths] of byRepo) {
|
|
335
|
+
log(`Removing chunks for ${filePaths.length} deleted files from ${repoName}...`);
|
|
336
|
+
await vectorStore.deleteFileChunks(project, repoName, filePaths);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// Embed only new/changed chunks
|
|
340
|
+
const embedder = createEmbeddingProvider(config.embedding);
|
|
341
|
+
const isOllama = embedder.name === 'ollama';
|
|
342
|
+
const batchSize = isOllama ? 10 : 50;
|
|
343
|
+
const batchDelay = isOllama ? 50 : 100;
|
|
344
|
+
log(`Embedding ${newChunks.length} new chunks with ${embedder.name} (${chunks.length - newChunks.length} cached, batch size: ${batchSize})...`);
|
|
345
|
+
const texts = newChunks.map((c) => c.contextualizedContent);
|
|
346
|
+
const embeddings = [];
|
|
347
|
+
const totalBatches = Math.ceil(texts.length / batchSize);
|
|
348
|
+
let batchesDone = 0;
|
|
349
|
+
const embedStartTime = Date.now();
|
|
350
|
+
for (let i = 0; i < texts.length; i += batchSize) {
|
|
351
|
+
const batch = texts.slice(i, i + batchSize);
|
|
352
|
+
const batchEmbeddings = await embedder.embed(batch);
|
|
353
|
+
embeddings.push(...batchEmbeddings);
|
|
354
|
+
batchesDone++;
|
|
355
|
+
const elapsed = Date.now() - embedStartTime;
|
|
356
|
+
const msPerBatch = elapsed / batchesDone;
|
|
357
|
+
const remainingBatches = totalBatches - batchesDone;
|
|
358
|
+
const etaSeconds = Math.ceil((msPerBatch * remainingBatches) / 1000);
|
|
359
|
+
const percent = Math.round(5 + (batchesDone / totalBatches) * 85);
|
|
360
|
+
const processed = Math.min(i + batchSize, texts.length);
|
|
361
|
+
report({
|
|
362
|
+
phase: 'embedding',
|
|
363
|
+
message: `Embedding: ${processed}/${texts.length} new (~${etaSeconds}s remaining)`,
|
|
364
|
+
percent, etaSeconds,
|
|
365
|
+
chunksTotal: texts.length, chunksProcessed: processed,
|
|
366
|
+
});
|
|
367
|
+
if (batchesDone % 10 === 0 || batchesDone === totalBatches) {
|
|
368
|
+
log(` Embedded ${processed}/${texts.length} (ETA: ${formatEta(etaSeconds)})`);
|
|
369
|
+
}
|
|
370
|
+
if (i + batchSize < texts.length && batchDelay > 0) {
|
|
371
|
+
await new Promise((resolve) => setTimeout(resolve, batchDelay));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const embeddedChunks = newChunks.map((chunk, i) => ({ ...chunk, embedding: embeddings[i] }));
|
|
375
|
+
// Add only new chunks to LanceDB (existing ones are preserved)
|
|
376
|
+
report({ phase: 'storing', message: 'Saving new chunks to vector database...', percent: 92, etaSeconds: -1 });
|
|
377
|
+
if (embeddedChunks.length > 0) {
|
|
378
|
+
await vectorStore.addChunks(embeddedChunks);
|
|
379
|
+
}
|
|
380
|
+
log(`Stored ${embeddedChunks.length} new chunks in LanceDB (${deletedFiles.length} removed)`);
|
|
381
|
+
// Update metadata
|
|
382
|
+
const repoNames = [...new Set(chunks.map((c) => c.repoName))];
|
|
383
|
+
for (const repoName of repoNames) {
|
|
384
|
+
const metaPath = join(basePath, repoName, 'index_meta.json');
|
|
385
|
+
if (existsSync(metaPath)) {
|
|
386
|
+
try {
|
|
387
|
+
const meta = JSON.parse(readFileSync(metaPath, 'utf-8'));
|
|
388
|
+
meta.embeddingProvider = embedder.name;
|
|
389
|
+
meta.lastIndexedAt = new Date().toISOString();
|
|
390
|
+
writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf-8');
|
|
391
|
+
}
|
|
392
|
+
catch { /* ok */ }
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const durationMs = Date.now() - startTime;
|
|
396
|
+
report({ phase: 'done', message: `Embedded ${newChunks.length} new chunks (${deletedFiles.length} removed) in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0 });
|
|
397
|
+
return {
|
|
398
|
+
project,
|
|
399
|
+
repos: repoNames.map((n) => ({ name: n, chunkCount: chunks.filter((c) => c.repoName === n).length, language: '' })),
|
|
400
|
+
totalChunks: chunks.length,
|
|
401
|
+
totalTokens: chunks.reduce((sum, c) => sum + c.tokens, 0),
|
|
402
|
+
embeddingProvider: embedder.name,
|
|
403
|
+
embeddingDimensions: embedder.dimensions,
|
|
404
|
+
crossRepoEdges: 0,
|
|
405
|
+
lastIndexed: new Date().toISOString(),
|
|
406
|
+
indexDurationMs: durationMs,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
/** Read the deleted files list saved by buildKB */
|
|
410
|
+
getDeletedFiles(basePath) {
|
|
411
|
+
const deletedPath = join(basePath, 'deleted_files.json');
|
|
412
|
+
if (!existsSync(deletedPath))
|
|
413
|
+
return [];
|
|
414
|
+
try {
|
|
415
|
+
return JSON.parse(readFileSync(deletedPath, 'utf-8'));
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
return [];
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
// ---------------------------------------------------------------------------
|
|
422
|
+
// FULL INDEX — convenience: buildKB + embedChunks in one call
|
|
423
|
+
// ---------------------------------------------------------------------------
|
|
424
|
+
async indexProject(project, repos, config, opts) {
|
|
425
|
+
// Phase 1: Build KB (fast)
|
|
426
|
+
await this.buildKB(project, repos, config, opts);
|
|
427
|
+
// Phase 2: Embed (slow)
|
|
428
|
+
return this.embedChunks(project, config, opts);
|
|
429
|
+
}
|
|
430
|
+
/** Load index statistics for a project */
|
|
431
|
+
async getStats(project) {
|
|
432
|
+
const basePath = getKnowledgeBasePath(project);
|
|
433
|
+
const dbPath = join(basePath, 'lancedb');
|
|
434
|
+
const store = new VectorStore(dbPath);
|
|
435
|
+
await store.init();
|
|
436
|
+
const stats = await store.getStats();
|
|
437
|
+
// Read metadata from per-repo index_meta.json files
|
|
438
|
+
let provider = 'unknown';
|
|
439
|
+
let lastIndexed = '';
|
|
440
|
+
const repos = [];
|
|
441
|
+
try {
|
|
442
|
+
const { readdirSync } = await import('node:fs');
|
|
443
|
+
for (const entry of readdirSync(basePath)) {
|
|
444
|
+
const meta = readRepoIndexMeta(basePath, entry);
|
|
445
|
+
if (meta) {
|
|
446
|
+
repos.push({ name: entry, chunkCount: meta.chunkCount, language: '' });
|
|
447
|
+
if (meta.embeddingProvider !== 'unknown')
|
|
448
|
+
provider = meta.embeddingProvider;
|
|
449
|
+
if (meta.lastIndexedAt > lastIndexed)
|
|
450
|
+
lastIndexed = meta.lastIndexedAt;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
catch { /* ignore */ }
|
|
455
|
+
return {
|
|
456
|
+
project,
|
|
457
|
+
repos,
|
|
458
|
+
totalChunks: stats?.rowCount ?? 0,
|
|
459
|
+
totalTokens: 0,
|
|
460
|
+
embeddingProvider: provider,
|
|
461
|
+
embeddingDimensions: 0,
|
|
462
|
+
crossRepoEdges: 0,
|
|
463
|
+
lastIndexed,
|
|
464
|
+
indexDurationMs: 0,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
// ---------------------------------------------------------------------------
|
|
469
|
+
// Path-based discovery — NO YAML, NO config. Just a directory path.
|
|
470
|
+
// ---------------------------------------------------------------------------
|
|
471
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', 'dist', '.next', 'build', '__pycache__', '.venv', 'vendor', 'target']);
|
|
472
|
+
/**
|
|
473
|
+
* Discover repos from a directory path. Zero config required.
|
|
474
|
+
*
|
|
475
|
+
* - If path IS a git repo → single repo
|
|
476
|
+
* - If path CONTAINS git repos → multi-repo (scans subdirs)
|
|
477
|
+
*/
|
|
478
|
+
export function discoverRepos(directoryPath) {
|
|
479
|
+
if (!existsSync(directoryPath))
|
|
480
|
+
return [];
|
|
481
|
+
const repos = [];
|
|
482
|
+
// Check if directory itself is a git repo
|
|
483
|
+
if (existsSync(join(directoryPath, '.git'))) {
|
|
484
|
+
repos.push({
|
|
485
|
+
name: basename(directoryPath),
|
|
486
|
+
path: directoryPath,
|
|
487
|
+
language: detectLanguage(directoryPath),
|
|
488
|
+
});
|
|
489
|
+
return repos;
|
|
490
|
+
}
|
|
491
|
+
// Scan subdirectories for git repos
|
|
492
|
+
try {
|
|
493
|
+
for (const entry of readdirSync(directoryPath)) {
|
|
494
|
+
if (entry.startsWith('.') || SKIP_DIRS.has(entry))
|
|
495
|
+
continue;
|
|
496
|
+
const fullPath = join(directoryPath, entry);
|
|
497
|
+
try {
|
|
498
|
+
if (!statSync(fullPath).isDirectory())
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
if (!existsSync(join(fullPath, '.git')))
|
|
505
|
+
continue;
|
|
506
|
+
repos.push({
|
|
507
|
+
name: entry,
|
|
508
|
+
path: fullPath,
|
|
509
|
+
language: detectLanguage(fullPath),
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
catch { /* ignore */ }
|
|
514
|
+
return repos;
|
|
515
|
+
}
|
|
516
|
+
/** Detect primary language of a repo from manifest files and file extensions */
|
|
517
|
+
function detectLanguage(repoPath) {
|
|
518
|
+
// Manifest-based detection (most reliable)
|
|
519
|
+
if (existsSync(join(repoPath, 'go.mod')))
|
|
520
|
+
return 'go';
|
|
521
|
+
if (existsSync(join(repoPath, 'Cargo.toml')))
|
|
522
|
+
return 'rust';
|
|
523
|
+
if (existsSync(join(repoPath, 'pom.xml')) || existsSync(join(repoPath, 'build.gradle')))
|
|
524
|
+
return 'java';
|
|
525
|
+
if (existsSync(join(repoPath, 'composer.json')))
|
|
526
|
+
return 'php';
|
|
527
|
+
if (existsSync(join(repoPath, 'pyproject.toml')) || existsSync(join(repoPath, 'setup.py')))
|
|
528
|
+
return 'python';
|
|
529
|
+
// Check package.json for TS vs JS
|
|
530
|
+
if (existsSync(join(repoPath, 'package.json'))) {
|
|
531
|
+
if (existsSync(join(repoPath, 'tsconfig.json')))
|
|
532
|
+
return 'typescript';
|
|
533
|
+
return 'javascript';
|
|
534
|
+
}
|
|
535
|
+
return 'unknown';
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Build KB from a directory path — fast, no embedding.
|
|
539
|
+
* Profiles repos, chunks files, builds AST graphs, detects cross-repo edges.
|
|
540
|
+
* Saves chunks.json for later embedding.
|
|
541
|
+
*/
|
|
542
|
+
export async function buildKBFromPath(projectName, directoryPath, opts) {
|
|
543
|
+
const log = opts?.onProgress ?? (() => { });
|
|
544
|
+
log(`Scanning ${directoryPath} for repos...`);
|
|
545
|
+
const repos = discoverRepos(directoryPath);
|
|
546
|
+
if (repos.length === 0)
|
|
547
|
+
throw new Error(`No git repos found in ${directoryPath}`);
|
|
548
|
+
log(`Discovered ${repos.length} repos`);
|
|
549
|
+
const indexer = new KnowledgeIndexer();
|
|
550
|
+
return indexer.buildKB(projectName, repos, DEFAULT_CONFIG, opts);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Embed chunks for a project that already has KB built.
|
|
554
|
+
* Reads chunks.json, embeds with Ollama bge-m3, stores in LanceDB.
|
|
555
|
+
*/
|
|
556
|
+
export async function embedFromPath(projectName, opts) {
|
|
557
|
+
const indexer = new KnowledgeIndexer();
|
|
558
|
+
return indexer.embedChunks(projectName, DEFAULT_CONFIG, opts);
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Full index from a directory path — buildKB + embed in one call.
|
|
562
|
+
*/
|
|
563
|
+
export async function indexFromPath(projectName, directoryPath, opts) {
|
|
564
|
+
const log = opts?.onProgress ?? (() => { });
|
|
565
|
+
log(`Scanning ${directoryPath} for repos...`);
|
|
566
|
+
const repos = discoverRepos(directoryPath);
|
|
567
|
+
if (repos.length === 0)
|
|
568
|
+
throw new Error(`No git repos found in ${directoryPath}`);
|
|
569
|
+
log(`Discovered ${repos.length} repos`);
|
|
570
|
+
const indexer = new KnowledgeIndexer();
|
|
571
|
+
return indexer.indexProject(projectName, repos, DEFAULT_CONFIG, opts);
|
|
572
|
+
}
|
|
573
|
+
function formatEta(seconds) {
|
|
574
|
+
if (seconds < 0)
|
|
575
|
+
return '...';
|
|
576
|
+
if (seconds < 60)
|
|
577
|
+
return `${seconds}s`;
|
|
578
|
+
const mins = Math.floor(seconds / 60);
|
|
579
|
+
const secs = seconds % 60;
|
|
580
|
+
return `${mins}m ${secs}s`;
|
|
581
|
+
}
|
|
582
|
+
// ---------------------------------------------------------------------------
|
|
583
|
+
// Convenience: get a ready-to-use retriever for an already-indexed project
|
|
584
|
+
// ---------------------------------------------------------------------------
|
|
585
|
+
/** Load an existing index and return a configured HybridRetriever with query routing. */
|
|
586
|
+
export async function getRetriever(project) {
|
|
587
|
+
const config = loadKnowledgeConfig(project);
|
|
588
|
+
const basePath = getKnowledgeBasePath(project);
|
|
589
|
+
// Load vector store
|
|
590
|
+
const dbPath = join(basePath, 'lancedb');
|
|
591
|
+
const vectorStore = new VectorStore(dbPath);
|
|
592
|
+
await vectorStore.init();
|
|
593
|
+
// Load project graph (if available)
|
|
594
|
+
let graph = null;
|
|
595
|
+
const graphPath = join(basePath, 'system_graph_v2.json');
|
|
596
|
+
if (existsSync(graphPath)) {
|
|
597
|
+
try {
|
|
598
|
+
const graphData = JSON.parse(readFileSync(graphPath, 'utf-8'));
|
|
599
|
+
graph = new ProjectGraphBuilder();
|
|
600
|
+
await graph.importJson(graphData);
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
// Proceed without graph — vector + BM25 still work
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
// Create embedding provider for query-time embedding
|
|
607
|
+
const embedder = createEmbeddingProvider(config.embedding);
|
|
608
|
+
// Create reranker (ollama by default, graceful fallback)
|
|
609
|
+
let reranker = null;
|
|
610
|
+
try {
|
|
611
|
+
const { createReranker } = await import('./reranker.js');
|
|
612
|
+
reranker = createReranker(config.retrieval.reranker);
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
// Reranker module unavailable — proceed without
|
|
616
|
+
}
|
|
617
|
+
// Create query router (WS-8) — routes queries to relevant repos
|
|
618
|
+
let queryRouter = null;
|
|
619
|
+
try {
|
|
620
|
+
queryRouter = await createQueryRouter(project, embedder);
|
|
621
|
+
if (queryRouter) {
|
|
622
|
+
// eslint-disable-next-line no-console
|
|
623
|
+
console.log(`[knowledge] Query router ready (${queryRouter.repoCount} repo profiles)`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
catch {
|
|
627
|
+
// Query routing unavailable — search all repos
|
|
628
|
+
}
|
|
629
|
+
return new HybridRetriever(vectorStore, embedder, graph, {
|
|
630
|
+
maxChunks: config.retrieval.maxChunks,
|
|
631
|
+
maxTokens: config.retrieval.maxTokens,
|
|
632
|
+
hybridWeights: config.retrieval.hybridWeights,
|
|
633
|
+
}, reranker, queryRouter);
|
|
634
|
+
}
|
|
635
|
+
//# sourceMappingURL=indexer.js.map
|