@esankhan3/anvil-knowledge-core 0.4.8 → 0.4.10
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 +1 -1
- package/dist/__tests__/change-check-async.test.d.ts +6 -0
- package/dist/__tests__/change-check-async.test.d.ts.map +1 -0
- package/dist/__tests__/change-check-async.test.js +41 -0
- package/dist/__tests__/change-check-async.test.js.map +1 -0
- package/dist/__tests__/content-hash-reuse.test.js +9 -0
- package/dist/__tests__/content-hash-reuse.test.js.map +1 -1
- package/dist/__tests__/cross-repo-detector.test.js +163 -0
- package/dist/__tests__/cross-repo-detector.test.js.map +1 -1
- package/dist/__tests__/graph-store-queries.test.d.ts +4 -2
- package/dist/__tests__/graph-store-queries.test.d.ts.map +1 -1
- package/dist/__tests__/graph-store-queries.test.js +95 -4
- package/dist/__tests__/graph-store-queries.test.js.map +1 -1
- package/dist/__tests__/graph-store-update.test.d.ts +16 -0
- package/dist/__tests__/graph-store-update.test.d.ts.map +1 -0
- package/dist/__tests__/graph-store-update.test.js +363 -0
- package/dist/__tests__/graph-store-update.test.js.map +1 -0
- package/dist/__tests__/identifier-bm25.test.js +16 -0
- package/dist/__tests__/identifier-bm25.test.js.map +1 -1
- package/dist/__tests__/incremental-graph.test.d.ts +6 -0
- package/dist/__tests__/incremental-graph.test.d.ts.map +1 -0
- package/dist/__tests__/incremental-graph.test.js +55 -0
- package/dist/__tests__/incremental-graph.test.js.map +1 -0
- package/dist/__tests__/literal-tier-integration.test.js +21 -0
- package/dist/__tests__/literal-tier-integration.test.js.map +1 -1
- package/dist/__tests__/partial-cycle-chunks.test.d.ts +4 -5
- package/dist/__tests__/partial-cycle-chunks.test.d.ts.map +1 -1
- package/dist/__tests__/partial-cycle-chunks.test.js +9 -8
- package/dist/__tests__/partial-cycle-chunks.test.js.map +1 -1
- package/dist/__tests__/per-repo-chunks.test.d.ts +9 -0
- package/dist/__tests__/per-repo-chunks.test.d.ts.map +1 -0
- package/dist/__tests__/per-repo-chunks.test.js +84 -0
- package/dist/__tests__/per-repo-chunks.test.js.map +1 -0
- package/dist/__tests__/vector-index-maintenance.test.js +17 -0
- package/dist/__tests__/vector-index-maintenance.test.js.map +1 -1
- package/dist/chunks-io.d.ts +8 -5
- package/dist/chunks-io.d.ts.map +1 -1
- package/dist/chunks-io.js +7 -6
- package/dist/chunks-io.js.map +1 -1
- package/dist/cross-repo-detector.d.ts +3 -1
- package/dist/cross-repo-detector.d.ts.map +1 -1
- package/dist/cross-repo-detector.js +45 -44
- package/dist/cross-repo-detector.js.map +1 -1
- package/dist/git-diff.d.ts +5 -0
- package/dist/git-diff.d.ts.map +1 -1
- package/dist/git-diff.js +33 -14
- package/dist/git-diff.js.map +1 -1
- package/dist/graph-store.d.ts +50 -5
- package/dist/graph-store.d.ts.map +1 -1
- package/dist/graph-store.js +350 -91
- package/dist/graph-store.js.map +1 -1
- package/dist/indexer.d.ts +4 -3
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +327 -169
- package/dist/indexer.js.map +1 -1
- package/dist/repo-chunks.d.ts +43 -0
- package/dist/repo-chunks.d.ts.map +1 -0
- package/dist/repo-chunks.js +92 -0
- package/dist/repo-chunks.js.map +1 -0
- package/dist/repo-pipeline.d.ts +6 -2
- package/dist/repo-pipeline.d.ts.map +1 -1
- package/dist/repo-pipeline.js +25 -3
- package/dist/repo-pipeline.js.map +1 -1
- package/dist/storage/fs-blob-store.js +2 -2
- package/dist/storage/fs-blob-store.js.map +1 -1
- package/dist/storage/mongo-blob-store.d.ts +1 -1
- package/dist/storage/mongo-blob-store.js +1 -1
- package/dist/storage/ports.d.ts +8 -4
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/resolve.d.ts +8 -5
- package/dist/storage/resolve.d.ts.map +1 -1
- package/dist/storage/resolve.js +10 -6
- package/dist/storage/resolve.js.map +1 -1
- package/dist/vector-index-maintenance.d.ts +2 -0
- package/dist/vector-index-maintenance.d.ts.map +1 -1
- package/dist/vector-index-maintenance.js +8 -3
- package/dist/vector-index-maintenance.js.map +1 -1
- package/dist/vector-store.d.ts +17 -10
- package/dist/vector-store.d.ts.map +1 -1
- package/dist/vector-store.js +148 -59
- package/dist/vector-store.js.map +1 -1
- package/package.json +1 -1
package/dist/indexer.js
CHANGED
|
@@ -9,7 +9,7 @@ import { cosineSimilarity } from './query-router.js';
|
|
|
9
9
|
import { FsBlobStore } from './storage/fs-blob-store.js';
|
|
10
10
|
import { ProjectGraphBuilder } from '@esankhan3/anvil-knowledge-core';
|
|
11
11
|
import { correlateCrossRepoEdges, CROSS_REPO_SIGNALS_VERSION } from './cross-repo-detector.js';
|
|
12
|
-
import {
|
|
12
|
+
import { getWorkingTreeStateAsync, sameWorkingTreeState } from './git-diff.js';
|
|
13
13
|
import { HybridRetriever } from './retriever.js';
|
|
14
14
|
import { loadKnowledgeConfig, getKnowledgeBasePath } from '@esankhan3/anvil-knowledge-core';
|
|
15
15
|
import { profileProject, loadAllProfiles } from '@esankhan3/anvil-knowledge-core';
|
|
@@ -17,9 +17,10 @@ import { inferServiceMesh } from '@esankhan3/anvil-knowledge-core';
|
|
|
17
17
|
import { CHUNK_ID_VERSION } from './chunker.js';
|
|
18
18
|
import { createQueryRouter } from '@esankhan3/anvil-knowledge-core';
|
|
19
19
|
import { iterateChunksFile } from './chunks-io.js';
|
|
20
|
-
import {
|
|
20
|
+
import { EMBED_PENDING_KEY, LEGACY_CHUNKS_KEY, iterateRepoChunks, readEmbedPending, repoChunksKey, splitLegacyChunks, } from './repo-chunks.js';
|
|
21
|
+
import { writeSystemGraphSqlite, createSystemGraphSqliteWriter, openSystemGraphSqliteUpdater } from './graph-store.js';
|
|
21
22
|
import { resolveIndexConcurrency, runReposPooled } from './index-pool.js';
|
|
22
|
-
import { processRepoPipeline, getRepoSha,
|
|
23
|
+
import { processRepoPipeline, getRepoSha, getRepoShaAsync, getRemoteShaAsync, readRepoIndexMeta } from './repo-pipeline.js';
|
|
23
24
|
// ---------------------------------------------------------------------------
|
|
24
25
|
// SHA-based staleness detection
|
|
25
26
|
// ---------------------------------------------------------------------------
|
|
@@ -31,15 +32,14 @@ async function writeRepoIndexMeta(blobs, repoName, meta) {
|
|
|
31
32
|
await blobs.putJson(`${repoName}/index_meta.json`, meta);
|
|
32
33
|
}
|
|
33
34
|
/**
|
|
34
|
-
* Merge
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
* Merge shards (+ chunks carried forward from a previous chunk file) into the
|
|
36
|
+
* chunk file at `chunksKey`, streaming: one chunk at a time plus a Set of ids.
|
|
37
|
+
* Every repo keeps its own copy of shared code — identical code in two repos
|
|
38
|
+
* is two searchable, separately-scoped chunks.
|
|
38
39
|
*/
|
|
39
40
|
async function mergeShardsToChunks(shardPaths, blobs, chunksKey,
|
|
40
|
-
/** Local NDJSON copy of the PREVIOUS
|
|
41
|
-
* keep. Absent
|
|
42
|
-
* then the complete corpus. */
|
|
41
|
+
/** Local NDJSON copy of the PREVIOUS chunk file + which of its chunks to
|
|
42
|
+
* keep. Absent when the shards are complete. */
|
|
43
43
|
carryForward) {
|
|
44
44
|
// Shards are transient local scratch — read raw. Chunks stream straight into
|
|
45
45
|
// the durable chunks blob via putNdjson; counts are tallied inside the
|
|
@@ -80,47 +80,59 @@ export class KnowledgeIndexer {
|
|
|
80
80
|
const reposToIndex = [];
|
|
81
81
|
const skippedRepos = [];
|
|
82
82
|
const skippedMeta = new Map();
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
83
|
+
// Is each repo unchanged since the last index? A check is a few git
|
|
84
|
+
// processes (~0.2 s for the working-tree listings on a large checkout), so
|
|
85
|
+
// checks run concurrently — sequentially they cost ~0.2 s × repos on every
|
|
86
|
+
// cycle, a minute at a few hundred repos, even when nothing changed.
|
|
87
|
+
const checkRepo = async (repo) => {
|
|
88
88
|
// Remote repos: compare the ls-remote HEAD sha — unchanged repos never clone.
|
|
89
|
-
const currentSha =
|
|
90
|
-
|
|
89
|
+
const [currentSha, meta] = await Promise.all([
|
|
90
|
+
repo.cloneUrl ? getRemoteShaAsync(repo.cloneUrl) : getRepoShaAsync(repo.path),
|
|
91
|
+
readRepoIndexMeta(basePath, repo.name, storage.blobs),
|
|
92
|
+
]);
|
|
93
|
+
if (!meta || !currentSha || meta.lastIndexedSha !== currentSha)
|
|
94
|
+
return null;
|
|
91
95
|
// Unchanged = same HEAD AND (local checkouts) the same uncommitted edits
|
|
92
96
|
// as last indexed — saved-but-uncommitted work must still be picked up.
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
97
|
+
if (!repo.cloneUrl && !sameWorkingTreeState(meta.workingTree ?? {}, await getWorkingTreeStateAsync(repo.path))) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
// A skipped repo is served entirely from its stored artifacts (graph +
|
|
101
|
+
// cross-repo signals + chunks carried forward) — no clone, no AST
|
|
102
|
+
// re-parse. An index whose signals are missing or in an older format,
|
|
103
|
+
// or whose chunks use an older id scheme, must be re-indexed once.
|
|
104
|
+
const signals = await storage.blobs
|
|
105
|
+
.getJson(`${repo.name}/signals.json`)
|
|
106
|
+
.catch(() => null);
|
|
107
|
+
const hasArtifacts = meta.chunkIdVersion === CHUNK_ID_VERSION &&
|
|
108
|
+
(await storage.blobs.exists(`${repo.name}/graph.json`)) &&
|
|
109
|
+
signals?.version === CROSS_REPO_SIGNALS_VERSION;
|
|
110
|
+
return { meta, sha: currentSha, hasArtifacts };
|
|
111
|
+
};
|
|
112
|
+
const checks = opts?.force
|
|
113
|
+
? repos.map(() => null)
|
|
114
|
+
: await runReposPooled(repos, {
|
|
115
|
+
concurrency: resolveIndexConcurrency(repos.length),
|
|
116
|
+
workerUrl: null,
|
|
117
|
+
inThread: checkRepo,
|
|
118
|
+
toMessage: () => null,
|
|
119
|
+
});
|
|
120
|
+
repos.forEach((repo, i) => {
|
|
121
|
+
const check = checks[i];
|
|
122
|
+
if (check?.hasArtifacts) {
|
|
123
|
+
skippedRepos.push(repo.name);
|
|
124
|
+
skippedMeta.set(repo.name, check.meta);
|
|
125
|
+
log(`Skipping ${repo.name} — unchanged (${check.sha.slice(0, 7)})`);
|
|
116
126
|
}
|
|
117
127
|
else {
|
|
118
128
|
reposToIndex.push(repo);
|
|
129
|
+
if (check)
|
|
130
|
+
log(`Re-indexing ${repo.name} — unchanged but stored graph/signals missing or outdated (pre-upgrade index)`);
|
|
119
131
|
}
|
|
120
|
-
}
|
|
132
|
+
});
|
|
121
133
|
// Repos the last cycle indexed that are no longer in the workspace: their
|
|
122
|
-
//
|
|
123
|
-
//
|
|
134
|
+
// per-repo artifacts (chunk file included) are deleted below and
|
|
135
|
+
// embedChunks deletes their rows — so this cycle isn't a no-op.
|
|
124
136
|
const currentRepoNames = new Set(repos.map((r) => r.name));
|
|
125
137
|
const prevStats = await storage.blobs
|
|
126
138
|
.getJson('index_stats.json')
|
|
@@ -131,7 +143,7 @@ export class KnowledgeIndexer {
|
|
|
131
143
|
if (reposToIndex.length === 0 && removedRepos.length === 0) {
|
|
132
144
|
log('All repos up to date — nothing to build.');
|
|
133
145
|
report({ phase: 'done', message: 'All repos up to date', percent: 100, etaSeconds: 0, skippedRepos });
|
|
134
|
-
return { project, repos: [], totalChunks: 0, totalTokens: 0, crossRepoEdges: prevStats?.crossRepoEdges ?? 0, durationMs: 0, chunksPath:
|
|
146
|
+
return { project, repos: [], totalChunks: 0, totalTokens: 0, crossRepoEdges: prevStats?.crossRepoEdges ?? 0, durationMs: 0, chunksPath: basePath };
|
|
135
147
|
}
|
|
136
148
|
// 2. LLM Repo Profiling (WS-1) — skipped if LLM_MODE=none
|
|
137
149
|
const { isLlmAvailable } = await import('./claude-runner.js');
|
|
@@ -176,10 +188,47 @@ export class KnowledgeIndexer {
|
|
|
176
188
|
// last unbounded structure). Fall back to the in-memory builder only when no
|
|
177
189
|
// sqlite driver is available (small/local indexes; also gives the JSON
|
|
178
190
|
// fallback + community detection that the streamed path drops as unused).
|
|
179
|
-
|
|
180
|
-
|
|
191
|
+
// An existing current-schema file is updated in place instead: only the
|
|
192
|
+
// re-indexed and removed repos' nodes/edges and the cross-repo edge set
|
|
193
|
+
// change, in one transaction readers don't see until it commits — so the
|
|
194
|
+
// graph's cost tracks the change, not the corpus. Forced runs rebuild; a
|
|
195
|
+
// failed update falls back to a rebuild from the stored per-repo graphs.
|
|
196
|
+
let graphUpdater = opts?.force ? null : await openSystemGraphSqliteUpdater(basePath);
|
|
197
|
+
let graphUpdateFailed = false;
|
|
198
|
+
const graphUpdateFailure = (e) => {
|
|
199
|
+
if (!graphUpdateFailed)
|
|
200
|
+
log(`Warning: in-place graph update failed (${e instanceof Error ? e.message : e}); rebuilding the system graph`);
|
|
201
|
+
graphUpdateFailed = true;
|
|
202
|
+
};
|
|
203
|
+
if (graphUpdater) {
|
|
204
|
+
try {
|
|
205
|
+
graphUpdater.removeRepos([...reposToIndex.map((r) => r.name), ...removedRepos]);
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
graphUpdateFailure(e);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
let graphWriter = graphUpdater ? null : await createSystemGraphSqliteWriter(basePath);
|
|
212
|
+
const graphBuilder = graphUpdater || graphWriter ? null : new ProjectGraphBuilder();
|
|
181
213
|
if (graphBuilder)
|
|
182
214
|
await graphBuilder.init();
|
|
215
|
+
const addRepoGraph = (name, g) => {
|
|
216
|
+
if (graphUpdater) {
|
|
217
|
+
if (!graphUpdateFailed)
|
|
218
|
+
try {
|
|
219
|
+
graphUpdater.addRepoGraph(name, g);
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
graphUpdateFailure(e);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
else if (graphWriter)
|
|
226
|
+
graphWriter.addRepoGraph(name, g);
|
|
227
|
+
else
|
|
228
|
+
graphBuilder.addRepoGraph(name, g);
|
|
229
|
+
};
|
|
230
|
+
// Detector + service-mesh edges; the updater takes the complete set at once.
|
|
231
|
+
const allCrossEdges = [];
|
|
183
232
|
// Only changed repos get jobs — skipped repos are served from their stored
|
|
184
233
|
// graph.json/signals.json below, so they are never cloned or re-parsed.
|
|
185
234
|
// This is what makes a partial cycle O(changed), not O(org).
|
|
@@ -209,10 +258,7 @@ export class KnowledgeIndexer {
|
|
|
209
258
|
onResult: (res) => {
|
|
210
259
|
if (res.graph) {
|
|
211
260
|
try {
|
|
212
|
-
|
|
213
|
-
graphWriter.addRepoGraph(res.repoName, res.graph);
|
|
214
|
-
else
|
|
215
|
-
graphBuilder.addRepoGraph(res.repoName, res.graph);
|
|
261
|
+
addRepoGraph(res.repoName, res.graph);
|
|
216
262
|
}
|
|
217
263
|
catch (e) {
|
|
218
264
|
log(`Warning: addRepoGraph failed for ${res.repoName}: ${e}`);
|
|
@@ -222,7 +268,7 @@ export class KnowledgeIndexer {
|
|
|
222
268
|
workspaceMaps.set(res.repoName, res.workspaceMap);
|
|
223
269
|
repoStats.push({ name: res.repoName, chunkCount: res.chunkCount, language: res.language });
|
|
224
270
|
if (res.chunked) {
|
|
225
|
-
repoChunkResults.set(res.repoName, { changedFiles: res.changedFiles, deletedFiles: res.deletedFiles, fileIndex: res.fileIndex ?? {}, sha: res.sha, shardComplete: res.shardComplete, workingTree: res.workingTree });
|
|
271
|
+
repoChunkResults.set(res.repoName, { changedFiles: res.changedFiles, deletedFiles: res.deletedFiles, fileIndex: res.fileIndex ?? {}, sha: res.sha, shardComplete: res.shardComplete, shardPath: res.shardPath, workingTree: res.workingTree });
|
|
226
272
|
if (res.shardPath)
|
|
227
273
|
shardPaths.push(res.shardPath);
|
|
228
274
|
}
|
|
@@ -233,23 +279,22 @@ export class KnowledgeIndexer {
|
|
|
233
279
|
},
|
|
234
280
|
});
|
|
235
281
|
// Skipped repos: their per-repo graphs were persisted when they were last
|
|
236
|
-
// indexed —
|
|
237
|
-
// graph never accumulates)
|
|
238
|
-
//
|
|
282
|
+
// indexed — a rebuild streams each into the system-graph writer (one at a
|
|
283
|
+
// time, the graph never accumulates); an in-place update already has them.
|
|
284
|
+
// Either way, rehydrate the persisted workspace packages for cross-repo
|
|
285
|
+
// correlation. No clone, no AST parse.
|
|
239
286
|
for (const name of skippedRepos) {
|
|
240
287
|
const meta = skippedMeta.get(name);
|
|
241
288
|
repoStats.push({ name, chunkCount: meta?.chunkCount ?? 0, language: '' });
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
if (
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
289
|
+
if (!graphUpdater) {
|
|
290
|
+
try {
|
|
291
|
+
const g = await storage.blobs.getJson(`${name}/graph.json`);
|
|
292
|
+
if (g)
|
|
293
|
+
addRepoGraph(name, g);
|
|
294
|
+
}
|
|
295
|
+
catch (e) {
|
|
296
|
+
log(`Warning: stored graph load failed for ${name}: ${e}`);
|
|
249
297
|
}
|
|
250
|
-
}
|
|
251
|
-
catch (e) {
|
|
252
|
-
log(`Warning: stored graph load failed for ${name}: ${e}`);
|
|
253
298
|
}
|
|
254
299
|
if (meta?.workspacePackages?.length) {
|
|
255
300
|
workspaceMaps.set(name, {
|
|
@@ -260,57 +305,79 @@ export class KnowledgeIndexer {
|
|
|
260
305
|
});
|
|
261
306
|
}
|
|
262
307
|
}
|
|
263
|
-
//
|
|
264
|
-
//
|
|
265
|
-
//
|
|
266
|
-
//
|
|
267
|
-
//
|
|
268
|
-
report({ phase: 'dedup', message: '
|
|
269
|
-
const chunksPath =
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
const prevPath = join(basePath, 'chunks.prev.ndjson');
|
|
278
|
-
await storage.blobs.getBytes('chunks.json', { toFile: prevPath });
|
|
279
|
-
const currentRepos = new Set(repos.map((r) => r.name));
|
|
280
|
-
const fullyRechunked = new Set([...repoChunkResults.entries()].filter(([, r]) => r.shardComplete).map(([name]) => name));
|
|
281
|
-
// A partial shard's fileIndex lists every file the repo still has: carry
|
|
282
|
-
// forward only those, minus the ones re-chunked this cycle.
|
|
283
|
-
const partial = new Map([...repoChunkResults.entries()]
|
|
284
|
-
.filter(([, r]) => !r.shardComplete)
|
|
285
|
-
.map(([name, r]) => [name, { files: r.fileIndex, changed: new Set(r.changedFiles) }]));
|
|
286
|
-
carryForward = {
|
|
287
|
-
prevPath,
|
|
288
|
-
keep: (c) => {
|
|
289
|
-
if (!currentRepos.has(c.repoName))
|
|
290
|
-
return false; // repos removed from the org drop out
|
|
291
|
-
if (fullyRechunked.has(c.repoName))
|
|
292
|
-
return false; // complete shard = replaces the repo wholesale
|
|
293
|
-
const p = partial.get(c.repoName);
|
|
294
|
-
return !p || (c.filePath in p.files && !p.changed.has(c.filePath));
|
|
295
|
-
},
|
|
296
|
-
};
|
|
308
|
+
// Write each re-chunked repo's chunk file (<repo>/chunks.ndjson) from its
|
|
309
|
+
// shard, so a cycle's chunk I/O covers the repos that changed; skipped
|
|
310
|
+
// repos keep their files untouched. A partial shard (incremental re-chunk)
|
|
311
|
+
// holds only the changed files: the repo's previous chunks of files it
|
|
312
|
+
// still has and didn't re-chunk are carried forward from its own file.
|
|
313
|
+
report({ phase: 'dedup', message: 'Writing chunk files...', percent: 68, etaSeconds: -1 });
|
|
314
|
+
const chunksPath = basePath;
|
|
315
|
+
const fullyRechunked = new Set([...repoChunkResults.entries()].filter(([, r]) => r.shardComplete).map(([name]) => name));
|
|
316
|
+
// An index from before per-repo files: split the legacy project-wide file
|
|
317
|
+
// once for every repo whose previous chunks this cycle keeps.
|
|
318
|
+
const needPrevious = new Set();
|
|
319
|
+
for (const r of repos) {
|
|
320
|
+
if (!fullyRechunked.has(r.name) && !(await storage.blobs.exists(repoChunksKey(r.name))))
|
|
321
|
+
needPrevious.add(r.name);
|
|
297
322
|
}
|
|
298
|
-
const
|
|
299
|
-
if (
|
|
300
|
-
|
|
301
|
-
|
|
323
|
+
const legacyTotals = await splitLegacyChunks(storage.blobs, basePath, needPrevious);
|
|
324
|
+
if (legacyTotals.size > 0)
|
|
325
|
+
log(`Split ${legacyTotals.size} repos out of the project-wide ${LEGACY_CHUNKS_KEY}`);
|
|
326
|
+
const repoTotals = new Map();
|
|
327
|
+
for (const [name, r] of repoChunkResults) {
|
|
328
|
+
let carryForward;
|
|
329
|
+
if (!r.shardComplete && (await storage.blobs.exists(repoChunksKey(name)))) {
|
|
330
|
+
// Pull the previous file to local scratch first — putNdjson overwrites
|
|
331
|
+
// the blob (Mongo deletes the GridFS file before upload), so reading
|
|
332
|
+
// and writing the same key concurrently would corrupt or truncate it.
|
|
333
|
+
const prevPath = join(basePath, name, 'chunks.prev.ndjson');
|
|
334
|
+
mkdirSync(join(basePath, name), { recursive: true });
|
|
335
|
+
await storage.blobs.getBytes(repoChunksKey(name), { toFile: prevPath });
|
|
336
|
+
const changed = new Set(r.changedFiles);
|
|
337
|
+
carryForward = { prevPath, keep: (c) => c.filePath in r.fileIndex && !changed.has(c.filePath) };
|
|
302
338
|
}
|
|
303
|
-
|
|
339
|
+
const merged = await mergeShardsToChunks(r.shardPath ? [r.shardPath] : [], storage.blobs, repoChunksKey(name), carryForward);
|
|
340
|
+
if (carryForward) {
|
|
341
|
+
try {
|
|
342
|
+
rmSync(carryForward.prevPath, { force: true });
|
|
343
|
+
}
|
|
344
|
+
catch { /* scratch */ }
|
|
345
|
+
}
|
|
346
|
+
repoTotals.set(name, { chunks: merged.kept, tokens: merged.tokens });
|
|
304
347
|
}
|
|
305
|
-
const mergedChunkCount = merged.kept;
|
|
306
|
-
const mergedTokenSum = merged.tokens;
|
|
307
|
-
log(`Saved ${mergedChunkCount} chunks to ${chunksPath}`);
|
|
308
348
|
for (const sp of shardPaths) {
|
|
309
349
|
try {
|
|
310
350
|
rmSync(sp, { force: true });
|
|
311
351
|
}
|
|
312
352
|
catch { /* ok */ }
|
|
313
353
|
}
|
|
354
|
+
// Every current repo has its own file now; the legacy one is no longer read.
|
|
355
|
+
if (await storage.blobs.exists(LEGACY_CHUNKS_KEY)) {
|
|
356
|
+
let allSplit = true;
|
|
357
|
+
for (const r of repos)
|
|
358
|
+
if (!(await storage.blobs.exists(repoChunksKey(r.name)))) {
|
|
359
|
+
allSplit = false;
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
if (allSplit)
|
|
363
|
+
await storage.blobs.delete(LEGACY_CHUNKS_KEY);
|
|
364
|
+
}
|
|
365
|
+
// Repos not re-chunked this cycle keep the totals they had.
|
|
366
|
+
const prevRepoStats = new Map((prevStats?.repos ?? []).map((r) => [r.name, r]));
|
|
367
|
+
for (const r of repos) {
|
|
368
|
+
if (repoTotals.has(r.name))
|
|
369
|
+
continue;
|
|
370
|
+
const prev = prevRepoStats.get(r.name);
|
|
371
|
+
repoTotals.set(r.name, legacyTotals.get(r.name)
|
|
372
|
+
?? { chunks: prev?.chunkCount ?? skippedMeta.get(r.name)?.chunkCount ?? 0, tokens: prev?.chunkTokens ?? 0 });
|
|
373
|
+
}
|
|
374
|
+
let mergedChunkCount = 0;
|
|
375
|
+
let mergedTokenSum = 0;
|
|
376
|
+
for (const t of repoTotals.values()) {
|
|
377
|
+
mergedChunkCount += t.chunks;
|
|
378
|
+
mergedTokenSum += t.tokens;
|
|
379
|
+
}
|
|
380
|
+
log(`Saved chunks of ${repoChunkResults.size} repos (${mergedChunkCount} chunks in the index)`);
|
|
314
381
|
// 7. Detect cross-repo edges (14 strategies) — correlated from the
|
|
315
382
|
// per-repo signals persisted at index time. In the bounded-scratch writer
|
|
316
383
|
// the clones are already discarded (and skipped repos were never cloned),
|
|
@@ -329,9 +396,11 @@ export class KnowledgeIndexer {
|
|
|
329
396
|
catch { /* a repo without signals just contributes no edges this cycle */ }
|
|
330
397
|
}
|
|
331
398
|
const crossEdges = correlateCrossRepoEdges(signalsMap, workspaceMaps);
|
|
399
|
+
for (const e of crossEdges)
|
|
400
|
+
allCrossEdges.push(e); // spread overflows the stack past ~100k edges
|
|
332
401
|
if (graphWriter)
|
|
333
402
|
graphWriter.addCrossRepoEdges(crossEdges);
|
|
334
|
-
else
|
|
403
|
+
else if (graphBuilder)
|
|
335
404
|
graphBuilder.addCrossRepoEdges(crossEdges);
|
|
336
405
|
crossRepoEdgeCount = crossEdges.length;
|
|
337
406
|
log(`Detected ${crossEdges.length} cross-repo edges (signals from ${signalsMap.size}/${repos.length} repos)`);
|
|
@@ -350,9 +419,11 @@ export class KnowledgeIndexer {
|
|
|
350
419
|
},
|
|
351
420
|
});
|
|
352
421
|
if (meshEdges.length > 0) {
|
|
422
|
+
for (const e of meshEdges)
|
|
423
|
+
allCrossEdges.push(e);
|
|
353
424
|
if (graphWriter)
|
|
354
425
|
graphWriter.addCrossRepoEdges(meshEdges);
|
|
355
|
-
else
|
|
426
|
+
else if (graphBuilder)
|
|
356
427
|
graphBuilder.addCrossRepoEdges(meshEdges);
|
|
357
428
|
crossRepoEdgeCount += meshEdges.length;
|
|
358
429
|
log(`Service mesh: ${meshEdges.length} edges inferred`);
|
|
@@ -372,6 +443,37 @@ export class KnowledgeIndexer {
|
|
|
372
443
|
}
|
|
373
444
|
// 9. Persist the system graph.
|
|
374
445
|
report({ phase: 'graphing', message: 'Saving system graph...', percent: 90, etaSeconds: -1 });
|
|
446
|
+
if (graphUpdater && !graphUpdateFailed) {
|
|
447
|
+
try {
|
|
448
|
+
graphUpdater.replaceCrossRepoEdges(allCrossEdges);
|
|
449
|
+
const { nodeCount, edgeCount } = graphUpdater.finalize();
|
|
450
|
+
log(`Updated project graph in place (${reposToIndex.length} re-indexed, ${removedRepos.length} removed repos: ${nodeCount} nodes, ${edgeCount} edges)`);
|
|
451
|
+
await uploadSystemGraphIfRemote(storage, basePath, log);
|
|
452
|
+
}
|
|
453
|
+
catch (e) {
|
|
454
|
+
graphUpdateFailure(e);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (graphUpdater && graphUpdateFailed) {
|
|
458
|
+
try {
|
|
459
|
+
graphUpdater.abort();
|
|
460
|
+
}
|
|
461
|
+
catch { /* already rolled back */ }
|
|
462
|
+
graphWriter = await createSystemGraphSqliteWriter(basePath);
|
|
463
|
+
if (graphWriter) {
|
|
464
|
+
for (const r of repos) {
|
|
465
|
+
try {
|
|
466
|
+
const g = await storage.blobs.getJson(`${r.name}/graph.json`);
|
|
467
|
+
if (g)
|
|
468
|
+
graphWriter.addRepoGraph(r.name, g);
|
|
469
|
+
}
|
|
470
|
+
catch (e) {
|
|
471
|
+
log(`Warning: stored graph load failed for ${r.name}: ${e}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
graphWriter.addCrossRepoEdges(allCrossEdges);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
375
477
|
if (graphWriter) {
|
|
376
478
|
// Streamed path: nodes/edges already written per-repo; backfill degrees +
|
|
377
479
|
// close. Community detection is skipped — `systemCommunity` has no readers.
|
|
@@ -385,7 +487,7 @@ export class KnowledgeIndexer {
|
|
|
385
487
|
console.error(`[knowledge-core] Could not persist system graph (streamed): ${msg}. Cross-repo graph tools will be unavailable; search and embeddings are unaffected.`);
|
|
386
488
|
}
|
|
387
489
|
}
|
|
388
|
-
else {
|
|
490
|
+
else if (graphBuilder) {
|
|
389
491
|
// In-memory fallback (no sqlite driver): detect communities, then write
|
|
390
492
|
// the whole graph to sqlite if a driver appears, else the legacy JSON blob.
|
|
391
493
|
graphBuilder.detectCommunities();
|
|
@@ -406,8 +508,8 @@ export class KnowledgeIndexer {
|
|
|
406
508
|
console.error(`[knowledge-core] Could not persist system graph (${graphBuilder.nodeCount} nodes, ${graphBuilder.edgeCount} edges): ${msg}. Cross-repo graph tools will be unavailable; search and embeddings are unaffected.`);
|
|
407
509
|
}
|
|
408
510
|
}
|
|
409
|
-
// 11. (
|
|
410
|
-
//
|
|
511
|
+
// 11. (The chunk files were written right after chunking, above — chunks
|
|
512
|
+
// stream from shards to blobs and never sit in memory through the graph build.)
|
|
411
513
|
// 11b. Save stale files list (for incremental embedding cleanup).
|
|
412
514
|
// Includes both deleted AND modified files: chunk ids are position-keyed
|
|
413
515
|
// (chunker.ts chunkId), so an in-place edit at the same line range produces
|
|
@@ -435,6 +537,15 @@ export class KnowledgeIndexer {
|
|
|
435
537
|
allStaleFiles.push(f);
|
|
436
538
|
}
|
|
437
539
|
await storage.blobs.putText('deleted_files.json', JSON.stringify(allStaleFiles));
|
|
540
|
+
// Repos whose chunk files changed, or that were removed, since the embed
|
|
541
|
+
// step last ran: embedChunks diffs, embeds and sweeps only those. Merged
|
|
542
|
+
// with a list a previous embed hasn't applied yet.
|
|
543
|
+
const pending = await readEmbedPending(storage.blobs);
|
|
544
|
+
await storage.blobs.putJson(EMBED_PENDING_KEY, {
|
|
545
|
+
all: pending.all,
|
|
546
|
+
repos: [...new Set([...pending.repos, ...repoChunkResults.keys()])],
|
|
547
|
+
removed: [...new Set([...pending.removed, ...removedRepos])],
|
|
548
|
+
});
|
|
438
549
|
// 12. Save per-repo metadata
|
|
439
550
|
for (const repo of reposToIndex) {
|
|
440
551
|
const result = repoChunkResults.get(repo.name);
|
|
@@ -476,7 +587,11 @@ export class KnowledgeIndexer {
|
|
|
476
587
|
// of walking every repo's index_meta (800 reads per call at org scale).
|
|
477
588
|
try {
|
|
478
589
|
await storage.blobs.putJson('index_stats.json', {
|
|
479
|
-
repos: repoStats
|
|
590
|
+
repos: repoStats.map((r) => ({
|
|
591
|
+
...r,
|
|
592
|
+
chunkCount: repoTotals.get(r.name)?.chunks ?? r.chunkCount,
|
|
593
|
+
chunkTokens: repoTotals.get(r.name)?.tokens ?? 0,
|
|
594
|
+
})),
|
|
480
595
|
totalChunks: mergedChunkCount,
|
|
481
596
|
totalTokens: mergedTokenSum,
|
|
482
597
|
crossRepoEdges: crossRepoEdgeCount,
|
|
@@ -508,19 +623,37 @@ export class KnowledgeIndexer {
|
|
|
508
623
|
const startTime = Date.now();
|
|
509
624
|
const storage = resolveStorage(project, config);
|
|
510
625
|
const basePath = storage.basePath;
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
626
|
+
// The index's repos and totals come from the stats rollup buildKB writes
|
|
627
|
+
// (cross-repo edges are counted there too); their chunks from each repo's
|
|
628
|
+
// chunk file (repo-chunks.ts).
|
|
629
|
+
const indexStats = await storage.blobs
|
|
630
|
+
.getJson('index_stats.json')
|
|
631
|
+
.catch(() => null);
|
|
632
|
+
const indexedRepos = indexStats?.repos ?? [];
|
|
633
|
+
if (indexedRepos.length === 0) {
|
|
634
|
+
throw new Error(`No chunks found — run Build KB first (no indexed repos under ${basePath}).`);
|
|
514
635
|
}
|
|
636
|
+
const repoNames = indexedRepos.map((r) => r.name);
|
|
637
|
+
const totalChunks = indexStats?.totalChunks ?? 0;
|
|
638
|
+
const totalTokens = indexStats?.totalTokens ?? 0;
|
|
639
|
+
const crossRepoEdges = indexStats?.crossRepoEdges ?? 0;
|
|
640
|
+
const repoStatsOut = indexedRepos.map((r) => ({ name: r.name, chunkCount: r.chunkCount ?? 0, language: '' }));
|
|
515
641
|
// Open vector store. healCorrupt: this is the write/rebuild path, so if a
|
|
516
642
|
// prior run left the table corrupt (killed mid-write → 0-byte fragment),
|
|
517
|
-
// drop it and rebuild from
|
|
643
|
+
// drop it and rebuild from the chunk files rather than failing every reindex.
|
|
518
644
|
const vectorStore = storage.vectors;
|
|
519
645
|
await vectorStore.init({ healCorrupt: true });
|
|
520
|
-
//
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
646
|
+
// Which repos to diff, embed and sweep: those whose chunk files changed, or
|
|
647
|
+
// that were removed, since the last embed (buildKB's list) — so a cycle's
|
|
648
|
+
// embed work tracks the change, not the corpus. A full pass over every repo
|
|
649
|
+
// (plus a sweep of rows no chunk file lists) when the list predates this
|
|
650
|
+
// version, or the table is empty (first run, or a corrupt store dropped).
|
|
651
|
+
const toEmbed = await readEmbedPending(storage.blobs);
|
|
652
|
+
const rowCount = (await vectorStore.getStats().catch(() => null))?.rowCount ?? 0;
|
|
653
|
+
const full = toEmbed.all || rowCount === 0;
|
|
654
|
+
const current = new Set(repoNames);
|
|
655
|
+
const scope = full ? repoNames : [...new Set(toEmbed.repos)].filter((n) => current.has(n));
|
|
656
|
+
const removedRepos = toEmbed.removed.filter((n) => !current.has(n));
|
|
524
657
|
// Rows of changed/deleted files (listed by buildKB) are stale. Chunk ids are
|
|
525
658
|
// hash(repoName, filePath, startLine, endLine), so a changed file's new
|
|
526
659
|
// chunks can take ids its old rows hold: note each stale row's
|
|
@@ -546,31 +679,24 @@ export class KnowledgeIndexer {
|
|
|
546
679
|
}
|
|
547
680
|
}
|
|
548
681
|
}
|
|
549
|
-
// Which chunks are already embedded (id-set diff). Bounded:
|
|
550
|
-
// id strings, never the chunk bodies.
|
|
682
|
+
// Which of the scope's chunks are already embedded (id-set diff). Bounded:
|
|
683
|
+
// holds only the id strings, never the chunk bodies.
|
|
551
684
|
const existingIds = new Set();
|
|
552
|
-
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
const existingChunks = await vectorStore.getChunkIds(project);
|
|
556
|
-
for (const id of existingChunks)
|
|
557
|
-
existingIds.add(id);
|
|
558
|
-
}
|
|
685
|
+
if (rowCount > 0 && scope.length > 0) {
|
|
686
|
+
for (const id of await vectorStore.getChunkIds(project, full ? undefined : scope))
|
|
687
|
+
existingIds.add(id);
|
|
559
688
|
}
|
|
560
|
-
catch { /* first run — no existing data */ }
|
|
561
689
|
for (const id of staleRows.keys())
|
|
562
690
|
existingIds.delete(id);
|
|
563
|
-
// Pass 1 — stream
|
|
691
|
+
// Pass 1 — stream the scope's chunk files to find what needs embedding,
|
|
564
692
|
// WITHOUT ever holding all chunks in memory. At org scale (~810k chunks,
|
|
565
693
|
// each carrying full source + contextualized text) the old
|
|
566
694
|
// `readChunksFile()` array was multi-GB and OOM'd the embed step (the
|
|
567
695
|
// crash surfaced during "Removing stale chunks", but the array — loaded
|
|
568
696
|
// here, before deletion — was the resident hog). Streaming bounds memory
|
|
569
697
|
// to the id-set + one in-flight batch (see pass 2 below).
|
|
570
|
-
let
|
|
571
|
-
let totalTokens = 0;
|
|
698
|
+
let scopeChunks = 0;
|
|
572
699
|
let newChunkCount = 0;
|
|
573
|
-
const repoChunkCounts = new Map();
|
|
574
700
|
const listedIds = new Set();
|
|
575
701
|
// A reservoir sample of named chunks: the source of the query-like probes
|
|
576
702
|
// that calibrate the vector index's nprobes (maintainVectorIndex).
|
|
@@ -578,21 +704,22 @@ export class KnowledgeIndexer {
|
|
|
578
704
|
let named = 0;
|
|
579
705
|
let seed = 0x2545f491;
|
|
580
706
|
const rand = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 2 ** 32;
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
const j = Math.floor(rand() * named);
|
|
592
|
-
if (j < CALIBRATION_PROBES)
|
|
593
|
-
probeChunks[j] = c;
|
|
594
|
-
}
|
|
707
|
+
const sampleProbe = (c) => {
|
|
708
|
+
if (!c.entityName || c.entityName.length < 4)
|
|
709
|
+
return;
|
|
710
|
+
named++;
|
|
711
|
+
if (probeChunks.length < CALIBRATION_PROBES)
|
|
712
|
+
probeChunks.push(c);
|
|
713
|
+
else {
|
|
714
|
+
const j = Math.floor(rand() * named);
|
|
715
|
+
if (j < CALIBRATION_PROBES)
|
|
716
|
+
probeChunks[j] = c;
|
|
595
717
|
}
|
|
718
|
+
};
|
|
719
|
+
for await (const c of iterateRepoChunks(storage.blobs, scope)) {
|
|
720
|
+
scopeChunks++;
|
|
721
|
+
listedIds.add(c.id);
|
|
722
|
+
sampleProbe(c);
|
|
596
723
|
if (existingIds.has(c.id))
|
|
597
724
|
continue;
|
|
598
725
|
// Same id, same text as a stale row: keep that row as it is.
|
|
@@ -603,14 +730,20 @@ export class KnowledgeIndexer {
|
|
|
603
730
|
}
|
|
604
731
|
newChunkCount++;
|
|
605
732
|
}
|
|
606
|
-
log(
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
//
|
|
610
|
-
//
|
|
611
|
-
//
|
|
612
|
-
|
|
733
|
+
log(full
|
|
734
|
+
? `Loaded ${scopeChunks} chunks of all ${scope.length} repos`
|
|
735
|
+
: `Loaded ${scopeChunks} chunks of ${scope.length} changed repos (${totalChunks} in the index)`);
|
|
736
|
+
// The chunk files are the corpus: the scope's rows they no longer list — a
|
|
737
|
+
// file deletion a fallback re-chunk caught, chunks from an older id scheme;
|
|
738
|
+
// in a full pass also rows of repos no longer indexed — are swept, after the
|
|
739
|
+
// embed loop so their vectors can be reused first (their ids can't collide
|
|
740
|
+
// with a listed chunk). Removed repos' rows go by repo name. A full pass
|
|
741
|
+
// that finds no chunks at all is treated as a failed build, not as
|
|
742
|
+
// "delete everything".
|
|
743
|
+
const orphanIds = full && scopeChunks === 0 ? [] : [...existingIds].filter((id) => !listedIds.has(id));
|
|
613
744
|
const staleLeft = [...staleRows].flatMap(([id, hashes]) => [...hashes].map((h) => ({ id, contentHash: h })));
|
|
745
|
+
// At least this many rows go (a removed repo has at least one).
|
|
746
|
+
const rowsDeleted = staleLeft.length + orphanIds.length + removedRepos.length;
|
|
614
747
|
const sweep = async () => {
|
|
615
748
|
// A stale row whose id no listed chunk took can go by id (cheap IN-list
|
|
616
749
|
// deletes); only ids a new chunk now holds need the exact pair.
|
|
@@ -619,12 +752,33 @@ export class KnowledgeIndexer {
|
|
|
619
752
|
if (staleLeft.length > 0)
|
|
620
753
|
log(`Removing ${staleLeft.length} stale rows of changed/deleted files...`);
|
|
621
754
|
if (orphanIds.length > 0)
|
|
622
|
-
log(`Removing ${orphanIds.length} rows no
|
|
755
|
+
log(`Removing ${orphanIds.length} rows no chunk file lists...`);
|
|
756
|
+
if (removedRepos.length > 0)
|
|
757
|
+
log(`Removing the rows of ${removedRepos.length} repos no longer indexed...`);
|
|
623
758
|
await vectorStore.deleteRows(takenIds);
|
|
624
759
|
await vectorStore.deleteChunksByIds(byId);
|
|
760
|
+
await vectorStore.deleteRepoRows(project, removedRepos);
|
|
761
|
+
};
|
|
762
|
+
// Probes come from the scope's chunks; a small scope is topped up from
|
|
763
|
+
// other repos' files, visited in a seeded random order — read only when a
|
|
764
|
+
// calibration actually runs.
|
|
765
|
+
const probes = async () => {
|
|
766
|
+
if (named < CALIBRATION_PROBES * 20) {
|
|
767
|
+
const inScope = new Set(scope);
|
|
768
|
+
const others = repoNames.filter((n) => !inScope.has(n));
|
|
769
|
+
for (let i = others.length - 1; i > 0; i--) {
|
|
770
|
+
const j = Math.floor(rand() * (i + 1));
|
|
771
|
+
[others[i], others[j]] = [others[j], others[i]];
|
|
772
|
+
}
|
|
773
|
+
for (const name of others) {
|
|
774
|
+
for await (const c of iterateRepoChunks(storage.blobs, [name]))
|
|
775
|
+
sampleProbe(c);
|
|
776
|
+
if (named >= CALIBRATION_PROBES * 20)
|
|
777
|
+
break;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return probeChunks.length > 0 ? createEmbeddingProvider(config.embedding).embed(calibrationProbeTexts(probeChunks)) : [];
|
|
625
781
|
};
|
|
626
|
-
const repoNames = [...repoChunkCounts.keys()];
|
|
627
|
-
const probes = async () => probeChunks.length > 0 ? createEmbeddingProvider(config.embedding).embed(calibrationProbeTexts(probeChunks)) : [];
|
|
628
782
|
if (newChunkCount === 0 && deletedFiles.length === 0) {
|
|
629
783
|
await sweep();
|
|
630
784
|
// All vectors already present, so DON'T re-embed. But build the full-text
|
|
@@ -640,7 +794,8 @@ export class KnowledgeIndexer {
|
|
|
640
794
|
// (build / due retrain / optimize — a prior run may also have died before
|
|
641
795
|
// folding its appends in).
|
|
642
796
|
await vectorStore.ensureScalarIndexes();
|
|
643
|
-
const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: 0, probes });
|
|
797
|
+
const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: 0, rowsDeleted, probes });
|
|
798
|
+
await storage.blobs.putJson(EMBED_PENDING_KEY, { all: false, repos: [], removed: [] });
|
|
644
799
|
// optimize() prunes dataset versions past the retention window; readers
|
|
645
800
|
// only reopen on a generation bump, so signal them or a reader pinned to
|
|
646
801
|
// a pruned version would lose its files.
|
|
@@ -648,7 +803,7 @@ export class KnowledgeIndexer {
|
|
|
648
803
|
report({ phase: 'done', message: 'All chunks already embedded', percent: 100, etaSeconds: 0 });
|
|
649
804
|
return {
|
|
650
805
|
project,
|
|
651
|
-
repos:
|
|
806
|
+
repos: repoStatsOut,
|
|
652
807
|
totalChunks,
|
|
653
808
|
totalTokens,
|
|
654
809
|
embeddingProvider: 'cached',
|
|
@@ -675,7 +830,7 @@ export class KnowledgeIndexer {
|
|
|
675
830
|
};
|
|
676
831
|
const batchSize = envInt('CODE_SEARCH_EMBEDDING_BATCH_SIZE', isOllama ? 10 : 128);
|
|
677
832
|
const concurrency = isOllama ? 1 : envInt('CODE_SEARCH_EMBEDDING_CONCURRENCY', 8);
|
|
678
|
-
log(`Embedding ${newChunkCount} new chunks with ${embedder.name} (${totalChunks - newChunkCount}
|
|
833
|
+
log(`Embedding ${newChunkCount} new chunks with ${embedder.name} (${totalChunks - newChunkCount} already embedded, batch ${batchSize} × concurrency ${concurrency})...`);
|
|
679
834
|
// The contentHash index must exist before the reuse lookups below (an
|
|
680
835
|
// upgraded table gets the column and its index here, not after the loop).
|
|
681
836
|
await vectorStore.ensureScalarIndexes();
|
|
@@ -718,7 +873,7 @@ export class KnowledgeIndexer {
|
|
|
718
873
|
reused += fromStore;
|
|
719
874
|
return vectors;
|
|
720
875
|
};
|
|
721
|
-
// Stream
|
|
876
|
+
// Stream the scope's chunk files a second time and embed only the new ones, in batches.
|
|
722
877
|
// Up to `concurrency` batches are in flight at once. Embedded rows go into
|
|
723
878
|
// a buffer that is appended to LanceDB once it holds WRITE_ROWS rows (and
|
|
724
879
|
// once more at the end): every append is a LanceDB commit — a new version
|
|
@@ -796,7 +951,7 @@ export class KnowledgeIndexer {
|
|
|
796
951
|
void task.finally(() => inFlight.delete(task));
|
|
797
952
|
};
|
|
798
953
|
let batch = [];
|
|
799
|
-
for await (const c of storage.blobs
|
|
954
|
+
for await (const c of iterateRepoChunks(storage.blobs, scope)) {
|
|
800
955
|
if (aborted)
|
|
801
956
|
break;
|
|
802
957
|
if (existingIds.has(c.id))
|
|
@@ -839,15 +994,17 @@ export class KnowledgeIndexer {
|
|
|
839
994
|
// last training reach the retrain ratio, and optimizes (folds this run's
|
|
840
995
|
// appends into every index, compacts, prunes).
|
|
841
996
|
await vectorStore.ensureScalarIndexes();
|
|
842
|
-
const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: stored, probes });
|
|
997
|
+
const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: stored, rowsDeleted, probes });
|
|
843
998
|
log(`Stored ${newChunkCount} new chunks in LanceDB (${reused} reused by content, ${deletedFiles.length} files re-planned)`);
|
|
844
999
|
// The stale-file list is applied — clear it, or a later no-change cycle
|
|
845
1000
|
// (buildKB returns early without rewriting it) would wipe those files again
|
|
846
1001
|
// with nothing left to re-embed them.
|
|
847
1002
|
if (deletedFiles.length > 0)
|
|
848
1003
|
await storage.blobs.putText('deleted_files.json', '[]');
|
|
849
|
-
//
|
|
850
|
-
|
|
1004
|
+
// Likewise the list of repos to embed: all applied.
|
|
1005
|
+
await storage.blobs.putJson(EMBED_PENDING_KEY, { all: false, repos: [], removed: [] });
|
|
1006
|
+
// Record the embedding space on the repos embedded this run.
|
|
1007
|
+
for (const repoName of scope) {
|
|
851
1008
|
const metaKey = `${repoName}/index_meta.json`;
|
|
852
1009
|
try {
|
|
853
1010
|
const meta = await storage.blobs.getJson(metaKey);
|
|
@@ -879,7 +1036,7 @@ export class KnowledgeIndexer {
|
|
|
879
1036
|
report({ phase: 'done', message: `Embedded ${newChunkCount} new chunks (${deletedFiles.length} removed) in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0 });
|
|
880
1037
|
return {
|
|
881
1038
|
project,
|
|
882
|
-
repos:
|
|
1039
|
+
repos: repoStatsOut,
|
|
883
1040
|
totalChunks,
|
|
884
1041
|
totalTokens,
|
|
885
1042
|
embeddingProvider: embedder.name,
|
|
@@ -1038,7 +1195,7 @@ function detectLanguage(repoPath) {
|
|
|
1038
1195
|
/**
|
|
1039
1196
|
* Build KB from a directory path — fast, no embedding.
|
|
1040
1197
|
* Profiles repos, chunks files, builds AST graphs, detects cross-repo edges.
|
|
1041
|
-
* Saves
|
|
1198
|
+
* Saves each re-chunked repo's chunk file for later embedding.
|
|
1042
1199
|
*/
|
|
1043
1200
|
export async function buildKBFromPath(projectName, directoryPath, opts) {
|
|
1044
1201
|
const log = opts?.onProgress ?? (() => { });
|
|
@@ -1053,7 +1210,8 @@ export async function buildKBFromPath(projectName, directoryPath, opts) {
|
|
|
1053
1210
|
}
|
|
1054
1211
|
/**
|
|
1055
1212
|
* Embed chunks for a project that already has KB built.
|
|
1056
|
-
* Reads
|
|
1213
|
+
* Reads the chunk files of repos changed since the last embed, embeds the new
|
|
1214
|
+
* chunks with the configured provider, stores them in LanceDB.
|
|
1057
1215
|
*/
|
|
1058
1216
|
export async function embedFromPath(projectName, opts) {
|
|
1059
1217
|
const indexer = new KnowledgeIndexer();
|