@floydous/pi-agent-kernel 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/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as crypto from "node:crypto";
|
|
5
|
+
import {
|
|
6
|
+
type CodeChunk,
|
|
7
|
+
chunkFile,
|
|
8
|
+
computeHash,
|
|
9
|
+
findChunkableFiles,
|
|
10
|
+
} from "./search_chunker";
|
|
11
|
+
import { BM25Engine } from "./search_bm25";
|
|
12
|
+
import { LocalEmbedder } from "./search_embedder";
|
|
13
|
+
import {
|
|
14
|
+
getSearchConfig,
|
|
15
|
+
type SearchConfig,
|
|
16
|
+
type SearchProfile,
|
|
17
|
+
savePersistedProfile,
|
|
18
|
+
} from "./search_config";
|
|
19
|
+
import { kernelDebug } from "../safety/kernel_debug";
|
|
20
|
+
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
21
|
+
|
|
22
|
+
export interface SearchHit {
|
|
23
|
+
chunk: CodeChunk;
|
|
24
|
+
rrfScore: number;
|
|
25
|
+
bm25Score: number;
|
|
26
|
+
vectorScore: number;
|
|
27
|
+
signal: "lexical" | "semantic" | "hybrid";
|
|
28
|
+
bm25Rank?: number;
|
|
29
|
+
vectorRank?: number;
|
|
30
|
+
matches: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class HybridSearchIndex {
|
|
34
|
+
private cwd: string;
|
|
35
|
+
private config: SearchConfig;
|
|
36
|
+
private bm25: BM25Engine = new BM25Engine();
|
|
37
|
+
private embedder: LocalEmbedder;
|
|
38
|
+
private chunks: Map<string, CodeChunk> = new Map();
|
|
39
|
+
private vectors: Map<string, Float32Array> = new Map();
|
|
40
|
+
private fileHashes: Map<string, string> = new Map(); // relPath -> SHA256 hash
|
|
41
|
+
private isInitialized = false;
|
|
42
|
+
private isIndexing = false;
|
|
43
|
+
private dirtyFiles = new Set<string>();
|
|
44
|
+
private generation = 0;
|
|
45
|
+
private activeSync: Promise<{ chunkCount: number; fileCount: number }> | null = null;
|
|
46
|
+
private liveCheckPromise: Promise<boolean> | null = null;
|
|
47
|
+
|
|
48
|
+
constructor(cwd: string, profile?: SearchProfile) {
|
|
49
|
+
this.cwd = cwd;
|
|
50
|
+
this.config = getSearchConfig(profile);
|
|
51
|
+
this.embedder = new LocalEmbedder(this.config);
|
|
52
|
+
this.loadFromDisk();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public getProfile(): SearchProfile {
|
|
56
|
+
return this.config.profile;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
public getEffectiveProfile(): "lean" | "hybrid" | "full" | "off" {
|
|
60
|
+
return this.config.effectiveProfile;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public setProfile(profile: SearchProfile): void {
|
|
64
|
+
savePersistedProfile(profile);
|
|
65
|
+
this.config = getSearchConfig(profile);
|
|
66
|
+
this.embedder.updateConfig(this.config);
|
|
67
|
+
if (
|
|
68
|
+
this.config.effectiveProfile === "off" ||
|
|
69
|
+
this.config.effectiveProfile === "lean"
|
|
70
|
+
) {
|
|
71
|
+
void this.embedder.dispose();
|
|
72
|
+
this.vectors.clear();
|
|
73
|
+
try {
|
|
74
|
+
if (typeof (global as any).gc === "function") {
|
|
75
|
+
(global as any).gc();
|
|
76
|
+
}
|
|
77
|
+
} catch (e) {
|
|
78
|
+
kernelDebug(e);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Warm up / preload embedding weights into RAM if profile requires vectors.
|
|
85
|
+
*/
|
|
86
|
+
public async preloadModel(
|
|
87
|
+
onProgress?: (msg: string) => void,
|
|
88
|
+
): Promise<boolean> {
|
|
89
|
+
if (
|
|
90
|
+
this.config.effectiveProfile === "hybrid" ||
|
|
91
|
+
this.config.effectiveProfile === "full"
|
|
92
|
+
) {
|
|
93
|
+
return await this.embedder.initialize(onProgress);
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private getCacheDir(): string {
|
|
99
|
+
return path.join(this.cwd, ".pi", "cache", "search");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private getIndexFilePath(): string {
|
|
103
|
+
return path.join(this.getCacheDir(), "index.json");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private getVectorsFilePath(): string {
|
|
107
|
+
return path.join(this.getCacheDir(), "vectors.bin");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Load cached index from disk if available.
|
|
112
|
+
*/
|
|
113
|
+
public loadFromDisk(): boolean {
|
|
114
|
+
const indexPath = this.getIndexFilePath();
|
|
115
|
+
const vectorsPath = this.getVectorsFilePath();
|
|
116
|
+
|
|
117
|
+
if (!fs.existsSync(indexPath)) return false;
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
const raw = fs.readFileSync(indexPath, "utf-8");
|
|
121
|
+
const data = JSON.parse(raw);
|
|
122
|
+
|
|
123
|
+
if (data.version !== 1) return false;
|
|
124
|
+
|
|
125
|
+
this.chunks.clear();
|
|
126
|
+
this.bm25.clear();
|
|
127
|
+
this.fileHashes.clear();
|
|
128
|
+
this.vectors.clear();
|
|
129
|
+
|
|
130
|
+
for (const chunk of data.chunks as CodeChunk[]) {
|
|
131
|
+
this.chunks.set(chunk.id, chunk);
|
|
132
|
+
this.bm25.addChunk(chunk);
|
|
133
|
+
}
|
|
134
|
+
this.bm25.recalculateStats();
|
|
135
|
+
|
|
136
|
+
for (const [f, h] of Object.entries(data.fileHashes || {})) {
|
|
137
|
+
this.fileHashes.set(f, h as string);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Only load binary vectors when metadata proves a complete, one-to-one
|
|
141
|
+
// chunk/vector mapping. Otherwise retain the safe BM25 index only.
|
|
142
|
+
const wantsVectors =
|
|
143
|
+
this.config.effectiveProfile === "hybrid" ||
|
|
144
|
+
this.config.effectiveProfile === "full";
|
|
145
|
+
const vectorChunkIds = data.vectorChunkIds;
|
|
146
|
+
const validVectorMetadata =
|
|
147
|
+
wantsVectors &&
|
|
148
|
+
data.profile === this.config.profile &&
|
|
149
|
+
fs.existsSync(vectorsPath) &&
|
|
150
|
+
Number.isInteger(data.vectorDim) &&
|
|
151
|
+
data.vectorDim > 0 &&
|
|
152
|
+
Array.isArray(vectorChunkIds) &&
|
|
153
|
+
vectorChunkIds.length > 0 &&
|
|
154
|
+
new Set(vectorChunkIds).size === vectorChunkIds.length &&
|
|
155
|
+
vectorChunkIds.every(
|
|
156
|
+
(id: unknown) => typeof id === "string" && this.chunks.has(id),
|
|
157
|
+
);
|
|
158
|
+
if (validVectorMetadata) {
|
|
159
|
+
const buf = fs.readFileSync(vectorsPath);
|
|
160
|
+
const dim = data.vectorDim as number;
|
|
161
|
+
const expectedBytes = vectorChunkIds.length * dim * 4;
|
|
162
|
+
if (
|
|
163
|
+
buf.byteLength === expectedBytes &&
|
|
164
|
+
typeof data.vectorHash === "string" &&
|
|
165
|
+
data.vectorHash ===
|
|
166
|
+
crypto
|
|
167
|
+
.createHash("sha256")
|
|
168
|
+
.update(JSON.stringify(vectorChunkIds))
|
|
169
|
+
.update(buf)
|
|
170
|
+
.digest("hex")
|
|
171
|
+
) {
|
|
172
|
+
const floatArray = new Float32Array(
|
|
173
|
+
buf.buffer,
|
|
174
|
+
buf.byteOffset,
|
|
175
|
+
buf.byteLength / 4,
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
for (let index = 0; index < vectorChunkIds.length; index++) {
|
|
179
|
+
const vec = new Float32Array(dim);
|
|
180
|
+
vec.set(floatArray.subarray(index * dim, (index + 1) * dim));
|
|
181
|
+
this.vectors.set(vectorChunkIds[index], vec);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
this.isInitialized = true;
|
|
187
|
+
return true;
|
|
188
|
+
} catch {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Save current index and binary vectors to disk cache.
|
|
195
|
+
*/
|
|
196
|
+
public saveToDisk(): void {
|
|
197
|
+
try {
|
|
198
|
+
const cacheDir = this.getCacheDir();
|
|
199
|
+
if (!fs.existsSync(cacheDir)) {
|
|
200
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Ensure .gitignore exists in .pi/cache
|
|
204
|
+
const gitignorePath = path.join(this.cwd, ".pi", "cache", ".gitignore");
|
|
205
|
+
if (!fs.existsSync(gitignorePath)) {
|
|
206
|
+
try {
|
|
207
|
+
fs.writeFileSync(gitignorePath, "*\n!.gitignore\n", "utf-8");
|
|
208
|
+
} catch (e) {
|
|
209
|
+
kernelDebug(e);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const chunkList = Array.from(this.chunks.values());
|
|
214
|
+
const fileHashesObj: Record<string, string> = {};
|
|
215
|
+
for (const [f, h] of this.fileHashes.entries()) {
|
|
216
|
+
fileHashesObj[f] = h;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const vectorChunkIds: string[] = [];
|
|
220
|
+
let vectorDim = 0;
|
|
221
|
+
const vectorArrays: Float32Array[] = [];
|
|
222
|
+
|
|
223
|
+
for (const [id, vec] of this.vectors.entries()) {
|
|
224
|
+
vectorChunkIds.push(id);
|
|
225
|
+
vectorArrays.push(vec);
|
|
226
|
+
if (vectorDim === 0) vectorDim = vec.length;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const vectorBuffer = Buffer.alloc(vectorArrays.length * vectorDim * 4);
|
|
230
|
+
for (let i = 0; i < vectorArrays.length; i++) {
|
|
231
|
+
const bytes = Buffer.from(
|
|
232
|
+
vectorArrays[i].buffer,
|
|
233
|
+
vectorArrays[i].byteOffset,
|
|
234
|
+
vectorArrays[i].byteLength,
|
|
235
|
+
);
|
|
236
|
+
bytes.copy(vectorBuffer, i * vectorDim * 4);
|
|
237
|
+
}
|
|
238
|
+
const vectorHash = crypto
|
|
239
|
+
.createHash("sha256")
|
|
240
|
+
.update(JSON.stringify(vectorChunkIds))
|
|
241
|
+
.update(vectorBuffer)
|
|
242
|
+
.digest("hex");
|
|
243
|
+
|
|
244
|
+
const indexData = {
|
|
245
|
+
version: 1,
|
|
246
|
+
updatedAt: new Date().toISOString(),
|
|
247
|
+
profile: this.config.profile,
|
|
248
|
+
vectorDim,
|
|
249
|
+
fileHashes: fileHashesObj,
|
|
250
|
+
chunks: chunkList,
|
|
251
|
+
vectorChunkIds,
|
|
252
|
+
vectorHash,
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
writeFileSyncAtomic(
|
|
256
|
+
this.getIndexFilePath(),
|
|
257
|
+
JSON.stringify(indexData, null, 2),
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
// Write binary vectors
|
|
261
|
+
if (vectorBuffer.length > 0) {
|
|
262
|
+
writeFileSyncAtomic(this.getVectorsFilePath(), vectorBuffer);
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
console.error("[Search Index] Failed saving cache:", err);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Synchronize and incrementally update workspace index.
|
|
271
|
+
*/
|
|
272
|
+
public async syncWorkspace(
|
|
273
|
+
forceReindex = false,
|
|
274
|
+
onProgress?: (msg: string) => void,
|
|
275
|
+
): Promise<{ chunkCount: number; fileCount: number }> {
|
|
276
|
+
if (this.activeSync) return this.activeSync;
|
|
277
|
+
|
|
278
|
+
const sync = (async () => {
|
|
279
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
280
|
+
const syncGeneration = this.generation;
|
|
281
|
+
const result = await this.performSyncWorkspace(
|
|
282
|
+
forceReindex && attempt === 0,
|
|
283
|
+
onProgress,
|
|
284
|
+
syncGeneration,
|
|
285
|
+
);
|
|
286
|
+
if (
|
|
287
|
+
this.generation !== syncGeneration ||
|
|
288
|
+
!this.isWorkspaceSnapshotFresh()
|
|
289
|
+
) {
|
|
290
|
+
this.isInitialized = false;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
this.dirtyFiles.clear();
|
|
294
|
+
return result;
|
|
295
|
+
}
|
|
296
|
+
this.isInitialized = false;
|
|
297
|
+
throw new Error("Workspace changed repeatedly while indexing; search was not refreshed.");
|
|
298
|
+
})();
|
|
299
|
+
this.activeSync = sync;
|
|
300
|
+
try {
|
|
301
|
+
return await sync;
|
|
302
|
+
} finally {
|
|
303
|
+
if (this.activeSync === sync) this.activeSync = null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
308
|
+
const hashes = new Map<string, string>();
|
|
309
|
+
for (const filePath of findChunkableFiles(this.cwd)) {
|
|
310
|
+
const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
|
|
311
|
+
try {
|
|
312
|
+
hashes.set(relPath, computeHash(fs.readFileSync(filePath, "utf8")));
|
|
313
|
+
} catch (error) {
|
|
314
|
+
kernelDebug(error);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return hashes;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private isWorkspaceSnapshotFresh(): boolean {
|
|
322
|
+
const currentHashes = this.getWorkspaceFileHashes();
|
|
323
|
+
if (!currentHashes || currentHashes.size !== this.fileHashes.size) return false;
|
|
324
|
+
for (const [relPath, hash] of this.fileHashes.entries()) {
|
|
325
|
+
if (currentHashes.get(relPath) !== hash) return false;
|
|
326
|
+
}
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private async waitForActiveSync(): Promise<void> {
|
|
331
|
+
while (this.activeSync) {
|
|
332
|
+
const sync = this.activeSync;
|
|
333
|
+
try {
|
|
334
|
+
await sync;
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (this.activeSync === sync) throw error;
|
|
337
|
+
}
|
|
338
|
+
if (this.activeSync === sync) return;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private async ensureWorkspaceSnapshotFresh(): Promise<void> {
|
|
343
|
+
await this.waitForActiveSync();
|
|
344
|
+
if (this.liveCheckPromise) {
|
|
345
|
+
const check = this.liveCheckPromise;
|
|
346
|
+
const isFresh = await check;
|
|
347
|
+
if (this.liveCheckPromise === check) {
|
|
348
|
+
if (!isFresh) {
|
|
349
|
+
this.isInitialized = false;
|
|
350
|
+
await this.waitForActiveSync();
|
|
351
|
+
if (this.dirtyFiles.size > 0 || !this.isInitialized) {
|
|
352
|
+
await this.syncWorkspace(false);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
return this.ensureWorkspaceSnapshotFresh();
|
|
358
|
+
}
|
|
359
|
+
const check = Promise.resolve().then(() => this.isWorkspaceSnapshotFresh());
|
|
360
|
+
this.liveCheckPromise = check;
|
|
361
|
+
try {
|
|
362
|
+
const isFresh = await check;
|
|
363
|
+
if (!isFresh) {
|
|
364
|
+
this.isInitialized = false;
|
|
365
|
+
await this.waitForActiveSync();
|
|
366
|
+
if (this.dirtyFiles.size > 0 || !this.isInitialized) {
|
|
367
|
+
await this.syncWorkspace(false);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
} finally {
|
|
371
|
+
if (this.liveCheckPromise === check) this.liveCheckPromise = null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
private async performSyncWorkspace(
|
|
376
|
+
forceReindex: boolean,
|
|
377
|
+
onProgress: ((msg: string) => void) | undefined,
|
|
378
|
+
syncGeneration: number,
|
|
379
|
+
): Promise<{ chunkCount: number; fileCount: number }> {
|
|
380
|
+
this.isIndexing = true;
|
|
381
|
+
try {
|
|
382
|
+
if (
|
|
383
|
+
!this.isInitialized &&
|
|
384
|
+
!forceReindex &&
|
|
385
|
+
this.dirtyFiles.size === 0
|
|
386
|
+
) {
|
|
387
|
+
this.loadFromDisk();
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
onProgress?.("Scanning workspace files...");
|
|
391
|
+
|
|
392
|
+
// Read each file once and derive both its chunks and hash from that same
|
|
393
|
+
// snapshot. A second read could pair old chunks with a new hash and make
|
|
394
|
+
// the final freshness check falsely accept stale content.
|
|
395
|
+
const currentFiles = new Map<
|
|
396
|
+
string,
|
|
397
|
+
{ hash: string; chunks: CodeChunk[] }
|
|
398
|
+
>();
|
|
399
|
+
for (const absPath of findChunkableFiles(this.cwd)) {
|
|
400
|
+
const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
|
|
401
|
+
try {
|
|
402
|
+
const content = fs.readFileSync(absPath, "utf-8");
|
|
403
|
+
currentFiles.set(relPath, {
|
|
404
|
+
hash: computeHash(content),
|
|
405
|
+
chunks: chunkFile(this.cwd, absPath, content),
|
|
406
|
+
});
|
|
407
|
+
} catch (error) {
|
|
408
|
+
kernelDebug(error);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Identify changed, added, or deleted files
|
|
413
|
+
const filesToReindex: string[] = [];
|
|
414
|
+
const filesToDelete: string[] = [];
|
|
415
|
+
|
|
416
|
+
for (const [relPath, info] of currentFiles.entries()) {
|
|
417
|
+
const oldHash = this.fileHashes.get(relPath);
|
|
418
|
+
if (forceReindex || !oldHash || oldHash !== info.hash) {
|
|
419
|
+
filesToReindex.push(relPath);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
for (const oldRelPath of this.fileHashes.keys()) {
|
|
424
|
+
if (!currentFiles.has(oldRelPath)) {
|
|
425
|
+
filesToDelete.push(oldRelPath);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Handle deletions
|
|
430
|
+
for (const delPath of filesToDelete) {
|
|
431
|
+
this.bm25.removeFile(delPath);
|
|
432
|
+
this.fileHashes.delete(delPath);
|
|
433
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
434
|
+
if (chunkId.startsWith(`${delPath}:`)) {
|
|
435
|
+
this.chunks.delete(chunkId);
|
|
436
|
+
this.vectors.delete(chunkId);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (filesToDelete.length > 0) {
|
|
441
|
+
this.bm25.recalculateStats();
|
|
442
|
+
this.saveToDisk();
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Handle additions and modifications
|
|
446
|
+
if (filesToReindex.length > 0) {
|
|
447
|
+
const chunksToEmbed: CodeChunk[] = [];
|
|
448
|
+
|
|
449
|
+
for (const relPath of filesToReindex) {
|
|
450
|
+
// Clean old chunks for this file
|
|
451
|
+
this.bm25.removeFile(relPath);
|
|
452
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
453
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
454
|
+
this.chunks.delete(chunkId);
|
|
455
|
+
this.vectors.delete(chunkId);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const fileInfo = currentFiles.get(relPath);
|
|
460
|
+
if (fileInfo) {
|
|
461
|
+
this.fileHashes.set(relPath, fileInfo.hash);
|
|
462
|
+
for (const chunk of fileInfo.chunks) {
|
|
463
|
+
this.chunks.set(chunk.id, chunk);
|
|
464
|
+
this.bm25.addChunk(chunk);
|
|
465
|
+
chunksToEmbed.push(chunk);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
this.bm25.recalculateStats();
|
|
471
|
+
|
|
472
|
+
// Embed new chunks if semantic vector search is enabled (hybrid / full)
|
|
473
|
+
const isVectorEnabled =
|
|
474
|
+
this.config.effectiveProfile === "hybrid" ||
|
|
475
|
+
this.config.effectiveProfile === "full";
|
|
476
|
+
if (isVectorEnabled && chunksToEmbed.length > 0) {
|
|
477
|
+
const batchSize = this.config.batchSize || 2;
|
|
478
|
+
const sleepMs = this.config.sleepBetweenBatchesMs || 50;
|
|
479
|
+
|
|
480
|
+
for (let i = 0; i < chunksToEmbed.length; i += batchSize) {
|
|
481
|
+
const batch = chunksToEmbed.slice(i, i + batchSize);
|
|
482
|
+
const texts = batch.map((c) => c.textForEmbedding);
|
|
483
|
+
const processed = Math.min(i + batch.length, chunksToEmbed.length);
|
|
484
|
+
const pct = Math.round((processed / chunksToEmbed.length) * 100);
|
|
485
|
+
onProgress?.(
|
|
486
|
+
`Embedding code chunks: ${pct}% (${processed}/${chunksToEmbed.length})`,
|
|
487
|
+
);
|
|
488
|
+
const vecs = await this.embedder.embedBatch(texts, false, onProgress);
|
|
489
|
+
|
|
490
|
+
for (let j = 0; j < batch.length; j++) {
|
|
491
|
+
if (vecs[j]) {
|
|
492
|
+
this.vectors.set(batch[j].id, vecs[j]);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// Async sleep to yield CPU and prevent freezing system daemons
|
|
497
|
+
if (sleepMs > 0 && i + batchSize < chunksToEmbed.length) {
|
|
498
|
+
await new Promise((r) => setTimeout(r, sleepMs));
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
this.saveToDisk();
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
this.isInitialized = true;
|
|
507
|
+
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size };
|
|
508
|
+
} finally {
|
|
509
|
+
this.isIndexing = false;
|
|
510
|
+
if (this.generation !== syncGeneration) this.isInitialized = false;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Drop cached chunks for a file; the next search performs an incremental rescan.
|
|
516
|
+
*/
|
|
517
|
+
public invalidateFile(filePath: string): void {
|
|
518
|
+
const resolvedPath = path.resolve(this.cwd, filePath);
|
|
519
|
+
const relPath = path
|
|
520
|
+
.relative(this.cwd, resolvedPath)
|
|
521
|
+
.replace(/\\/g, "/");
|
|
522
|
+
if (
|
|
523
|
+
!relPath ||
|
|
524
|
+
relPath === ".." ||
|
|
525
|
+
relPath.startsWith("../") ||
|
|
526
|
+
path.isAbsolute(relPath)
|
|
527
|
+
) return;
|
|
528
|
+
this.bm25.removeFile(relPath);
|
|
529
|
+
this.fileHashes.delete(relPath);
|
|
530
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
531
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
532
|
+
this.chunks.delete(chunkId);
|
|
533
|
+
this.vectors.delete(chunkId);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
this.bm25.recalculateStats();
|
|
537
|
+
this.generation++;
|
|
538
|
+
this.dirtyFiles.add(relPath);
|
|
539
|
+
this.isInitialized = false;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Perform Hybrid BM25 + Vector Search with Reciprocal Rank Fusion.
|
|
544
|
+
* If workspace embedding/indexing is in progress, gracefully falls back to Lean (BM25)
|
|
545
|
+
* mode to ensure instant, non-blocking retrieval without contention.
|
|
546
|
+
*/
|
|
547
|
+
public async search(
|
|
548
|
+
query: string,
|
|
549
|
+
options: {
|
|
550
|
+
limit?: number;
|
|
551
|
+
filePattern?: string;
|
|
552
|
+
profile?: SearchProfile;
|
|
553
|
+
/** Bounded RRF smoothing constant; defaults to 60. */
|
|
554
|
+
rrfK?: number;
|
|
555
|
+
} = {},
|
|
556
|
+
): Promise<SearchHit[]> {
|
|
557
|
+
// Do not return the previous snapshot while a background synchronization
|
|
558
|
+
// is active. This also covers startup/reindex work where the old index is
|
|
559
|
+
// still initialized and would otherwise look usable.
|
|
560
|
+
await this.waitForActiveSync();
|
|
561
|
+
if (this.dirtyFiles.size > 0 || !this.isInitialized) {
|
|
562
|
+
if (!this.isIndexing) {
|
|
563
|
+
await this.syncWorkspace(false);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
if (this.isInitialized && !this.isIndexing) {
|
|
568
|
+
await this.ensureWorkspaceSnapshotFresh();
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const limit = options.limit || 5;
|
|
572
|
+
const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
|
|
573
|
+
const activeConfig = options.profile
|
|
574
|
+
? getSearchConfig(options.profile)
|
|
575
|
+
: this.config;
|
|
576
|
+
|
|
577
|
+
// 1. BM25 Search (Instant AST-tokenized lexical retrieval)
|
|
578
|
+
const bm25Results = this.bm25.search(query, 100);
|
|
579
|
+
const bm25RankMap = new Map<
|
|
580
|
+
string,
|
|
581
|
+
{ rank: number; score: number; matches: string[] }
|
|
582
|
+
>();
|
|
583
|
+
bm25Results.forEach((r, idx) => {
|
|
584
|
+
bm25RankMap.set(r.chunkId, {
|
|
585
|
+
rank: idx + 1,
|
|
586
|
+
score: r.score,
|
|
587
|
+
matches: r.matches,
|
|
588
|
+
});
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
// 2. Vector Search (if active profile is hybrid/full AND indexing is not actively in progress)
|
|
592
|
+
const vectorRankMap = new Map<string, { rank: number; score: number }>();
|
|
593
|
+
const wantsVectors =
|
|
594
|
+
activeConfig.effectiveProfile === "hybrid" ||
|
|
595
|
+
activeConfig.effectiveProfile === "full";
|
|
596
|
+
const isVectorReady =
|
|
597
|
+
wantsVectors && !this.isIndexing && this.vectors.size > 0;
|
|
598
|
+
|
|
599
|
+
if (isVectorReady) {
|
|
600
|
+
const queryVec = await this.embedder.embed(query, true);
|
|
601
|
+
if (queryVec) {
|
|
602
|
+
const vecScores: { chunkId: string; score: number }[] = [];
|
|
603
|
+
for (const [chunkId, vec] of this.vectors.entries()) {
|
|
604
|
+
const score = LocalEmbedder.cosineSimilarity(queryVec, vec);
|
|
605
|
+
vecScores.push({ chunkId, score });
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
vecScores.sort((a, b) => b.score - a.score);
|
|
609
|
+
const threshold = activeConfig.vectorSimilarityThreshold;
|
|
610
|
+
vecScores
|
|
611
|
+
.filter((item) => item.score >= threshold)
|
|
612
|
+
.slice(0, 100)
|
|
613
|
+
.forEach((item, idx) => {
|
|
614
|
+
vectorRankMap.set(item.chunkId, {
|
|
615
|
+
rank: idx + 1,
|
|
616
|
+
score: item.score,
|
|
617
|
+
});
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// 3. Reciprocal Rank Fusion (RRF)
|
|
623
|
+
const candidateIds = new Set([
|
|
624
|
+
...bm25RankMap.keys(),
|
|
625
|
+
...vectorRankMap.keys(),
|
|
626
|
+
]);
|
|
627
|
+
const hits: SearchHit[] = [];
|
|
628
|
+
|
|
629
|
+
for (const chunkId of candidateIds) {
|
|
630
|
+
const chunk = this.chunks.get(chunkId);
|
|
631
|
+
if (!chunk) continue;
|
|
632
|
+
|
|
633
|
+
if (
|
|
634
|
+
options.filePattern &&
|
|
635
|
+
!chunk.filePath
|
|
636
|
+
.replace(/\\/g, "/")
|
|
637
|
+
.toLowerCase()
|
|
638
|
+
.includes(options.filePattern.replace(/\\/g, "/").toLowerCase())
|
|
639
|
+
) {
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const bmData = bm25RankMap.get(chunkId);
|
|
644
|
+
const vecData = vectorRankMap.get(chunkId);
|
|
645
|
+
|
|
646
|
+
const bm25Rank = bmData ? bmData.rank : 999;
|
|
647
|
+
const vecRank = vecData ? vecData.rank : 999;
|
|
648
|
+
|
|
649
|
+
const rrfBm25 = bmData ? 1 / (k + bm25Rank) : 0;
|
|
650
|
+
const rrfVec = vecData ? 1 / (k + vecRank) : 0;
|
|
651
|
+
const rrfScore = rrfBm25 + rrfVec;
|
|
652
|
+
|
|
653
|
+
hits.push({
|
|
654
|
+
chunk,
|
|
655
|
+
rrfScore,
|
|
656
|
+
bm25Score: bmData ? bmData.score : 0,
|
|
657
|
+
vectorScore: vecData ? vecData.score : 0,
|
|
658
|
+
signal: bmData && vecData ? "hybrid" : vecData ? "semantic" : "lexical",
|
|
659
|
+
bm25Rank: bmData?.rank,
|
|
660
|
+
vectorRank: vecData?.rank,
|
|
661
|
+
matches: bmData?.matches || [],
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// Sort by combined RRF score descending
|
|
666
|
+
hits.sort((a, b) => b.rrfScore - a.rrfScore);
|
|
667
|
+
return hits.slice(0, limit);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Get active index diagnostic status.
|
|
672
|
+
*/
|
|
673
|
+
public getStatus(): {
|
|
674
|
+
profile: SearchProfile;
|
|
675
|
+
effectiveProfile: "lean" | "hybrid" | "full" | "off";
|
|
676
|
+
fileCount: number;
|
|
677
|
+
chunkCount: number;
|
|
678
|
+
vectorCount: number;
|
|
679
|
+
isModelLoaded: boolean;
|
|
680
|
+
isModelCached: boolean;
|
|
681
|
+
rssMemoryMB: number;
|
|
682
|
+
modelStatus: string;
|
|
683
|
+
engineState: string;
|
|
684
|
+
pipelineDesc: string;
|
|
685
|
+
hardwareInfo: string;
|
|
686
|
+
} {
|
|
687
|
+
const isModelLoaded = this.embedder.isLoaded();
|
|
688
|
+
const isModelCached = this.embedder.isCachedOnDisk();
|
|
689
|
+
let modelStatus = "";
|
|
690
|
+
let pipelineDesc = "";
|
|
691
|
+
|
|
692
|
+
if (this.config.effectiveProfile === "off") {
|
|
693
|
+
modelStatus = "Disabled";
|
|
694
|
+
pipelineDesc = "Engine is turned off";
|
|
695
|
+
} else if (this.config.effectiveProfile === "lean") {
|
|
696
|
+
modelStatus = "Active (BM25 Engine - 0 MB Model RAM)";
|
|
697
|
+
pipelineDesc = "AST-tokenized BM25 Lexical Retrieval";
|
|
698
|
+
} else if (this.config.effectiveProfile === "hybrid") {
|
|
699
|
+
if (isModelLoaded) {
|
|
700
|
+
modelStatus = "Active in RAM (Nomic v1.5 Matryoshka 256-dim)";
|
|
701
|
+
} else if (isModelCached) {
|
|
702
|
+
modelStatus = "Cached on disk (Loads on-demand into RAM)";
|
|
703
|
+
} else {
|
|
704
|
+
modelStatus = "Not downloaded (~135 MB)";
|
|
705
|
+
}
|
|
706
|
+
pipelineDesc = "Hybrid BM25 + 256-dim Matryoshka Vector Search";
|
|
707
|
+
} else {
|
|
708
|
+
if (isModelLoaded) {
|
|
709
|
+
modelStatus = "Active in RAM (Nomic v1.5 768-dim)";
|
|
710
|
+
} else if (isModelCached) {
|
|
711
|
+
modelStatus = "Cached on disk (Loads on-demand into RAM)";
|
|
712
|
+
} else {
|
|
713
|
+
modelStatus = "Not downloaded (~135 MB)";
|
|
714
|
+
}
|
|
715
|
+
pipelineDesc = "Full BM25 + 768-dim Semantic Vector Search";
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
let engineState = "Active & Ready";
|
|
719
|
+
if (this.config.effectiveProfile === "off") {
|
|
720
|
+
engineState = "Disabled";
|
|
721
|
+
} else if (this.isIndexing) {
|
|
722
|
+
engineState = "Indexing files...";
|
|
723
|
+
} else if (!this.isInitialized && this.chunks.size === 0) {
|
|
724
|
+
engineState = "Ready (Empty workspace)";
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
const cpus = os.cpus().length;
|
|
728
|
+
const freeMem = (os.freemem() / (1024 * 1024 * 1024)).toFixed(1);
|
|
729
|
+
const hardwareInfo = `${cpus} CPUs, ${freeMem} GB free RAM`;
|
|
730
|
+
|
|
731
|
+
return {
|
|
732
|
+
profile: this.config.profile,
|
|
733
|
+
effectiveProfile: this.config.effectiveProfile,
|
|
734
|
+
fileCount: this.fileHashes.size,
|
|
735
|
+
chunkCount: this.chunks.size,
|
|
736
|
+
vectorCount: this.vectors.size,
|
|
737
|
+
isModelLoaded,
|
|
738
|
+
isModelCached,
|
|
739
|
+
rssMemoryMB: Math.round(process.memoryUsage().rss / 1024 / 1024),
|
|
740
|
+
modelStatus,
|
|
741
|
+
engineState,
|
|
742
|
+
pipelineDesc,
|
|
743
|
+
hardwareInfo,
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Unload model from RAM.
|
|
749
|
+
*/
|
|
750
|
+
public unloadModel(): void {
|
|
751
|
+
this.embedder.dispose();
|
|
752
|
+
}
|
|
753
|
+
}
|