@esankhan3/anvil-knowledge-core 0.3.14 → 0.4.1
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/dist/__tests__/cross-repo-detector.test.d.ts +9 -0
- package/dist/__tests__/cross-repo-detector.test.d.ts.map +1 -0
- package/dist/__tests__/cross-repo-detector.test.js +105 -0
- package/dist/__tests__/cross-repo-detector.test.js.map +1 -0
- package/dist/__tests__/literal-tier-integration.test.d.ts +7 -0
- package/dist/__tests__/literal-tier-integration.test.d.ts.map +1 -0
- package/dist/__tests__/literal-tier-integration.test.js +84 -0
- package/dist/__tests__/literal-tier-integration.test.js.map +1 -0
- package/dist/__tests__/partial-cycle-chunks.test.d.ts +15 -0
- package/dist/__tests__/partial-cycle-chunks.test.d.ts.map +1 -0
- package/dist/__tests__/partial-cycle-chunks.test.js +133 -0
- package/dist/__tests__/partial-cycle-chunks.test.js.map +1 -0
- package/dist/__tests__/retriever-fusion.test.js +34 -1
- package/dist/__tests__/retriever-fusion.test.js.map +1 -1
- package/dist/__tests__/storage-graph-accessor.test.d.ts +11 -0
- package/dist/__tests__/storage-graph-accessor.test.d.ts.map +1 -0
- package/dist/__tests__/storage-graph-accessor.test.js +70 -0
- package/dist/__tests__/storage-graph-accessor.test.js.map +1 -0
- package/dist/__tests__/storage-mongo-blob.test.d.ts +11 -0
- package/dist/__tests__/storage-mongo-blob.test.d.ts.map +1 -0
- package/dist/__tests__/storage-mongo-blob.test.js +118 -0
- package/dist/__tests__/storage-mongo-blob.test.js.map +1 -0
- package/dist/__tests__/storage-ports.test.d.ts +9 -0
- package/dist/__tests__/storage-ports.test.d.ts.map +1 -0
- package/dist/__tests__/storage-ports.test.js +276 -0
- package/dist/__tests__/storage-ports.test.js.map +1 -0
- package/dist/__tests__/storage-profile-helpers.test.d.ts +7 -0
- package/dist/__tests__/storage-profile-helpers.test.d.ts.map +1 -0
- package/dist/__tests__/storage-profile-helpers.test.js +50 -0
- package/dist/__tests__/storage-profile-helpers.test.js.map +1 -0
- package/dist/__tests__/storage-vector-integration.test.d.ts +15 -0
- package/dist/__tests__/storage-vector-integration.test.d.ts.map +1 -0
- package/dist/__tests__/storage-vector-integration.test.js +196 -0
- package/dist/__tests__/storage-vector-integration.test.js.map +1 -0
- package/dist/__tests__/vector-recall.test.d.ts +15 -0
- package/dist/__tests__/vector-recall.test.d.ts.map +1 -0
- package/dist/__tests__/vector-recall.test.js +94 -0
- package/dist/__tests__/vector-recall.test.js.map +1 -0
- package/dist/__tests__/writer-remote-pipeline.test.d.ts +2 -0
- package/dist/__tests__/writer-remote-pipeline.test.d.ts.map +1 -0
- package/dist/__tests__/writer-remote-pipeline.test.js +39 -0
- package/dist/__tests__/writer-remote-pipeline.test.js.map +1 -0
- package/dist/config.d.ts +69 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/cross-repo-detector.d.ts +70 -0
- package/dist/cross-repo-detector.d.ts.map +1 -1
- package/dist/cross-repo-detector.js +672 -812
- package/dist/cross-repo-detector.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/indexer.d.ts +17 -1
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +355 -93
- package/dist/indexer.js.map +1 -1
- package/dist/project-graph-builder.d.ts +8 -5
- package/dist/project-graph-builder.d.ts.map +1 -1
- package/dist/project-graph-builder.js +66 -66
- package/dist/project-graph-builder.js.map +1 -1
- package/dist/query-router.d.ts +7 -5
- package/dist/query-router.d.ts.map +1 -1
- package/dist/query-router.js +16 -50
- package/dist/query-router.js.map +1 -1
- package/dist/repo-pipeline.d.ts +27 -2
- package/dist/repo-pipeline.d.ts.map +1 -1
- package/dist/repo-pipeline.js +66 -11
- package/dist/repo-pipeline.js.map +1 -1
- package/dist/repo-profiler.d.ts +9 -4
- package/dist/repo-profiler.d.ts.map +1 -1
- package/dist/repo-profiler.js +49 -41
- package/dist/repo-profiler.js.map +1 -1
- package/dist/retriever.d.ts +4 -5
- package/dist/retriever.d.ts.map +1 -1
- package/dist/retriever.js +29 -14
- package/dist/retriever.js.map +1 -1
- package/dist/storage/fs-blob-store.d.ts +31 -0
- package/dist/storage/fs-blob-store.d.ts.map +1 -0
- package/dist/storage/fs-blob-store.js +163 -0
- package/dist/storage/fs-blob-store.js.map +1 -0
- package/dist/storage/index.d.ts +11 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +4 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/mongo-blob-store.d.ts +50 -0
- package/dist/storage/mongo-blob-store.d.ts.map +1 -0
- package/dist/storage/mongo-blob-store.js +264 -0
- package/dist/storage/mongo-blob-store.js.map +1 -0
- package/dist/storage/ports.d.ts +135 -0
- package/dist/storage/ports.d.ts.map +1 -0
- package/dist/storage/ports.js +12 -0
- package/dist/storage/ports.js.map +1 -0
- package/dist/storage/resolve.d.ts +78 -0
- package/dist/storage/resolve.d.ts.map +1 -0
- package/dist/storage/resolve.js +208 -0
- package/dist/storage/resolve.js.map +1 -0
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-recall.d.ts +30 -0
- package/dist/vector-recall.d.ts.map +1 -0
- package/dist/vector-recall.js +32 -0
- package/dist/vector-recall.js.map +1 -0
- package/dist/vector-store.d.ts +61 -10
- package/dist/vector-store.d.ts.map +1 -1
- package/dist/vector-store.js +184 -22
- package/dist/vector-store.js.map +1 -1
- package/package.json +4 -3
package/dist/indexer.js
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, rmSync } from 'node:fs';
|
|
2
2
|
import { join, basename } from 'node:path';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
3
4
|
import { createEmbeddingProvider } from '@esankhan3/anvil-knowledge-core';
|
|
4
|
-
import {
|
|
5
|
+
import { resolveStorage, invalidateGraphStores } from './storage/resolve.js';
|
|
6
|
+
import { FsBlobStore } from './storage/fs-blob-store.js';
|
|
5
7
|
import { ProjectGraphBuilder } from '@esankhan3/anvil-knowledge-core';
|
|
6
|
-
import {
|
|
8
|
+
import { correlateCrossRepoEdges } from './cross-repo-detector.js';
|
|
7
9
|
import { HybridRetriever } from './retriever.js';
|
|
8
10
|
import { loadKnowledgeConfig, getKnowledgeBasePath } from '@esankhan3/anvil-knowledge-core';
|
|
9
11
|
import { profileProject, loadAllProfiles } from '@esankhan3/anvil-knowledge-core';
|
|
10
12
|
import { inferServiceMesh } from '@esankhan3/anvil-knowledge-core';
|
|
11
13
|
import { computeStructuralHash } from '@esankhan3/anvil-knowledge-core';
|
|
12
14
|
import { createQueryRouter } from '@esankhan3/anvil-knowledge-core';
|
|
13
|
-
import {
|
|
14
|
-
import { writeSystemGraphSqlite,
|
|
15
|
+
import { iterateChunksFile } from './chunks-io.js';
|
|
16
|
+
import { writeSystemGraphSqlite, createSystemGraphSqliteWriter } from './graph-store.js';
|
|
15
17
|
import { resolveIndexConcurrency, runReposPooled } from './index-pool.js';
|
|
16
|
-
import { processRepoPipeline, getRepoSha, readRepoIndexMeta } from './repo-pipeline.js';
|
|
18
|
+
import { processRepoPipeline, getRepoSha, getRemoteSha, readRepoIndexMeta } from './repo-pipeline.js';
|
|
17
19
|
// ---------------------------------------------------------------------------
|
|
18
20
|
// SHA-based staleness detection
|
|
19
21
|
// ---------------------------------------------------------------------------
|
|
20
22
|
// RepoIndexMeta, getRepoSha, readRepoIndexMeta moved to repo-pipeline.ts (shared
|
|
21
23
|
// with the worker). writeRepoIndexMeta stays here — only buildKB writes meta.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
// Routed through BlobStorePort (P0c); putJson pretty-prints, byte-identical to
|
|
25
|
+
// the prior JSON.stringify(meta, null, 2).
|
|
26
|
+
async function writeRepoIndexMeta(blobs, repoName, meta) {
|
|
27
|
+
await blobs.putJson(`${repoName}/index_meta.json`, meta);
|
|
26
28
|
}
|
|
27
29
|
/**
|
|
28
30
|
* Structural dedup, streaming: read each per-repo shard line-by-line, keep the
|
|
@@ -32,11 +34,19 @@ function writeRepoIndexMeta(basePath, repoName, meta) {
|
|
|
32
34
|
* Keeps first-seen per hash (repo order) rather than smallest-id, but the
|
|
33
35
|
* survivors are structurally identical, so dedup is functionally equivalent.
|
|
34
36
|
*/
|
|
35
|
-
async function dedupShardsToChunks(shardPaths,
|
|
37
|
+
async function dedupShardsToChunks(shardPaths, blobs, chunksKey,
|
|
38
|
+
/** Local NDJSON copy of the PREVIOUS chunks.json + which of its chunks to
|
|
39
|
+
* keep. Absent on a full rebuild (every repo re-chunked) — the shards are
|
|
40
|
+
* then the complete corpus, today's behavior. */
|
|
41
|
+
carryForward) {
|
|
42
|
+
// Shards are transient local scratch — read raw. Survivors stream straight
|
|
43
|
+
// into the durable chunks blob via putNdjson (byte-identical NDJSON to the
|
|
44
|
+
// prior createChunkWriter); counts are tallied inside the generator and read
|
|
45
|
+
// back after putNdjson drains it. Fresh shards stream FIRST so a re-chunked
|
|
46
|
+
// file's new chunk wins the structural-hash dedup over a stale twin.
|
|
36
47
|
const seen = new Set();
|
|
37
|
-
const writer = createChunkWriter(chunksPath);
|
|
38
48
|
let kept = 0, dropped = 0, tokens = 0;
|
|
39
|
-
|
|
49
|
+
async function* survivors() {
|
|
40
50
|
for (const sp of shardPaths) {
|
|
41
51
|
if (!existsSync(sp))
|
|
42
52
|
continue;
|
|
@@ -47,15 +57,28 @@ async function dedupShardsToChunks(shardPaths, chunksPath) {
|
|
|
47
57
|
continue;
|
|
48
58
|
}
|
|
49
59
|
seen.add(h);
|
|
50
|
-
writer.write(c);
|
|
51
60
|
kept++;
|
|
52
61
|
tokens += c.tokens;
|
|
62
|
+
yield c;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (carryForward && existsSync(carryForward.prevPath)) {
|
|
66
|
+
for await (const c of iterateChunksFile(carryForward.prevPath)) {
|
|
67
|
+
if (!carryForward.keep(c))
|
|
68
|
+
continue;
|
|
69
|
+
const h = computeStructuralHash(c.content, c.language).hash;
|
|
70
|
+
if (seen.has(h)) {
|
|
71
|
+
dropped++;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
seen.add(h);
|
|
75
|
+
kept++;
|
|
76
|
+
tokens += c.tokens;
|
|
77
|
+
yield c;
|
|
53
78
|
}
|
|
54
79
|
}
|
|
55
80
|
}
|
|
56
|
-
|
|
57
|
-
writer.close();
|
|
58
|
-
}
|
|
81
|
+
await blobs.putNdjson(chunksKey, survivors());
|
|
59
82
|
return { kept, dropped, tokens };
|
|
60
83
|
}
|
|
61
84
|
export class KnowledgeIndexer {
|
|
@@ -66,21 +89,36 @@ export class KnowledgeIndexer {
|
|
|
66
89
|
const log = opts?.onProgress ?? (() => { });
|
|
67
90
|
const report = opts?.onDetailedProgress ?? (() => { });
|
|
68
91
|
const startTime = Date.now();
|
|
69
|
-
const
|
|
92
|
+
const storage = resolveStorage(project, config);
|
|
93
|
+
const basePath = storage.basePath;
|
|
70
94
|
mkdirSync(basePath, { recursive: true });
|
|
71
95
|
// 1. Determine which repos need re-indexing (SHA check)
|
|
72
96
|
const reposToIndex = [];
|
|
73
97
|
const skippedRepos = [];
|
|
98
|
+
const skippedMeta = new Map();
|
|
74
99
|
for (const repo of repos) {
|
|
75
100
|
if (opts?.force) {
|
|
76
101
|
reposToIndex.push(repo);
|
|
77
102
|
continue;
|
|
78
103
|
}
|
|
79
|
-
|
|
80
|
-
const
|
|
104
|
+
// Remote repos: compare the ls-remote HEAD sha — unchanged repos never clone.
|
|
105
|
+
const currentSha = repo.cloneUrl ? getRemoteSha(repo.cloneUrl) : getRepoSha(repo.path);
|
|
106
|
+
const meta = await readRepoIndexMeta(basePath, repo.name, storage.blobs);
|
|
81
107
|
if (meta && currentSha && meta.lastIndexedSha === currentSha) {
|
|
82
|
-
|
|
83
|
-
|
|
108
|
+
// A skipped repo is served entirely from its stored artifacts (graph +
|
|
109
|
+
// cross-repo signals) — no clone, no AST re-parse. An index written
|
|
110
|
+
// before signals existed must be re-indexed once to backfill them.
|
|
111
|
+
const hasArtifacts = (await storage.blobs.exists(`${repo.name}/graph.json`)) &&
|
|
112
|
+
(await storage.blobs.exists(`${repo.name}/signals.json`));
|
|
113
|
+
if (hasArtifacts) {
|
|
114
|
+
skippedRepos.push(repo.name);
|
|
115
|
+
skippedMeta.set(repo.name, meta);
|
|
116
|
+
log(`Skipping ${repo.name} — unchanged (${currentSha.slice(0, 7)})`);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
reposToIndex.push(repo);
|
|
120
|
+
log(`Re-indexing ${repo.name} — unchanged but stored graph/signals missing (pre-upgrade index)`);
|
|
121
|
+
}
|
|
84
122
|
}
|
|
85
123
|
else {
|
|
86
124
|
reposToIndex.push(repo);
|
|
@@ -99,6 +137,7 @@ export class KnowledgeIndexer {
|
|
|
99
137
|
try {
|
|
100
138
|
const profiles = await profileProject(project, repos, {
|
|
101
139
|
force: opts?.force,
|
|
140
|
+
config,
|
|
102
141
|
onProgress: (m) => {
|
|
103
142
|
log(m);
|
|
104
143
|
report({ phase: 'profiling', message: m, percent: 5, etaSeconds: -1 });
|
|
@@ -137,16 +176,20 @@ export class KnowledgeIndexer {
|
|
|
137
176
|
const graphBuilder = graphWriter ? null : new ProjectGraphBuilder();
|
|
138
177
|
if (graphBuilder)
|
|
139
178
|
await graphBuilder.init();
|
|
140
|
-
|
|
141
|
-
|
|
179
|
+
// Only changed repos get jobs — skipped repos are served from their stored
|
|
180
|
+
// graph.json/signals.json below, so they are never cloned or re-parsed.
|
|
181
|
+
// This is what makes a partial cycle O(changed), not O(org).
|
|
182
|
+
const jobs = reposToIndex.map((r) => ({
|
|
142
183
|
repoName: r.name,
|
|
143
184
|
repoPath: r.path,
|
|
144
185
|
language: r.language,
|
|
145
186
|
basePath,
|
|
146
187
|
project,
|
|
147
188
|
chunking: config.chunking,
|
|
148
|
-
doChunk:
|
|
189
|
+
doChunk: true,
|
|
149
190
|
force: !!opts?.force,
|
|
191
|
+
storage: config.storage,
|
|
192
|
+
cloneUrl: r.cloneUrl,
|
|
150
193
|
}));
|
|
151
194
|
const concurrency = resolveIndexConcurrency(jobs.length);
|
|
152
195
|
const workerUrl = concurrency > 1 ? new URL('./index-worker.js', import.meta.url) : null;
|
|
@@ -175,7 +218,7 @@ export class KnowledgeIndexer {
|
|
|
175
218
|
workspaceMaps.set(res.repoName, res.workspaceMap);
|
|
176
219
|
repoStats.push({ name: res.repoName, chunkCount: res.chunkCount, language: res.language });
|
|
177
220
|
if (res.chunked) {
|
|
178
|
-
repoChunkResults.set(res.repoName, { changedFiles: res.changedFiles, deletedFiles: res.deletedFiles, fileIndex: res.fileIndex ?? {} });
|
|
221
|
+
repoChunkResults.set(res.repoName, { changedFiles: res.changedFiles, deletedFiles: res.deletedFiles, fileIndex: res.fileIndex ?? {}, sha: res.sha, shardComplete: res.shardComplete });
|
|
179
222
|
if (res.shardPath)
|
|
180
223
|
shardPaths.push(res.shardPath);
|
|
181
224
|
}
|
|
@@ -185,15 +228,70 @@ export class KnowledgeIndexer {
|
|
|
185
228
|
}
|
|
186
229
|
},
|
|
187
230
|
});
|
|
231
|
+
// Skipped repos: their per-repo graphs were persisted when they were last
|
|
232
|
+
// indexed — stream each into the system-graph writer (one at a time, the
|
|
233
|
+
// graph never accumulates) and rehydrate the persisted workspace packages
|
|
234
|
+
// for cross-repo correlation. No clone, no AST parse.
|
|
188
235
|
for (const name of skippedRepos) {
|
|
189
|
-
const meta =
|
|
236
|
+
const meta = skippedMeta.get(name);
|
|
190
237
|
repoStats.push({ name, chunkCount: meta?.chunkCount ?? 0, language: '' });
|
|
238
|
+
try {
|
|
239
|
+
const g = await storage.blobs.getJson(`${name}/graph.json`);
|
|
240
|
+
if (g) {
|
|
241
|
+
if (graphWriter)
|
|
242
|
+
graphWriter.addRepoGraph(name, g);
|
|
243
|
+
else
|
|
244
|
+
graphBuilder.addRepoGraph(name, g);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
log(`Warning: stored graph load failed for ${name}: ${e}`);
|
|
249
|
+
}
|
|
250
|
+
if (meta?.workspacePackages?.length) {
|
|
251
|
+
workspaceMaps.set(name, {
|
|
252
|
+
repoPath: '',
|
|
253
|
+
packages: meta.workspacePackages,
|
|
254
|
+
nameToPackage: new Map(meta.workspacePackages.map((pkg) => [pkg.name, pkg])),
|
|
255
|
+
pathAliases: new Map(),
|
|
256
|
+
});
|
|
257
|
+
}
|
|
191
258
|
}
|
|
192
259
|
// Structural dedup — streaming over the per-repo shards into chunks.json
|
|
193
260
|
// (bounded memory; replaces the in-RAM dedup that OOM'd at org scale).
|
|
261
|
+
// PARTIAL CYCLES: the shards only cover repos re-chunked THIS cycle —
|
|
262
|
+
// skipped repos' chunks and an incrementally-chunked repo's untouched
|
|
263
|
+
// files must be carried forward from the previous chunks.json, or every
|
|
264
|
+
// scheduled reindex silently shrinks the corpus to the changed set.
|
|
194
265
|
report({ phase: 'dedup', message: 'Deduplicating chunks (streaming)...', percent: 68, etaSeconds: -1 });
|
|
195
266
|
const chunksPath = join(basePath, 'chunks.json');
|
|
196
|
-
const
|
|
267
|
+
const anyPartialShard = [...repoChunkResults.values()].some((r) => !r.shardComplete);
|
|
268
|
+
const needCarry = (skippedRepos.length > 0 || anyPartialShard) && (await storage.blobs.exists('chunks.json'));
|
|
269
|
+
let carryForward;
|
|
270
|
+
if (needCarry) {
|
|
271
|
+
// Pull the previous corpus to local scratch first — putNdjson overwrites
|
|
272
|
+
// the blob (Mongo deletes the GridFS file before upload), so reading and
|
|
273
|
+
// writing the same key concurrently would corrupt or truncate it.
|
|
274
|
+
const prevPath = join(basePath, 'chunks.prev.ndjson');
|
|
275
|
+
await storage.blobs.getBytes('chunks.json', { toFile: prevPath });
|
|
276
|
+
const currentRepos = new Set(repos.map((r) => r.name));
|
|
277
|
+
const fullyRechunked = new Set([...repoChunkResults.entries()].filter(([, r]) => r.shardComplete).map(([name]) => name));
|
|
278
|
+
const removedFiles = new Map([...repoChunkResults.entries()]
|
|
279
|
+
.filter(([, r]) => !r.shardComplete)
|
|
280
|
+
.map(([name, r]) => [name, new Set([...r.changedFiles, ...r.deletedFiles])]));
|
|
281
|
+
carryForward = {
|
|
282
|
+
prevPath,
|
|
283
|
+
keep: (c) => currentRepos.has(c.repoName) && // repos removed from the org drop out
|
|
284
|
+
!fullyRechunked.has(c.repoName) && // complete shard = replaces the repo wholesale
|
|
285
|
+
!removedFiles.get(c.repoName)?.has(c.filePath), // partial shard: only its changed/deleted files are replaced
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
const dedup = await dedupShardsToChunks(shardPaths, storage.blobs, 'chunks.json', carryForward);
|
|
289
|
+
if (carryForward) {
|
|
290
|
+
try {
|
|
291
|
+
rmSync(carryForward.prevPath, { force: true });
|
|
292
|
+
}
|
|
293
|
+
catch { /* scratch */ }
|
|
294
|
+
}
|
|
197
295
|
const dedupedChunkCount = dedup.kept;
|
|
198
296
|
const dedupedTokenSum = dedup.tokens;
|
|
199
297
|
if (dedup.dropped > 0)
|
|
@@ -205,24 +303,36 @@ export class KnowledgeIndexer {
|
|
|
205
303
|
}
|
|
206
304
|
catch { /* ok */ }
|
|
207
305
|
}
|
|
208
|
-
// 7. Detect cross-repo edges (14 strategies)
|
|
306
|
+
// 7. Detect cross-repo edges (14 strategies) — correlated from the
|
|
307
|
+
// per-repo signals persisted at index time. In the bounded-scratch writer
|
|
308
|
+
// the clones are already discarded (and skipped repos were never cloned),
|
|
309
|
+
// so the join runs on stored signals, not working trees.
|
|
209
310
|
report({ phase: 'graphing', message: 'Detecting cross-repo edges...', percent: 70, etaSeconds: -1 });
|
|
210
311
|
let crossRepoEdgeCount = 0;
|
|
211
312
|
const hasWorkspaces = workspaceMaps.size > 0;
|
|
212
313
|
if (repos.length > 1 || hasWorkspaces) {
|
|
213
|
-
const
|
|
314
|
+
const signalsMap = new Map();
|
|
315
|
+
for (const r of repos) {
|
|
316
|
+
try {
|
|
317
|
+
const sig = await storage.blobs.getJson(`${r.name}/signals.json`);
|
|
318
|
+
if (sig)
|
|
319
|
+
signalsMap.set(r.name, sig);
|
|
320
|
+
}
|
|
321
|
+
catch { /* a repo without signals just contributes no edges this cycle */ }
|
|
322
|
+
}
|
|
323
|
+
const crossEdges = correlateCrossRepoEdges(signalsMap, workspaceMaps);
|
|
214
324
|
if (graphWriter)
|
|
215
325
|
graphWriter.addCrossRepoEdges(crossEdges);
|
|
216
326
|
else
|
|
217
327
|
graphBuilder.addCrossRepoEdges(crossEdges);
|
|
218
328
|
crossRepoEdgeCount = crossEdges.length;
|
|
219
|
-
log(`Detected ${crossEdges.length} cross-repo edges`);
|
|
329
|
+
log(`Detected ${crossEdges.length} cross-repo edges (signals from ${signalsMap.size}/${repos.length} repos)`);
|
|
220
330
|
}
|
|
221
331
|
// 8. LLM Service Mesh Inference (WS-2) — skipped if LLM_MODE=none
|
|
222
332
|
if (isLlmAvailable()) {
|
|
223
333
|
report({ phase: 'service-mesh', message: 'Inferring service mesh from profiles...', percent: 80, etaSeconds: -1 });
|
|
224
334
|
try {
|
|
225
|
-
const profiles = loadAllProfiles(project);
|
|
335
|
+
const profiles = await loadAllProfiles(project, config);
|
|
226
336
|
if (profiles.length > 0) {
|
|
227
337
|
log(`Inferring service mesh from ${profiles.length} profiles...`);
|
|
228
338
|
const meshEdges = await inferServiceMesh(profiles, {
|
|
@@ -260,6 +370,7 @@ export class KnowledgeIndexer {
|
|
|
260
370
|
try {
|
|
261
371
|
const { nodeCount, edgeCount } = graphWriter.finalize();
|
|
262
372
|
log(`Saved project graph to ${join(basePath, 'system_graph.sqlite')} (streamed: ${nodeCount} nodes, ${edgeCount} edges)`);
|
|
373
|
+
await uploadSystemGraphIfRemote(storage, basePath, log);
|
|
263
374
|
}
|
|
264
375
|
catch (err) {
|
|
265
376
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -274,11 +385,12 @@ export class KnowledgeIndexer {
|
|
|
274
385
|
const wroteSqlite = await writeSystemGraphSqlite(basePath, graphBuilder);
|
|
275
386
|
if (wroteSqlite) {
|
|
276
387
|
log(`Saved project graph to ${join(basePath, 'system_graph.sqlite')}`);
|
|
388
|
+
await uploadSystemGraphIfRemote(storage, basePath, log);
|
|
277
389
|
}
|
|
278
390
|
else {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
log(`Saved project graph to ${
|
|
391
|
+
// No sqlite driver → legacy compact JSON blob (byte-parity via putText).
|
|
392
|
+
await storage.blobs.putText('system_graph_v2.json', JSON.stringify(graphBuilder.exportJson()));
|
|
393
|
+
log(`Saved project graph to ${join(basePath, 'system_graph_v2.json')} (no sqlite driver; JSON fallback)`);
|
|
282
394
|
}
|
|
283
395
|
}
|
|
284
396
|
catch (err) {
|
|
@@ -306,23 +418,43 @@ export class KnowledgeIndexer {
|
|
|
306
418
|
allStaleFiles.push({ repoName: repo.name, filePath: f });
|
|
307
419
|
}
|
|
308
420
|
}
|
|
309
|
-
|
|
310
|
-
writeFileSync(deletedPath, JSON.stringify(allStaleFiles));
|
|
421
|
+
await storage.blobs.putText('deleted_files.json', JSON.stringify(allStaleFiles));
|
|
311
422
|
// 12. Save per-repo metadata
|
|
312
423
|
for (const repo of reposToIndex) {
|
|
313
|
-
const sha = getRepoSha(repo.path);
|
|
314
424
|
const result = repoChunkResults.get(repo.name);
|
|
425
|
+
// Writer mode discards the clone before we get here — the sha was
|
|
426
|
+
// captured inside the pipeline (pre-discard); fall back to the local
|
|
427
|
+
// checkout only when the pipeline didn't run for this repo.
|
|
428
|
+
const sha = result?.sha ?? getRepoSha(repo.path);
|
|
315
429
|
const totalChunkCount = result ? Object.values(result.fileIndex).reduce((sum, f) => sum + f.chunkCount, 0) : 0;
|
|
316
430
|
if (sha) {
|
|
317
|
-
writeRepoIndexMeta(
|
|
431
|
+
await writeRepoIndexMeta(storage.blobs, repo.name, {
|
|
318
432
|
lastIndexedSha: sha,
|
|
319
433
|
lastIndexedAt: new Date().toISOString(),
|
|
320
434
|
chunkCount: totalChunkCount,
|
|
321
435
|
embeddingProvider: 'pending',
|
|
322
436
|
files: result?.fileIndex,
|
|
437
|
+
// Serializable form (WorkspaceMap holds Maps) — rehydrated when this
|
|
438
|
+
// repo is later skipped, for cross-repo workspace-dep correlation.
|
|
439
|
+
workspacePackages: workspaceMaps.get(repo.name)?.packages,
|
|
323
440
|
});
|
|
324
441
|
}
|
|
325
442
|
}
|
|
443
|
+
// Rolled-up stats: index_status / GET /status read ONE small blob instead
|
|
444
|
+
// of walking every repo's index_meta (800 reads per call at org scale).
|
|
445
|
+
try {
|
|
446
|
+
await storage.blobs.putJson('index_stats.json', {
|
|
447
|
+
repos: repoStats,
|
|
448
|
+
totalChunks: dedupedChunkCount,
|
|
449
|
+
totalTokens: dedupedTokenSum,
|
|
450
|
+
crossRepoEdges: crossRepoEdgeCount,
|
|
451
|
+
embeddingProvider: 'pending',
|
|
452
|
+
lastIndexed: new Date().toISOString(),
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
catch { /* rollup is an optimization — getStats falls back to the walk */ }
|
|
456
|
+
// Signal read replicas: chunks + graph + metas for this cycle are visible.
|
|
457
|
+
await bumpIndexGeneration(storage.blobs);
|
|
326
458
|
const durationMs = Date.now() - startTime;
|
|
327
459
|
report({ phase: 'done', message: `KB built: ${dedupedChunkCount} chunks, ${crossRepoEdgeCount} edges in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0, skippedRepos });
|
|
328
460
|
return {
|
|
@@ -342,16 +474,16 @@ export class KnowledgeIndexer {
|
|
|
342
474
|
const log = opts?.onProgress ?? (() => { });
|
|
343
475
|
const report = opts?.onDetailedProgress ?? (() => { });
|
|
344
476
|
const startTime = Date.now();
|
|
345
|
-
const
|
|
346
|
-
const
|
|
347
|
-
|
|
477
|
+
const storage = resolveStorage(project, config);
|
|
478
|
+
const basePath = storage.basePath;
|
|
479
|
+
const chunksPath = join(basePath, 'chunks.json'); // for display in logs/errors
|
|
480
|
+
if (!(await storage.blobs.exists('chunks.json'))) {
|
|
348
481
|
throw new Error(`No chunks found — run Build KB first. Expected: ${chunksPath}`);
|
|
349
482
|
}
|
|
350
483
|
// Open vector store. healCorrupt: this is the write/rebuild path, so if a
|
|
351
484
|
// prior run left the table corrupt (killed mid-write → 0-byte fragment),
|
|
352
485
|
// drop it and rebuild from chunks.json rather than failing every reindex.
|
|
353
|
-
const
|
|
354
|
-
const vectorStore = new VectorStore(dbPath);
|
|
486
|
+
const vectorStore = storage.vectors;
|
|
355
487
|
await vectorStore.init({ healCorrupt: true });
|
|
356
488
|
// Which chunks are already embedded (id-set diff). Bounded: holds only the
|
|
357
489
|
// id strings, never the chunk bodies.
|
|
@@ -365,7 +497,7 @@ export class KnowledgeIndexer {
|
|
|
365
497
|
}
|
|
366
498
|
}
|
|
367
499
|
catch { /* first run — no existing data */ }
|
|
368
|
-
const deletedFiles = this.getDeletedFiles(
|
|
500
|
+
const deletedFiles = await this.getDeletedFiles(storage.blobs);
|
|
369
501
|
// Pass 1 — stream chunks.json to tally totals + how many need embedding,
|
|
370
502
|
// WITHOUT ever holding all chunks in memory. At org scale (~810k chunks,
|
|
371
503
|
// each carrying full source + contextualized text) the old
|
|
@@ -377,7 +509,7 @@ export class KnowledgeIndexer {
|
|
|
377
509
|
let totalTokens = 0;
|
|
378
510
|
let newChunkCount = 0;
|
|
379
511
|
const repoChunkCounts = new Map();
|
|
380
|
-
for await (const c of
|
|
512
|
+
for await (const c of storage.blobs.iterateNdjson('chunks.json')) {
|
|
381
513
|
totalChunks++;
|
|
382
514
|
totalTokens += c.tokens;
|
|
383
515
|
repoChunkCounts.set(c.repoName, (repoChunkCounts.get(c.repoName) ?? 0) + 1);
|
|
@@ -396,7 +528,9 @@ export class KnowledgeIndexer {
|
|
|
396
528
|
await vectorStore.ensureFtsIndex();
|
|
397
529
|
// Heal missing scalar + vector indexes too (a prior run could have aborted
|
|
398
530
|
// before building them) so filtered search / graph expansion / vector search
|
|
399
|
-
// stay index-backed rather than full-scanning.
|
|
531
|
+
// stay index-backed rather than full-scanning. The vector index shape
|
|
532
|
+
// (IVF_FLAT default / IVF_PQ when storage.vector.lancedb.index is set)
|
|
533
|
+
// resolves inside ensureVectorIndex.
|
|
400
534
|
await vectorStore.ensureScalarIndexes();
|
|
401
535
|
await vectorStore.ensureVectorIndex();
|
|
402
536
|
report({ phase: 'done', message: 'All chunks already embedded', percent: 100, etaSeconds: 0 });
|
|
@@ -504,7 +638,7 @@ export class KnowledgeIndexer {
|
|
|
504
638
|
void task.finally(() => inFlight.delete(task));
|
|
505
639
|
};
|
|
506
640
|
let batch = [];
|
|
507
|
-
for await (const c of
|
|
641
|
+
for await (const c of storage.blobs.iterateNdjson('chunks.json')) {
|
|
508
642
|
if (aborted)
|
|
509
643
|
break;
|
|
510
644
|
if (existingIds.has(c.id))
|
|
@@ -529,27 +663,44 @@ export class KnowledgeIndexer {
|
|
|
529
663
|
await vectorStore.ensureFtsIndex();
|
|
530
664
|
}
|
|
531
665
|
// Scalar indexes (repoName/project/filePath/entityName/id) turn graph-expansion
|
|
532
|
-
// + filtered search from full-table scans into indexed lookups; the
|
|
533
|
-
//
|
|
534
|
-
//
|
|
666
|
+
// + filtered search from full-table scans into indexed lookups; the vector
|
|
667
|
+
// index (IVF_FLAT default, IVF_PQ when storage.vector.lancedb.index is set)
|
|
668
|
+
// turns brute-force KNN into probed-partition reads — together the
|
|
669
|
+
// query-latency win at org scale. After a full rebuild the table was
|
|
670
|
+
// recreated, so this trains fresh centroids; incremental adds are folded in
|
|
671
|
+
// by optimizeIndexes.
|
|
535
672
|
await vectorStore.ensureScalarIndexes();
|
|
536
673
|
await vectorStore.ensureVectorIndex();
|
|
537
674
|
await vectorStore.optimizeIndexes();
|
|
538
675
|
log(`Stored ${newChunkCount} new chunks in LanceDB (${deletedFiles.length} removed)`);
|
|
539
676
|
// Update metadata (repoNames was computed during pass 1).
|
|
540
677
|
for (const repoName of repoNames) {
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
678
|
+
const metaKey = `${repoName}/index_meta.json`;
|
|
679
|
+
try {
|
|
680
|
+
const meta = await storage.blobs.getJson(metaKey);
|
|
681
|
+
if (meta) {
|
|
545
682
|
meta.embeddingProvider = embedder.name;
|
|
546
683
|
meta.lastIndexedAt = new Date().toISOString();
|
|
547
|
-
|
|
684
|
+
await storage.blobs.putJson(metaKey, meta);
|
|
548
685
|
}
|
|
549
|
-
catch { /* ok */ }
|
|
550
686
|
}
|
|
687
|
+
catch { /* ok */ }
|
|
551
688
|
}
|
|
552
689
|
const durationMs = Date.now() - startTime;
|
|
690
|
+
// Patch the stats rollup now that the embedding provider is committed.
|
|
691
|
+
try {
|
|
692
|
+
const rollup = await storage.blobs.getJson('index_stats.json');
|
|
693
|
+
if (rollup) {
|
|
694
|
+
await storage.blobs.putJson('index_stats.json', {
|
|
695
|
+
...rollup,
|
|
696
|
+
embeddingProvider: embedder.name,
|
|
697
|
+
lastIndexed: new Date().toISOString(),
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
catch { /* optimization only */ }
|
|
702
|
+
// Signal read replicas: the vector + FTS state for this cycle is visible.
|
|
703
|
+
await bumpIndexGeneration(storage.blobs);
|
|
553
704
|
report({ phase: 'done', message: `Embedded ${newChunkCount} new chunks (${deletedFiles.length} removed) in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0 });
|
|
554
705
|
return {
|
|
555
706
|
project,
|
|
@@ -564,12 +715,9 @@ export class KnowledgeIndexer {
|
|
|
564
715
|
};
|
|
565
716
|
}
|
|
566
717
|
/** Read the deleted files list saved by buildKB */
|
|
567
|
-
getDeletedFiles(
|
|
568
|
-
const deletedPath = join(basePath, 'deleted_files.json');
|
|
569
|
-
if (!existsSync(deletedPath))
|
|
570
|
-
return [];
|
|
718
|
+
async getDeletedFiles(blobs) {
|
|
571
719
|
try {
|
|
572
|
-
return
|
|
720
|
+
return (await blobs.getJson('deleted_files.json')) ?? [];
|
|
573
721
|
}
|
|
574
722
|
catch {
|
|
575
723
|
return [];
|
|
@@ -585,10 +733,29 @@ export class KnowledgeIndexer {
|
|
|
585
733
|
return this.embedChunks(project, config, opts);
|
|
586
734
|
}
|
|
587
735
|
/** Load index statistics for a project */
|
|
588
|
-
async getStats(project) {
|
|
589
|
-
const
|
|
590
|
-
const
|
|
591
|
-
|
|
736
|
+
async getStats(project, config) {
|
|
737
|
+
const storage = resolveStorage(project, config);
|
|
738
|
+
const basePath = storage.basePath;
|
|
739
|
+
// Fast path: the writer's rolled-up stats — one small blob read instead of
|
|
740
|
+
// a vector-store connect + a meta read per repo.
|
|
741
|
+
try {
|
|
742
|
+
const rollup = await storage.blobs.getJson('index_stats.json');
|
|
743
|
+
if (rollup) {
|
|
744
|
+
return {
|
|
745
|
+
project,
|
|
746
|
+
repos: rollup.repos,
|
|
747
|
+
totalChunks: rollup.totalChunks,
|
|
748
|
+
totalTokens: rollup.totalTokens,
|
|
749
|
+
embeddingProvider: rollup.embeddingProvider,
|
|
750
|
+
embeddingDimensions: 0,
|
|
751
|
+
crossRepoEdges: rollup.crossRepoEdges,
|
|
752
|
+
lastIndexed: rollup.lastIndexed,
|
|
753
|
+
indexDurationMs: 0,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
catch { /* fall back to the walk */ }
|
|
758
|
+
const store = storage.vectors;
|
|
592
759
|
await store.init();
|
|
593
760
|
const stats = await store.getStats();
|
|
594
761
|
// Read metadata from per-repo index_meta.json files
|
|
@@ -596,9 +763,8 @@ export class KnowledgeIndexer {
|
|
|
596
763
|
let lastIndexed = '';
|
|
597
764
|
const repos = [];
|
|
598
765
|
try {
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
const meta = readRepoIndexMeta(basePath, entry);
|
|
766
|
+
for (const entry of await listRepoNames(storage)) {
|
|
767
|
+
const meta = await readRepoIndexMeta(basePath, entry, storage.blobs);
|
|
602
768
|
if (meta) {
|
|
603
769
|
repos.push({ name: entry, chunkCount: meta.chunkCount, language: '' });
|
|
604
770
|
if (meta.embeddingProvider !== 'unknown')
|
|
@@ -719,6 +885,23 @@ export async function embedFromPath(projectName, opts) {
|
|
|
719
885
|
/**
|
|
720
886
|
* Full index from a directory path — buildKB + embed in one call.
|
|
721
887
|
*/
|
|
888
|
+
/** Bounded-scratch writer entry (k8s CronJob): index repos straight from
|
|
889
|
+
* their clone URLs. Unchanged repos are skipped via `git ls-remote` without
|
|
890
|
+
* cloning; changed ones are shallow-cloned into scratchDir, processed, and
|
|
891
|
+
* discarded — peak disk = pool concurrency × largest repo. */
|
|
892
|
+
export async function indexFromRemotes(project, remotes, opts) {
|
|
893
|
+
const scratch = opts.scratchDir ?? join(tmpdir(), 'code-search-scratch', project);
|
|
894
|
+
mkdirSync(scratch, { recursive: true });
|
|
895
|
+
const repos = remotes.map((r) => ({
|
|
896
|
+
name: r.name,
|
|
897
|
+
path: join(scratch, r.name),
|
|
898
|
+
language: r.language ?? '',
|
|
899
|
+
cloneUrl: r.cloneUrl,
|
|
900
|
+
}));
|
|
901
|
+
const indexer = new KnowledgeIndexer();
|
|
902
|
+
await indexer.buildKB(project, repos, opts.config, opts);
|
|
903
|
+
return indexer.embedChunks(project, opts.config, opts);
|
|
904
|
+
}
|
|
722
905
|
export async function indexFromPath(projectName, directoryPath, opts) {
|
|
723
906
|
const log = opts?.onProgress ?? (() => { });
|
|
724
907
|
log(`Scanning ${directoryPath} for repos...`);
|
|
@@ -752,9 +935,19 @@ function retrieverCacheKey(project, config) {
|
|
|
752
935
|
const e = config.embedding;
|
|
753
936
|
return `${project}::${e.provider}:${e.model ?? ''}:${e.dimensions ?? ''}`;
|
|
754
937
|
}
|
|
755
|
-
/** Cheap change-signal for a project's index:
|
|
756
|
-
*
|
|
757
|
-
|
|
938
|
+
/** Cheap change-signal for a project's index. Primary: the `index_generation`
|
|
939
|
+
* blob the writer bumps after every cycle — works on EVERY backend (a Mongo
|
|
940
|
+
* findOne / a local file read) and is what lets remote read replicas notice a
|
|
941
|
+
* reindex without a redeploy. Fallback for indexes written before the
|
|
942
|
+
* generation blob existed: mtimes of the local LanceDB dir + system-graph
|
|
943
|
+
* sqlite (meaningful on the fs backend only). */
|
|
944
|
+
async function indexFingerprint(basePath, blobs) {
|
|
945
|
+
try {
|
|
946
|
+
const gen = await blobs.getJson('index_generation');
|
|
947
|
+
if (gen?.generation !== undefined)
|
|
948
|
+
return `gen:${gen.generation}`;
|
|
949
|
+
}
|
|
950
|
+
catch { /* fall through to local mtimes */ }
|
|
758
951
|
const mt = (p) => { try {
|
|
759
952
|
return statSync(p).mtimeMs;
|
|
760
953
|
}
|
|
@@ -763,26 +956,91 @@ function indexFingerprint(basePath) {
|
|
|
763
956
|
} };
|
|
764
957
|
return `${mt(join(basePath, 'lancedb'))}:${mt(join(basePath, 'system_graph.sqlite'))}`;
|
|
765
958
|
}
|
|
959
|
+
/** Bump the change-signal read replicas poll on their freshness TTL. Written
|
|
960
|
+
* after every completed write phase (buildKB, embedChunks) — non-fatal, the
|
|
961
|
+
* in-process invalidate still covers the writer's own cache. */
|
|
962
|
+
async function bumpIndexGeneration(blobs) {
|
|
963
|
+
try {
|
|
964
|
+
await blobs.putJson('index_generation', { generation: Date.now(), updatedAt: new Date().toISOString() });
|
|
965
|
+
}
|
|
966
|
+
catch (err) {
|
|
967
|
+
console.error(`[knowledge-core] index_generation bump failed (read replicas will not refresh until redeploy): ${err instanceof Error ? err.message : String(err)}`);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
/** Non-fs backends only: the sqlite system graph is produced on local scratch
|
|
971
|
+
* by the writer and shipped as a blob artifact; readers pull it back through
|
|
972
|
+
* the graph thunk (resolveStorage). Non-fatal — on failure readers keep the
|
|
973
|
+
* previously-uploaded graph. (Whole-file buffer: acceptable for the graph's
|
|
974
|
+
* size class; a streaming put needs a fromFile port extension.) */
|
|
975
|
+
async function uploadSystemGraphIfRemote(storage, basePath, log) {
|
|
976
|
+
if (storage.blobs instanceof FsBlobStore)
|
|
977
|
+
return;
|
|
978
|
+
const localPath = join(basePath, 'system_graph.sqlite');
|
|
979
|
+
if (!existsSync(localPath))
|
|
980
|
+
return;
|
|
981
|
+
try {
|
|
982
|
+
await storage.blobs.putBytes('system_graph.sqlite', readFileSync(localPath));
|
|
983
|
+
log('Uploaded system_graph.sqlite to the blob backend');
|
|
984
|
+
// On a remote backend the local copy is writer scratch — the blob store is
|
|
985
|
+
// the durable home (readers pull it to their cache dir). Discard it so a
|
|
986
|
+
// remote deployment leaves zero durable artifacts on the local fs.
|
|
987
|
+
rmSync(localPath, { force: true });
|
|
988
|
+
}
|
|
989
|
+
catch (err) {
|
|
990
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
991
|
+
console.error(`[knowledge-core] system graph upload failed (readers keep the previous graph): ${msg.slice(0, 160)}`);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
/** Repo names that carry KB artifacts. fs fast-path: shallow top-level dir
|
|
995
|
+
* scan (readRepoIndexMeta returns null for non-repo entries — same as the
|
|
996
|
+
* prior readdirSync walk). Non-fs backends derive names from a blob list
|
|
997
|
+
* (a metadata query), keyed on index_meta.json. */
|
|
998
|
+
async function listRepoNames(storage) {
|
|
999
|
+
if (storage.blobs instanceof FsBlobStore) {
|
|
1000
|
+
try {
|
|
1001
|
+
if (!existsSync(storage.basePath))
|
|
1002
|
+
return [];
|
|
1003
|
+
return readdirSync(storage.basePath);
|
|
1004
|
+
}
|
|
1005
|
+
catch {
|
|
1006
|
+
return [];
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
const names = new Set();
|
|
1010
|
+
try {
|
|
1011
|
+
for (const key of await storage.blobs.list('')) {
|
|
1012
|
+
const m = /^([^/]+)\/index_meta\.json$/.exec(key);
|
|
1013
|
+
if (m)
|
|
1014
|
+
names.add(m[1]);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
catch { /* unreadable */ }
|
|
1018
|
+
return [...names];
|
|
1019
|
+
}
|
|
766
1020
|
export async function getRetriever(project, configOverride) {
|
|
767
1021
|
const config = configOverride ?? loadKnowledgeConfig(project);
|
|
768
1022
|
const key = retrieverCacheKey(project, config);
|
|
769
1023
|
const basePath = getKnowledgeBasePath(project);
|
|
770
1024
|
const entry = retrieverCache.get(key);
|
|
1025
|
+
const freshnessBlobs = resolveStorage(project, config).blobs;
|
|
771
1026
|
if (entry) {
|
|
772
1027
|
const now = Date.now();
|
|
773
1028
|
if (RETRIEVER_FRESHNESS_MS === 0 || now - entry.checkedAt < RETRIEVER_FRESHNESS_MS) {
|
|
774
|
-
return entry.retriever; // within TTL — serve cached, no
|
|
1029
|
+
return entry.retriever; // within TTL — serve cached, no storage touch
|
|
775
1030
|
}
|
|
776
|
-
// TTL elapsed: one cheap
|
|
777
|
-
// (
|
|
778
|
-
|
|
1031
|
+
// TTL elapsed: one cheap generation read; rebuild ONLY if the index
|
|
1032
|
+
// actually advanced (the sole writer reindexed). Steady state = one small
|
|
1033
|
+
// read every TTL.
|
|
1034
|
+
if (await indexFingerprint(basePath, freshnessBlobs) === entry.fingerprint) {
|
|
779
1035
|
entry.checkedAt = now;
|
|
780
1036
|
return entry.retriever;
|
|
781
1037
|
}
|
|
782
1038
|
retrieverCache.delete(key);
|
|
783
1039
|
entry.retriever.then((r) => r.close()).catch(() => { });
|
|
1040
|
+
// The graph tools' shared store is part of the same index generation.
|
|
1041
|
+
await invalidateGraphStores(project);
|
|
784
1042
|
}
|
|
785
|
-
const fingerprint = indexFingerprint(basePath);
|
|
1043
|
+
const fingerprint = await indexFingerprint(basePath, freshnessBlobs);
|
|
786
1044
|
const building = buildRetriever(project, config);
|
|
787
1045
|
retrieverCache.set(key, { retriever: building, fingerprint, checkedAt: Date.now() });
|
|
788
1046
|
// Evict a failed build so a transient error doesn't poison the cache forever.
|
|
@@ -804,12 +1062,18 @@ export async function invalidateRetriever(project) {
|
|
|
804
1062
|
}
|
|
805
1063
|
catch { /* already closed / build failed */ }
|
|
806
1064
|
}
|
|
1065
|
+
// The shared graph-store cache follows the same reindex lifecycle.
|
|
1066
|
+
await invalidateGraphStores(project);
|
|
807
1067
|
}
|
|
808
1068
|
async function buildRetriever(project, config) {
|
|
809
|
-
|
|
1069
|
+
// All storage (vectors / blobs / graph) resolves through the bundle so the
|
|
1070
|
+
// retriever serves fs/LanceDB-local AND object-store deployments alike. Note:
|
|
1071
|
+
// the freshness fingerprint in getRetriever stats the LOCAL layout — on a
|
|
1072
|
+
// remote backend it degrades to invalidate-on-reindex only.
|
|
1073
|
+
const storage = resolveStorage(project, config);
|
|
1074
|
+
const basePath = storage.basePath;
|
|
810
1075
|
// Load vector store
|
|
811
|
-
const
|
|
812
|
-
const vectorStore = new VectorStore(dbPath);
|
|
1076
|
+
const vectorStore = storage.vectors;
|
|
813
1077
|
await vectorStore.init();
|
|
814
1078
|
// Open the system-graph store for graph-augmented retrieval. It prefers
|
|
815
1079
|
// system_graph.sqlite (org scale, bounded slice queries) and falls back to
|
|
@@ -817,24 +1081,22 @@ async function buildRetriever(project, config) {
|
|
|
817
1081
|
// runs vector + BM25 only. This replaces loading the whole graph into an
|
|
818
1082
|
// in-memory graphology graph per query — which at org scale either didn't
|
|
819
1083
|
// exist (only the sqlite is written) or was multi-GB to parse.
|
|
820
|
-
const graphStore = await
|
|
1084
|
+
const graphStore = await storage.graph();
|
|
821
1085
|
// Create embedding provider for query-time embedding
|
|
822
1086
|
const embedder = createEmbeddingProvider(config.embedding);
|
|
823
1087
|
// Vector-space safety: refuse to run if the index was embedded with a
|
|
824
1088
|
// different provider/dimension than what the current config resolves to.
|
|
825
1089
|
// Garbage results from silent space mismatch are worse than a hard error.
|
|
826
1090
|
try {
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
`(set CODE_SEARCH_EMBEDDING_PROVIDER or config.embedding.provider to match the index.)`);
|
|
837
|
-
}
|
|
1091
|
+
for (const entry of await listRepoNames(storage)) {
|
|
1092
|
+
const meta = await readRepoIndexMeta(basePath, entry, storage.blobs);
|
|
1093
|
+
if (!meta || !meta.embeddingProvider || meta.embeddingProvider === 'pending')
|
|
1094
|
+
continue;
|
|
1095
|
+
if (meta.embeddingProvider !== embedder.name) {
|
|
1096
|
+
throw new Error(`[knowledge-core] Vector-space mismatch for repo "${entry}": ` +
|
|
1097
|
+
`index built with "${meta.embeddingProvider}" but retrieval is using "${embedder.name}". ` +
|
|
1098
|
+
`Reindex with consistent embedding provider, or revert the config change. ` +
|
|
1099
|
+
`(set CODE_SEARCH_EMBEDDING_PROVIDER or config.embedding.provider to match the index.)`);
|
|
838
1100
|
}
|
|
839
1101
|
}
|
|
840
1102
|
}
|
|
@@ -855,7 +1117,7 @@ async function buildRetriever(project, config) {
|
|
|
855
1117
|
// Create query router (WS-8) — routes queries to relevant repos
|
|
856
1118
|
let queryRouter = null;
|
|
857
1119
|
try {
|
|
858
|
-
queryRouter = await createQueryRouter(project, embedder);
|
|
1120
|
+
queryRouter = await createQueryRouter(project, embedder, config);
|
|
859
1121
|
if (queryRouter) {
|
|
860
1122
|
console.error(`[knowledge] Query router ready (${queryRouter.repoCount} repo profiles)`);
|
|
861
1123
|
}
|