@floydous/pi-agent-kernel 0.3.31 → 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/AGENT_KERNEL_SYS_PROMPT.md +6 -4
- package/CHANGELOG.md +35 -4
- package/README.md +39 -74
- package/config.example.toml +36 -0
- package/docs/configuration.md +11 -3
- package/docs/retrieval.md +17 -1
- package/docs/testing.md +5 -3
- package/package.json +9 -7
- package/src/config/agent_kernel_command.ts +91 -91
- package/src/config/kernel_config.ts +179 -43
- package/src/config/toml.ts +15 -4
- package/src/context/session_repair.ts +179 -80
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +29 -36
- package/src/editing/syntax-verify.ts +52 -18
- package/src/index.ts +257 -219
- package/src/lsp/lsp_client.ts +138 -23
- package/src/lsp/lsp_formatter.ts +61 -24
- package/src/lsp/lsp_installer.ts +277 -561
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +110 -73
- package/src/retrieval/ast_search.ts +136 -172
- package/src/retrieval/repomap.ts +8 -47
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +21 -43
- package/src/retrieval/search_config.ts +75 -18
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +923 -123
- package/src/retrieval/workspace_walker.ts +262 -0
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +163 -43
- package/src/safety/output_clamper.ts +316 -74
- package/src/tools/code_search_output.ts +59 -23
- package/src/tools/code_search_tool.ts +42 -46
- package/src/tools/context.ts +15 -1
- package/src/tools/edit_tool.ts +124 -43
- package/src/tools/lsp_tool.ts +17 -4
- package/src/tools/read_tool.ts +48 -7
- package/config.toml +0 -31
|
@@ -3,11 +3,14 @@ import * as path from "node:path";
|
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as crypto from "node:crypto";
|
|
5
5
|
import {
|
|
6
|
+
MAX_INDEX_CHUNKS,
|
|
7
|
+
MAX_INDEX_FILE_BYTES,
|
|
8
|
+
MAX_INDEX_WORKSPACE_BYTES,
|
|
6
9
|
type CodeChunk,
|
|
7
10
|
chunkFile,
|
|
8
11
|
computeHash,
|
|
9
12
|
findChunkableFiles,
|
|
10
|
-
|
|
13
|
+
SUPPORTED_EXTENSIONS,
|
|
11
14
|
} from "./search_chunker";
|
|
12
15
|
import { BM25Engine } from "./search_bm25";
|
|
13
16
|
import { LocalEmbedder } from "./search_embedder";
|
|
@@ -15,13 +18,17 @@ import {
|
|
|
15
18
|
getSearchConfig,
|
|
16
19
|
type SearchConfig,
|
|
17
20
|
type SearchProfile,
|
|
18
|
-
savePersistedProfile,
|
|
19
21
|
} from "./search_config";
|
|
20
22
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
21
23
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
22
24
|
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
25
|
+
import { getSearchCacheDir } from "./search_cache";
|
|
26
|
+
export { getSearchCacheDir } from "./search_cache";
|
|
23
27
|
|
|
24
|
-
const INDEX_VERSION =
|
|
28
|
+
const INDEX_VERSION = 4;
|
|
29
|
+
const LEGACY_INDEX_VERSION = 3;
|
|
30
|
+
const MAX_PERSISTED_INDEX_BYTES = 128 * 1024 * 1024;
|
|
31
|
+
const MAX_PERSISTED_VECTOR_BYTES = MAX_INDEX_CHUNKS * 768 * 4;
|
|
25
32
|
const EXTRACTOR_GENERATION = "tree-sitter-wasm-v2";
|
|
26
33
|
|
|
27
34
|
interface PersistedVectorCache {
|
|
@@ -32,6 +39,274 @@ interface PersistedVectorCache {
|
|
|
32
39
|
fileName: string;
|
|
33
40
|
}
|
|
34
41
|
|
|
42
|
+
interface PersistedIndexSnapshot {
|
|
43
|
+
chunks: CodeChunk[];
|
|
44
|
+
fileHashes: Map<string, string>;
|
|
45
|
+
chunkHashes: Map<string, string>;
|
|
46
|
+
chunkFiles: Map<string, string>;
|
|
47
|
+
ignoreConfigHashes: Map<string, string>;
|
|
48
|
+
staleFiles: Set<string>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
52
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readDescriptorBounded(descriptor: number, maxBytes: number): Buffer {
|
|
56
|
+
const parts: Buffer[] = [];
|
|
57
|
+
let total = 0;
|
|
58
|
+
while (total <= maxBytes) {
|
|
59
|
+
const part = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total));
|
|
60
|
+
const bytesRead = fs.readSync(descriptor, part, 0, part.length, null);
|
|
61
|
+
if (bytesRead === 0) break;
|
|
62
|
+
total += bytesRead;
|
|
63
|
+
if (total > maxBytes) throw new Error("File exceeds size limit");
|
|
64
|
+
parts.push(part.subarray(0, bytesRead));
|
|
65
|
+
}
|
|
66
|
+
return Buffer.concat(parts, total);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function sameFileSnapshot(before: fs.Stats, after: fs.Stats): boolean {
|
|
70
|
+
return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isValidChunkKind(kind: string): boolean {
|
|
74
|
+
return kind === "file" || ["function", "class", "interface", "type", "enum", "variable", "constant", "method", "alias", "test"].includes(kind);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function assertSafeWorkspaceRelativePath(relativePath: string): void {
|
|
78
|
+
if (
|
|
79
|
+
!relativePath ||
|
|
80
|
+
relativePath.includes("\0") ||
|
|
81
|
+
relativePath.includes(":") ||
|
|
82
|
+
path.isAbsolute(relativePath) ||
|
|
83
|
+
relativePath.includes("\\") ||
|
|
84
|
+
relativePath.split("/").some((part) => !part || part === "." || part === "..")
|
|
85
|
+
) {
|
|
86
|
+
throw new Error(`Unsafe persisted file path: ${relativePath}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function canonicalWorkspaceFile(cwd: string, relativePath: string): string {
|
|
91
|
+
assertSafeWorkspaceRelativePath(relativePath);
|
|
92
|
+
const canonicalRoot = fs.realpathSync(path.resolve(cwd));
|
|
93
|
+
const absolutePath = path.resolve(canonicalRoot, relativePath);
|
|
94
|
+
let current = canonicalRoot;
|
|
95
|
+
for (const part of relativePath.split("/")) {
|
|
96
|
+
current = path.join(current, part);
|
|
97
|
+
const stat = fs.lstatSync(current);
|
|
98
|
+
if (stat.isSymbolicLink()) {
|
|
99
|
+
throw new Error(`Persisted workspace path contains a symbolic link: ${relativePath}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const canonicalFile = fs.realpathSync(absolutePath);
|
|
103
|
+
const relative = path.relative(canonicalRoot, canonicalFile);
|
|
104
|
+
if (
|
|
105
|
+
relative === ".." ||
|
|
106
|
+
relative.startsWith(`..${path.sep}`) ||
|
|
107
|
+
path.isAbsolute(relative)
|
|
108
|
+
) {
|
|
109
|
+
throw new Error(`Persisted file escapes workspace: ${relativePath}`);
|
|
110
|
+
}
|
|
111
|
+
return canonicalFile;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function validatePersistedIndex(
|
|
115
|
+
data: unknown,
|
|
116
|
+
cwd: string,
|
|
117
|
+
readSource = readDescriptorBounded,
|
|
118
|
+
): PersistedIndexSnapshot {
|
|
119
|
+
if (!isRecord(data)) throw new Error("Persisted index must be an object");
|
|
120
|
+
if (
|
|
121
|
+
data.version !== INDEX_VERSION &&
|
|
122
|
+
data.version !== LEGACY_INDEX_VERSION
|
|
123
|
+
) {
|
|
124
|
+
throw new Error("Persisted index version mismatch");
|
|
125
|
+
}
|
|
126
|
+
if (data.extractorGeneration !== EXTRACTOR_GENERATION) {
|
|
127
|
+
throw new Error("Persisted index version mismatch");
|
|
128
|
+
}
|
|
129
|
+
if (
|
|
130
|
+
!Array.isArray(data.chunks) ||
|
|
131
|
+
data.chunks.length > MAX_INDEX_CHUNKS ||
|
|
132
|
+
!isRecord(data.fileHashes) ||
|
|
133
|
+
Object.keys(data.fileHashes).length > MAX_INDEX_CHUNKS
|
|
134
|
+
) {
|
|
135
|
+
throw new Error("Persisted index has invalid or oversized chunks/file hashes");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const fileHashes = new Map<string, string>();
|
|
139
|
+
const chunksByFile = new Map<string, CodeChunk[]>();
|
|
140
|
+
for (const [filePath, hash] of Object.entries(data.fileHashes)) {
|
|
141
|
+
if (typeof hash !== "string" || !/^[0-9a-f]{16}$/i.test(hash)) {
|
|
142
|
+
throw new Error(`Invalid persisted hash for ${filePath}`);
|
|
143
|
+
}
|
|
144
|
+
assertSafeWorkspaceRelativePath(filePath);
|
|
145
|
+
fileHashes.set(filePath, hash);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const ids = new Set<string>();
|
|
149
|
+
const chunkHashes = new Map<string, string>();
|
|
150
|
+
const chunkFiles = new Map<string, string>();
|
|
151
|
+
for (const value of data.chunks) {
|
|
152
|
+
if (!isRecord(value)) throw new Error("Persisted chunk must be an object");
|
|
153
|
+
const chunk = value as unknown as CodeChunk;
|
|
154
|
+
if (
|
|
155
|
+
typeof chunk.id !== "string" ||
|
|
156
|
+
!chunk.id ||
|
|
157
|
+
ids.has(chunk.id) ||
|
|
158
|
+
typeof chunk.filePath !== "string" ||
|
|
159
|
+
!fileHashes.has(chunk.filePath) ||
|
|
160
|
+
!Number.isSafeInteger(chunk.startLine) ||
|
|
161
|
+
!Number.isSafeInteger(chunk.endLine) ||
|
|
162
|
+
chunk.startLine > MAX_INDEX_FILE_BYTES ||
|
|
163
|
+
chunk.endLine > MAX_INDEX_FILE_BYTES ||
|
|
164
|
+
!chunk.symbolName ||
|
|
165
|
+
chunk.startLine < 1 ||
|
|
166
|
+
chunk.endLine < chunk.startLine ||
|
|
167
|
+
typeof chunk.content !== "string" ||
|
|
168
|
+
typeof chunk.symbolName !== "string" ||
|
|
169
|
+
!chunk.symbolName ||
|
|
170
|
+
!isValidChunkKind(chunk.kind) ||
|
|
171
|
+
typeof chunk.signature !== "string" ||
|
|
172
|
+
typeof chunk.breadcrumb !== "string" ||
|
|
173
|
+
typeof chunk.textForEmbedding !== "string" ||
|
|
174
|
+
Buffer.byteLength(chunk.content, "utf8") > MAX_INDEX_FILE_BYTES ||
|
|
175
|
+
Buffer.byteLength(chunk.textForEmbedding, "utf8") > MAX_INDEX_FILE_BYTES ||
|
|
176
|
+
chunk.id !== (chunk.kind === "file"
|
|
177
|
+
? `${chunk.filePath}:${chunk.startLine}-${chunk.endLine}`
|
|
178
|
+
: `${chunk.filePath}:${chunk.startLine}-${chunk.endLine}#${chunk.symbolName}`) ||
|
|
179
|
+
typeof chunk.hash !== "string" ||
|
|
180
|
+
chunk.hash !== computeHash(chunk.content)
|
|
181
|
+
) {
|
|
182
|
+
throw new Error(`Invalid persisted chunk: ${String(chunk?.id ?? "<unknown>")}`);
|
|
183
|
+
}
|
|
184
|
+
ids.add(chunk.id);
|
|
185
|
+
chunkHashes.set(chunk.id, chunk.hash);
|
|
186
|
+
chunkFiles.set(chunk.id, chunk.filePath);
|
|
187
|
+
const list = chunksByFile.get(chunk.filePath) || [];
|
|
188
|
+
list.push(chunk);
|
|
189
|
+
chunksByFile.set(chunk.filePath, list);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const validatedChunks: CodeChunk[] = [];
|
|
193
|
+
const staleFiles = new Set<string>();
|
|
194
|
+
let validatedWorkspaceBytes = 0;
|
|
195
|
+
for (const [filePath, expectedHash] of fileHashes) {
|
|
196
|
+
const fileChunks = chunksByFile.get(filePath) || [];
|
|
197
|
+
if (fileChunks.length === 0) {
|
|
198
|
+
throw new Error(`Persisted file has no chunks: ${filePath}`);
|
|
199
|
+
}
|
|
200
|
+
const fileChunkBytes = fileChunks.reduce((total, chunk) => total + Buffer.byteLength(chunk.content, "utf8"), 0);
|
|
201
|
+
if (fileChunkBytes > MAX_INDEX_FILE_BYTES || fileChunkBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
202
|
+
throw new Error(`Persisted chunks exceed file size limits: ${filePath}`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let source: string;
|
|
206
|
+
const workspaceRoot = fs.realpathSync(path.resolve(cwd));
|
|
207
|
+
const unresolvedPath = path.resolve(workspaceRoot, filePath);
|
|
208
|
+
const relativeToWorkspace = path.relative(workspaceRoot, unresolvedPath);
|
|
209
|
+
if (
|
|
210
|
+
relativeToWorkspace === ".." ||
|
|
211
|
+
relativeToWorkspace.startsWith(`..${path.sep}`) ||
|
|
212
|
+
path.isAbsolute(relativeToWorkspace)
|
|
213
|
+
) {
|
|
214
|
+
throw new Error(`Unsafe persisted workspace path: ${filePath}`);
|
|
215
|
+
}
|
|
216
|
+
let absolutePath: string;
|
|
217
|
+
try {
|
|
218
|
+
absolutePath = canonicalWorkspaceFile(cwd, filePath);
|
|
219
|
+
} catch (error: any) {
|
|
220
|
+
if (error?.code === "ENOENT" || error?.code === "ENOTDIR") {
|
|
221
|
+
// Keep the old hash so syncWorkspace can recognize and remove this deleted file.
|
|
222
|
+
staleFiles.add(filePath);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
const relativeCanonical = path.relative(workspaceRoot, absolutePath);
|
|
228
|
+
if (
|
|
229
|
+
relativeCanonical === ".." ||
|
|
230
|
+
relativeCanonical.startsWith(`..${path.sep}`) ||
|
|
231
|
+
path.isAbsolute(relativeCanonical)
|
|
232
|
+
) {
|
|
233
|
+
throw new Error(`Persisted file escapes workspace: ${filePath}`);
|
|
234
|
+
}
|
|
235
|
+
let sourceStat: fs.Stats;
|
|
236
|
+
let descriptor: number | undefined;
|
|
237
|
+
try {
|
|
238
|
+
descriptor = fs.openSync(absolutePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
239
|
+
sourceStat = fs.fstatSync(descriptor);
|
|
240
|
+
if (!sourceStat.isFile() || sourceStat.size > MAX_INDEX_FILE_BYTES) {
|
|
241
|
+
staleFiles.add(filePath);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
source = readSource(descriptor, MAX_INDEX_FILE_BYTES).toString("utf8");
|
|
245
|
+
const afterRead = fs.fstatSync(descriptor);
|
|
246
|
+
if (!sameFileSnapshot(sourceStat, afterRead) || !sameFileSnapshot(sourceStat, fs.statSync(absolutePath))) {
|
|
247
|
+
throw new Error(`Persisted workspace source changed during validation: ${filePath}`);
|
|
248
|
+
}
|
|
249
|
+
const resolvedAfterRead = fs.realpathSync(absolutePath);
|
|
250
|
+
const relativeAfterRead = path.relative(workspaceRoot, resolvedAfterRead);
|
|
251
|
+
if (relativeAfterRead === ".." || relativeAfterRead.startsWith(`..${path.sep}`) || path.isAbsolute(relativeAfterRead)) {
|
|
252
|
+
throw new Error(`Persisted file escaped workspace during validation: ${filePath}`);
|
|
253
|
+
}
|
|
254
|
+
} catch (error: any) {
|
|
255
|
+
if (error?.code === "ENOENT" || error?.code === "ENOTDIR") {
|
|
256
|
+
staleFiles.add(filePath);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
} finally {
|
|
261
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
validatedWorkspaceBytes += Buffer.byteLength(source, "utf8");
|
|
265
|
+
if (validatedWorkspaceBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
266
|
+
throw new Error("Persisted workspace exceeds index size limit");
|
|
267
|
+
}
|
|
268
|
+
if (computeHash(source) !== expectedHash) {
|
|
269
|
+
// Changed files are re-chunked by syncWorkspace; unaffected files remain reusable.
|
|
270
|
+
staleFiles.add(filePath);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const sourceLines = source.split("\n");
|
|
275
|
+
for (const chunk of fileChunks) {
|
|
276
|
+
if (chunk.endLine > sourceLines.length) {
|
|
277
|
+
throw new Error(`Persisted chunk exceeds source bounds: ${chunk.id}`);
|
|
278
|
+
}
|
|
279
|
+
const sourceSlice = sourceLines
|
|
280
|
+
.slice(chunk.startLine - 1, chunk.endLine)
|
|
281
|
+
.join("\n");
|
|
282
|
+
if (sourceSlice !== chunk.content) {
|
|
283
|
+
throw new Error(`Persisted chunk content mismatch: ${chunk.id}`);
|
|
284
|
+
}
|
|
285
|
+
chunk.absolutePath = absolutePath;
|
|
286
|
+
validatedChunks.push(chunk);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const ignoreConfigHashes = new Map<string, string>();
|
|
291
|
+
if (data.ignoreConfigHashes !== undefined) {
|
|
292
|
+
if (!isRecord(data.ignoreConfigHashes)) {
|
|
293
|
+
throw new Error("Persisted ignore hashes must be an object");
|
|
294
|
+
}
|
|
295
|
+
for (const [name, hash] of Object.entries(data.ignoreConfigHashes)) {
|
|
296
|
+
if (
|
|
297
|
+
(name !== ".gitignore" && name !== ".piignore") ||
|
|
298
|
+
typeof hash !== "string" ||
|
|
299
|
+
!/^[0-9a-f]{16}$/i.test(hash)
|
|
300
|
+
) {
|
|
301
|
+
throw new Error(`Invalid persisted ignore hash: ${name}`);
|
|
302
|
+
}
|
|
303
|
+
ignoreConfigHashes.set(name, hash);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return { chunks: validatedChunks, fileHashes, chunkHashes, chunkFiles, ignoreConfigHashes, staleFiles };
|
|
308
|
+
}
|
|
309
|
+
|
|
35
310
|
export interface SearchHit {
|
|
36
311
|
chunk: CodeChunk;
|
|
37
312
|
rrfScore: number;
|
|
@@ -51,17 +326,34 @@ export class HybridSearchIndex {
|
|
|
51
326
|
private chunks: Map<string, CodeChunk> = new Map();
|
|
52
327
|
private vectors: Map<string, Float32Array> = new Map();
|
|
53
328
|
private fileHashes: Map<string, string> = new Map(); // relPath -> SHA256 hash
|
|
329
|
+
private ignoreConfigHashes: Map<string, string> = new Map(); // ignore config file -> SHA256 hash
|
|
54
330
|
private isInitialized = false;
|
|
55
331
|
private isIndexing = false;
|
|
56
332
|
private dirtyFiles = new Set<string>();
|
|
57
333
|
private generation = 0;
|
|
334
|
+
private syncAbortController: AbortController | null = null;
|
|
335
|
+
private fileGenerations = new Map<string, number>();
|
|
336
|
+
private activeFileUpdates = new Map<string, Promise<void>>();
|
|
337
|
+
private debouncedSaveTimer: NodeJS.Timeout | null = null;
|
|
338
|
+
private debouncedSaveDeadline: number | null = null;
|
|
339
|
+
private isSaving = false;
|
|
340
|
+
private hasPendingSave = false;
|
|
341
|
+
private isShuttingDown = false;
|
|
342
|
+
private activeSavePromise: Promise<void> | null = null;
|
|
58
343
|
private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
|
|
59
344
|
private liveCheckPromise: Promise<boolean> | null = null;
|
|
60
345
|
private persistedVectorCaches: PersistedVectorCache[] = [];
|
|
61
|
-
|
|
62
|
-
|
|
346
|
+
private skippedOversizedFiles = new Set<string>();
|
|
347
|
+
private projectTrusted: boolean;
|
|
348
|
+
|
|
349
|
+
constructor(
|
|
350
|
+
cwd: string,
|
|
351
|
+
profile?: SearchProfile,
|
|
352
|
+
options: { projectTrusted?: boolean } = {},
|
|
353
|
+
) {
|
|
63
354
|
this.cwd = cwd;
|
|
64
|
-
this.
|
|
355
|
+
this.projectTrusted = options.projectTrusted === true;
|
|
356
|
+
this.config = getSearchConfig(profile, cwd, this.projectTrusted);
|
|
65
357
|
this.embedder = new LocalEmbedder(this.config);
|
|
66
358
|
this.loadFromDisk();
|
|
67
359
|
}
|
|
@@ -76,15 +368,28 @@ export class HybridSearchIndex {
|
|
|
76
368
|
|
|
77
369
|
public setProfile(profile: SearchProfile): void {
|
|
78
370
|
const oldEffective = this.config.effectiveProfile;
|
|
79
|
-
|
|
80
|
-
this.config = getSearchConfig(profile);
|
|
371
|
+
const oldProfile = this.config.profile;
|
|
372
|
+
this.config = getSearchConfig(profile, this.cwd, this.projectTrusted);
|
|
81
373
|
this.embedder.updateConfig(this.config);
|
|
82
374
|
|
|
83
|
-
if (oldEffective !== this.config.effectiveProfile) {
|
|
375
|
+
if (oldProfile !== this.config.profile || oldEffective !== this.config.effectiveProfile) {
|
|
376
|
+
this.generation++;
|
|
377
|
+
if (this.debouncedSaveTimer) {
|
|
378
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
379
|
+
this.debouncedSaveTimer = null;
|
|
380
|
+
this.debouncedSaveDeadline = null;
|
|
381
|
+
}
|
|
382
|
+
if (this.syncAbortController) {
|
|
383
|
+
this.syncAbortController.abort();
|
|
384
|
+
this.syncAbortController = null;
|
|
385
|
+
}
|
|
386
|
+
this.activeSync = null;
|
|
387
|
+
|
|
84
388
|
// Keep vector caches on disk; only the active in-memory representation
|
|
85
389
|
// changes when switching profiles.
|
|
86
390
|
this.vectors.clear();
|
|
87
391
|
this.isInitialized = false;
|
|
392
|
+
this.loadFromDisk();
|
|
88
393
|
}
|
|
89
394
|
|
|
90
395
|
if (
|
|
@@ -118,7 +423,7 @@ export class HybridSearchIndex {
|
|
|
118
423
|
}
|
|
119
424
|
|
|
120
425
|
private getCacheDir(): string {
|
|
121
|
-
return
|
|
426
|
+
return getSearchCacheDir(this.cwd);
|
|
122
427
|
}
|
|
123
428
|
|
|
124
429
|
private getIndexFilePath(): string {
|
|
@@ -139,19 +444,32 @@ export class HybridSearchIndex {
|
|
|
139
444
|
(cache: any): cache is PersistedVectorCache =>
|
|
140
445
|
cache &&
|
|
141
446
|
Number.isInteger(cache.vectorDim) &&
|
|
142
|
-
cache.vectorDim
|
|
143
|
-
|
|
447
|
+
(cache.vectorDim === 256 || cache.vectorDim === 768) &&
|
|
448
|
+
Array.isArray(cache.vectorChunkIds) &&
|
|
449
|
+
cache.vectorChunkIds.length <= MAX_INDEX_CHUNKS &&
|
|
450
|
+
cache.vectorChunkIds.every((id: unknown) => typeof id === "string" && id.length > 0 && id.length <= 4096) &&
|
|
451
|
+
(cache.vectorChunkHashes === undefined ||
|
|
452
|
+
(Array.isArray(cache.vectorChunkHashes) &&
|
|
453
|
+
cache.vectorChunkHashes.length === cache.vectorChunkIds.length &&
|
|
454
|
+
cache.vectorChunkHashes.every((hash: unknown) => typeof hash === "string" && /^[0-9a-f]{16}$/i.test(hash)))) &&
|
|
455
|
+
new Set(cache.vectorChunkIds).size === cache.vectorChunkIds.length &&
|
|
144
456
|
typeof cache.vectorHash === "string" &&
|
|
457
|
+
/^[0-9a-f]{64}$/i.test(cache.vectorHash) &&
|
|
145
458
|
typeof cache.fileName === "string" &&
|
|
146
|
-
|
|
459
|
+
(cache.fileName === "vectors.bin" || cache.fileName === `vectors-${cache.vectorDim}d.bin`),
|
|
147
460
|
);
|
|
148
461
|
}
|
|
149
462
|
|
|
150
463
|
if (
|
|
151
464
|
Number.isInteger(data.vectorDim) &&
|
|
152
|
-
data.vectorDim
|
|
465
|
+
(data.vectorDim === 256 || data.vectorDim === 768) &&
|
|
153
466
|
Array.isArray(data.vectorChunkIds) &&
|
|
154
|
-
|
|
467
|
+
data.vectorChunkIds.length <= MAX_INDEX_CHUNKS &&
|
|
468
|
+
data.vectorChunkIds.every((id: unknown) => typeof id === "string" && id.length > 0 && id.length <= 4096) &&
|
|
469
|
+
new Set(data.vectorChunkIds).size === data.vectorChunkIds.length &&
|
|
470
|
+
(data.vectorChunkHashes === undefined || (Array.isArray(data.vectorChunkHashes) && data.vectorChunkHashes.length === data.vectorChunkIds.length && data.vectorChunkHashes.every((hash: unknown) => typeof hash === "string" && /^[0-9a-f]{16}$/i.test(hash)))) &&
|
|
471
|
+
typeof data.vectorHash === "string" &&
|
|
472
|
+
/^[0-9a-f]{64}$/i.test(data.vectorHash)
|
|
155
473
|
) {
|
|
156
474
|
return [{
|
|
157
475
|
vectorDim: data.vectorDim,
|
|
@@ -171,7 +489,11 @@ export class HybridSearchIndex {
|
|
|
171
489
|
);
|
|
172
490
|
}
|
|
173
491
|
|
|
174
|
-
private loadVectorCache(
|
|
492
|
+
private loadVectorCache(
|
|
493
|
+
cache: PersistedVectorCache,
|
|
494
|
+
persistedChunkHashes: Map<string, string>,
|
|
495
|
+
allowUnhashedVectors = false,
|
|
496
|
+
): void {
|
|
175
497
|
const vectorChunkIds = cache.vectorChunkIds;
|
|
176
498
|
const vectorPath = this.getVectorsFilePath(cache.fileName);
|
|
177
499
|
if (
|
|
@@ -180,8 +502,18 @@ export class HybridSearchIndex {
|
|
|
180
502
|
new Set(vectorChunkIds).size !== vectorChunkIds.length
|
|
181
503
|
) return;
|
|
182
504
|
|
|
183
|
-
const buffer = fs.readFileSync(vectorPath);
|
|
184
505
|
const expectedBytes = vectorChunkIds.length * cache.vectorDim * 4;
|
|
506
|
+
if (expectedBytes > MAX_PERSISTED_VECTOR_BYTES) return;
|
|
507
|
+
const descriptor = fs.openSync(vectorPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
508
|
+
let buffer: Buffer;
|
|
509
|
+
try {
|
|
510
|
+
const before = fs.fstatSync(descriptor);
|
|
511
|
+
if (!before.isFile() || before.size !== expectedBytes) return;
|
|
512
|
+
buffer = readDescriptorBounded(descriptor, expectedBytes);
|
|
513
|
+
if (!sameFileSnapshot(before, fs.fstatSync(descriptor))) return;
|
|
514
|
+
} finally {
|
|
515
|
+
fs.closeSync(descriptor);
|
|
516
|
+
}
|
|
185
517
|
if (
|
|
186
518
|
buffer.byteLength !== expectedBytes ||
|
|
187
519
|
cache.vectorHash !==
|
|
@@ -197,25 +529,27 @@ export class HybridSearchIndex {
|
|
|
197
529
|
Array.isArray(cache.vectorChunkHashes) &&
|
|
198
530
|
cache.vectorChunkHashes.length === vectorChunkIds.length;
|
|
199
531
|
if (Array.isArray(cache.vectorChunkHashes) && !hasChunkHashes) return;
|
|
200
|
-
if (!hasChunkHashes &&
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
) return;
|
|
206
|
-
|
|
532
|
+
if (!hasChunkHashes && (
|
|
533
|
+
!allowUnhashedVectors ||
|
|
534
|
+
vectorChunkIds.length !== this.chunks.size ||
|
|
535
|
+
vectorChunkIds.some((id) => !this.chunks.has(id)) ||
|
|
536
|
+
!this.isWorkspaceSnapshotFresh()
|
|
537
|
+
)) return;
|
|
207
538
|
const floatArray = new Float32Array(
|
|
208
539
|
buffer.buffer,
|
|
209
540
|
buffer.byteOffset,
|
|
210
541
|
buffer.byteLength / 4,
|
|
211
542
|
);
|
|
543
|
+
for (const value of floatArray) {
|
|
544
|
+
if (!Number.isFinite(value)) return;
|
|
545
|
+
}
|
|
212
546
|
for (let index = 0; index < vectorChunkIds.length; index++) {
|
|
213
547
|
const chunkId = vectorChunkIds[index];
|
|
214
548
|
if (!this.chunks.has(chunkId)) continue;
|
|
215
|
-
if (
|
|
216
|
-
|
|
549
|
+
if (hasChunkHashes && (
|
|
550
|
+
cache.vectorChunkHashes?.[index] !== persistedChunkHashes.get(chunkId) ||
|
|
217
551
|
cache.vectorChunkHashes?.[index] !== currentHashes.get(chunkId)
|
|
218
|
-
) continue;
|
|
552
|
+
)) continue;
|
|
219
553
|
const vector = new Float32Array(cache.vectorDim);
|
|
220
554
|
vector.set(
|
|
221
555
|
floatArray.subarray(
|
|
@@ -236,41 +570,45 @@ export class HybridSearchIndex {
|
|
|
236
570
|
if (!fs.existsSync(indexPath)) return false;
|
|
237
571
|
|
|
238
572
|
try {
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
573
|
+
const descriptor = fs.openSync(indexPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
574
|
+
let data: any;
|
|
575
|
+
let validated: PersistedIndexSnapshot;
|
|
576
|
+
try {
|
|
577
|
+
const before = fs.fstatSync(descriptor);
|
|
578
|
+
if (!before.isFile()) throw new Error("Persisted index is not a regular file");
|
|
579
|
+
const raw = readDescriptorBounded(descriptor, MAX_PERSISTED_INDEX_BYTES).toString("utf8");
|
|
580
|
+
data = JSON.parse(raw);
|
|
581
|
+
validated = validatePersistedIndex(data, this.cwd);
|
|
582
|
+
if (!sameFileSnapshot(before, fs.fstatSync(descriptor)) || !sameFileSnapshot(before, fs.statSync(indexPath))) {
|
|
583
|
+
throw new Error("Persisted index changed while loading");
|
|
584
|
+
}
|
|
585
|
+
} finally {
|
|
586
|
+
fs.closeSync(descriptor);
|
|
247
587
|
}
|
|
588
|
+
const persistedVectorCaches = this.getPersistedVectorCaches(data).filter((cache) =>
|
|
589
|
+
cache.vectorChunkIds.every((id) => validated.chunkFiles.has(id)),
|
|
590
|
+
);
|
|
248
591
|
|
|
249
592
|
this.chunks.clear();
|
|
250
593
|
this.bm25.clear();
|
|
251
594
|
this.fileHashes.clear();
|
|
595
|
+
this.ignoreConfigHashes.clear();
|
|
252
596
|
this.vectors.clear();
|
|
253
597
|
this.persistedVectorCaches = [];
|
|
254
598
|
|
|
255
|
-
for (const chunk of
|
|
256
|
-
// Normalize chunk.filePath alias if chunk was serialized with file
|
|
257
|
-
if (!chunk.filePath && (chunk as any).file) {
|
|
258
|
-
chunk.filePath = (chunk as any).file;
|
|
259
|
-
}
|
|
260
|
-
// Rebase absolutePath to the current workspace root if paths differ
|
|
261
|
-
if (chunk.filePath && this.cwd) {
|
|
262
|
-
chunk.absolutePath = path.resolve(this.cwd, chunk.filePath);
|
|
263
|
-
}
|
|
599
|
+
for (const chunk of validated.chunks) {
|
|
264
600
|
this.chunks.set(chunk.id, chunk);
|
|
265
601
|
this.bm25.addChunk(chunk);
|
|
266
602
|
}
|
|
267
603
|
this.bm25.recalculateStats();
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
604
|
+
for (const [file, hash] of validated.fileHashes) {
|
|
605
|
+
this.fileHashes.set(file, hash);
|
|
606
|
+
}
|
|
607
|
+
for (const [file, hash] of validated.ignoreConfigHashes) {
|
|
608
|
+
this.ignoreConfigHashes.set(file, hash);
|
|
271
609
|
}
|
|
272
610
|
|
|
273
|
-
this.persistedVectorCaches =
|
|
611
|
+
this.persistedVectorCaches = persistedVectorCaches;
|
|
274
612
|
const wantsVectors =
|
|
275
613
|
this.config.effectiveProfile === "hybrid" ||
|
|
276
614
|
this.config.effectiveProfile === "full";
|
|
@@ -278,7 +616,16 @@ export class HybridSearchIndex {
|
|
|
278
616
|
(cache) => cache.vectorDim === this.config.matryoshkaDim,
|
|
279
617
|
);
|
|
280
618
|
if (wantsVectors && activeCache) {
|
|
281
|
-
|
|
619
|
+
try {
|
|
620
|
+
this.loadVectorCache(
|
|
621
|
+
activeCache,
|
|
622
|
+
validated.chunkHashes,
|
|
623
|
+
data.version === LEGACY_INDEX_VERSION && validated.staleFiles.size === 0,
|
|
624
|
+
);
|
|
625
|
+
} catch (error) {
|
|
626
|
+
this.vectors.clear();
|
|
627
|
+
kernelDebug(error);
|
|
628
|
+
}
|
|
282
629
|
}
|
|
283
630
|
|
|
284
631
|
const vectorsReady =
|
|
@@ -288,9 +635,10 @@ export class HybridSearchIndex {
|
|
|
288
635
|
Array.from(this.vectors.values()).every(
|
|
289
636
|
(vector) => vector.length === this.config.matryoshkaDim,
|
|
290
637
|
));
|
|
291
|
-
this.isInitialized = vectorsReady;
|
|
638
|
+
this.isInitialized = vectorsReady && validated.staleFiles.size === 0;
|
|
292
639
|
return true;
|
|
293
|
-
} catch {
|
|
640
|
+
} catch (error) {
|
|
641
|
+
kernelDebug(error);
|
|
294
642
|
return false;
|
|
295
643
|
}
|
|
296
644
|
}
|
|
@@ -301,19 +649,6 @@ export class HybridSearchIndex {
|
|
|
301
649
|
public saveToDisk(): void {
|
|
302
650
|
try {
|
|
303
651
|
const cacheDir = this.getCacheDir();
|
|
304
|
-
if (!fs.existsSync(cacheDir)) {
|
|
305
|
-
fs.mkdirSync(cacheDir, { recursive: true });
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// Ensure .gitignore exists in .pi/cache
|
|
309
|
-
const gitignorePath = path.join(this.cwd, ".pi", "cache", ".gitignore");
|
|
310
|
-
if (!fs.existsSync(gitignorePath)) {
|
|
311
|
-
try {
|
|
312
|
-
fs.writeFileSync(gitignorePath, "*\n!.gitignore\n", "utf-8");
|
|
313
|
-
} catch (e) {
|
|
314
|
-
kernelDebug(e);
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
652
|
|
|
318
653
|
const chunkList = Array.from(this.chunks.values());
|
|
319
654
|
const fileHashesObj: Record<string, string> = {};
|
|
@@ -351,6 +686,7 @@ export class HybridSearchIndex {
|
|
|
351
686
|
const vectorChunkHashes = vectorChunkIds.map(
|
|
352
687
|
(id) => this.chunks.get(id)?.hash || "",
|
|
353
688
|
);
|
|
689
|
+
if (vectorChunkHashes.some((hash) => !hash)) return;
|
|
354
690
|
const fileName = this.getVectorCacheFileName(vectorDim);
|
|
355
691
|
vectorCaches.set(vectorDim, {
|
|
356
692
|
vectorDim,
|
|
@@ -369,6 +705,7 @@ export class HybridSearchIndex {
|
|
|
369
705
|
updatedAt: new Date().toISOString(),
|
|
370
706
|
profile: this.config.profile,
|
|
371
707
|
fileHashes: fileHashesObj,
|
|
708
|
+
ignoreConfigHashes: Object.fromEntries(this.ignoreConfigHashes),
|
|
372
709
|
chunks: chunkList,
|
|
373
710
|
vectorCaches: this.persistedVectorCaches,
|
|
374
711
|
};
|
|
@@ -382,6 +719,71 @@ export class HybridSearchIndex {
|
|
|
382
719
|
}
|
|
383
720
|
}
|
|
384
721
|
|
|
722
|
+
/**
|
|
723
|
+
* Schedule debounced disk persistence to coalesce rapid edits.
|
|
724
|
+
*/
|
|
725
|
+
public scheduleDebouncedSave(delayMs = 500, maxDelayMs = 2000): void {
|
|
726
|
+
const now = Date.now();
|
|
727
|
+
if (!this.debouncedSaveDeadline) {
|
|
728
|
+
this.debouncedSaveDeadline = now + maxDelayMs;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (this.debouncedSaveTimer) {
|
|
732
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
733
|
+
this.debouncedSaveTimer = null;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const remainingMax = Math.max(0, this.debouncedSaveDeadline - now);
|
|
737
|
+
const actualDelay = Math.min(delayMs, remainingMax);
|
|
738
|
+
|
|
739
|
+
this.debouncedSaveTimer = setTimeout(() => {
|
|
740
|
+
this.debouncedSaveTimer = null;
|
|
741
|
+
this.debouncedSaveDeadline = null;
|
|
742
|
+
void this.flushPendingSave();
|
|
743
|
+
}, actualDelay);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Flush any pending index updates to disk cache.
|
|
748
|
+
*/
|
|
749
|
+
public async flushPendingSave(isFinalShutdown = false): Promise<void> {
|
|
750
|
+
if (isFinalShutdown) {
|
|
751
|
+
this.isShuttingDown = true;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Disarm debounce timer immediately to prevent reentrancy while awaiting tasks
|
|
755
|
+
if (this.debouncedSaveTimer) {
|
|
756
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
757
|
+
this.debouncedSaveTimer = null;
|
|
758
|
+
this.debouncedSaveDeadline = null;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// Await any in-flight full workspace sync
|
|
762
|
+
await this.waitForActiveSync();
|
|
763
|
+
|
|
764
|
+
// Drain all active in-flight file updates first so latest edits commit to RAM before saving
|
|
765
|
+
while (this.activeFileUpdates.size > 0) {
|
|
766
|
+
await Promise.allSettled(Array.from(this.activeFileUpdates.values()));
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// Await any active in-flight save before starting final save
|
|
770
|
+
while (this.activeSavePromise) {
|
|
771
|
+
await this.activeSavePromise;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const saveTask = (async () => {
|
|
775
|
+
this.saveToDisk();
|
|
776
|
+
})();
|
|
777
|
+
this.activeSavePromise = saveTask;
|
|
778
|
+
try {
|
|
779
|
+
await saveTask;
|
|
780
|
+
} finally {
|
|
781
|
+
if (this.activeSavePromise === saveTask) {
|
|
782
|
+
this.activeSavePromise = null;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
385
787
|
/**
|
|
386
788
|
* Synchronize and incrementally update workspace index.
|
|
387
789
|
*/
|
|
@@ -391,14 +793,24 @@ export class HybridSearchIndex {
|
|
|
391
793
|
): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
|
|
392
794
|
if (this.activeSync) return this.activeSync;
|
|
393
795
|
|
|
796
|
+
const abortController = new AbortController();
|
|
797
|
+
this.syncAbortController = abortController;
|
|
798
|
+
const syncGeneration = ++this.generation;
|
|
799
|
+
|
|
394
800
|
const sync = (async () => {
|
|
395
801
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
396
|
-
|
|
802
|
+
if (abortController.signal.aborted) {
|
|
803
|
+
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
|
|
804
|
+
}
|
|
397
805
|
const result = await this.performSyncWorkspace(
|
|
398
806
|
forceReindex && attempt === 0,
|
|
399
807
|
onProgress,
|
|
400
808
|
syncGeneration,
|
|
809
|
+
abortController.signal,
|
|
401
810
|
);
|
|
811
|
+
if (abortController.signal.aborted) {
|
|
812
|
+
return result;
|
|
813
|
+
}
|
|
402
814
|
if (
|
|
403
815
|
this.generation !== syncGeneration ||
|
|
404
816
|
!this.isWorkspaceSnapshotFresh()
|
|
@@ -416,16 +828,74 @@ export class HybridSearchIndex {
|
|
|
416
828
|
try {
|
|
417
829
|
return await sync;
|
|
418
830
|
} finally {
|
|
419
|
-
if (this.activeSync === sync)
|
|
831
|
+
if (this.activeSync === sync) {
|
|
832
|
+
this.activeSync = null;
|
|
833
|
+
if (this.syncAbortController === abortController) {
|
|
834
|
+
this.syncAbortController = null;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
private getWorkspaceIgnoreHashes(): Map<string, string> {
|
|
841
|
+
const hashes = new Map<string, string>();
|
|
842
|
+
const gitIgnorePath = path.join(this.cwd, ".gitignore");
|
|
843
|
+
if (fs.existsSync(gitIgnorePath)) {
|
|
844
|
+
try {
|
|
845
|
+
hashes.set(".gitignore", computeHash(fs.readFileSync(gitIgnorePath, "utf8")));
|
|
846
|
+
} catch (e) {
|
|
847
|
+
kernelDebug(e);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const piIgnorePath = path.join(this.cwd, ".piignore");
|
|
851
|
+
if (fs.existsSync(piIgnorePath)) {
|
|
852
|
+
try {
|
|
853
|
+
hashes.set(".piignore", computeHash(fs.readFileSync(piIgnorePath, "utf8")));
|
|
854
|
+
} catch (e) {
|
|
855
|
+
kernelDebug(e);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return hashes;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
private isIgnoreConfigFresh(): boolean {
|
|
862
|
+
const current = this.getWorkspaceIgnoreHashes();
|
|
863
|
+
if (current.size !== this.ignoreConfigHashes.size) return false;
|
|
864
|
+
for (const [k, v] of this.ignoreConfigHashes.entries()) {
|
|
865
|
+
if (current.get(k) !== v) return false;
|
|
420
866
|
}
|
|
867
|
+
return true;
|
|
421
868
|
}
|
|
422
869
|
|
|
423
870
|
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
424
871
|
const hashes = new Map<string, string>();
|
|
425
|
-
|
|
872
|
+
let workspaceBytes = 0;
|
|
873
|
+
const files = findChunkableFiles(this.cwd).sort();
|
|
874
|
+
for (const filePath of files) {
|
|
426
875
|
const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
|
|
427
876
|
try {
|
|
428
|
-
|
|
877
|
+
const descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
878
|
+
let content: string;
|
|
879
|
+
let opened: fs.Stats;
|
|
880
|
+
try {
|
|
881
|
+
opened = fs.fstatSync(descriptor);
|
|
882
|
+
if (!opened.isFile() || opened.size > MAX_INDEX_FILE_BYTES || workspaceBytes + opened.size > MAX_INDEX_WORKSPACE_BYTES) {
|
|
883
|
+
this.skippedOversizedFiles.add(relPath);
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
content = readDescriptorBounded(descriptor, MAX_INDEX_FILE_BYTES).toString("utf8");
|
|
887
|
+
} finally {
|
|
888
|
+
fs.closeSync(descriptor);
|
|
889
|
+
}
|
|
890
|
+
const afterRead = fs.statSync(filePath);
|
|
891
|
+
if (!sameFileSnapshot(opened, afterRead)) return null;
|
|
892
|
+
const actualBytes = Buffer.byteLength(content, "utf8");
|
|
893
|
+
if (actualBytes > MAX_INDEX_FILE_BYTES || workspaceBytes + actualBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
894
|
+
this.skippedOversizedFiles.add(relPath);
|
|
895
|
+
continue;
|
|
896
|
+
}
|
|
897
|
+
workspaceBytes += actualBytes;
|
|
898
|
+
hashes.set(relPath, computeHash(content));
|
|
429
899
|
} catch (error) {
|
|
430
900
|
kernelDebug(error);
|
|
431
901
|
return null;
|
|
@@ -435,6 +905,7 @@ export class HybridSearchIndex {
|
|
|
435
905
|
}
|
|
436
906
|
|
|
437
907
|
private isWorkspaceSnapshotFresh(): boolean {
|
|
908
|
+
if (!this.isIgnoreConfigFresh()) return false;
|
|
438
909
|
const currentHashes = this.getWorkspaceFileHashes();
|
|
439
910
|
if (!currentHashes || currentHashes.size !== this.fileHashes.size) return false;
|
|
440
911
|
for (const [relPath, hash] of this.fileHashes.entries()) {
|
|
@@ -492,7 +963,14 @@ export class HybridSearchIndex {
|
|
|
492
963
|
forceReindex: boolean,
|
|
493
964
|
onProgress: ((msg: string) => void) | undefined,
|
|
494
965
|
syncGeneration: number,
|
|
966
|
+
signal?: AbortSignal,
|
|
495
967
|
): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
|
|
968
|
+
if (this.config.effectiveProfile === "off") {
|
|
969
|
+
return { chunkCount: 0, fileCount: 0, indexedCount: 0 };
|
|
970
|
+
}
|
|
971
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
972
|
+
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
|
|
973
|
+
}
|
|
496
974
|
this.isIndexing = true;
|
|
497
975
|
try {
|
|
498
976
|
if (
|
|
@@ -506,7 +984,8 @@ export class HybridSearchIndex {
|
|
|
506
984
|
onProgress?.("Scanning workspace files...");
|
|
507
985
|
|
|
508
986
|
// Ensure Tree-sitter parsers are warm for languages present in this workspace
|
|
509
|
-
const chunkableFiles = findChunkableFiles(this.cwd);
|
|
987
|
+
const chunkableFiles = findChunkableFiles(this.cwd).sort();
|
|
988
|
+
this.skippedOversizedFiles.clear();
|
|
510
989
|
const workspaceExts = new Set<string>();
|
|
511
990
|
for (const f of chunkableFiles) {
|
|
512
991
|
const ext = path.extname(f).toLowerCase();
|
|
@@ -517,18 +996,48 @@ export class HybridSearchIndex {
|
|
|
517
996
|
// Read each file once and derive both its chunks and hash from that same
|
|
518
997
|
// snapshot. A second read could pair old chunks with a new hash and make
|
|
519
998
|
// the final freshness check falsely accept stale content.
|
|
520
|
-
const currentFiles = new Map<
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
>();
|
|
999
|
+
const currentFiles = new Map<string, { hash: string; chunks: CodeChunk[] }>();
|
|
1000
|
+
let workspaceBytes = 0;
|
|
1001
|
+
let workspaceChunks = 0;
|
|
524
1002
|
for (const absPath of chunkableFiles) {
|
|
525
1003
|
const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
|
|
526
1004
|
try {
|
|
527
|
-
const
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
1005
|
+
const stat = fs.statSync(absPath);
|
|
1006
|
+
if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
|
|
1007
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (workspaceBytes + stat.size > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1011
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
const descriptor = fs.openSync(absPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
1015
|
+
let content: string;
|
|
1016
|
+
let opened: fs.Stats;
|
|
1017
|
+
try {
|
|
1018
|
+
opened = fs.fstatSync(descriptor);
|
|
1019
|
+
if (!opened.isFile()) throw new Error(`Not a regular file: ${relPath}`);
|
|
1020
|
+
content = readDescriptorBounded(descriptor, MAX_INDEX_FILE_BYTES).toString("utf8");
|
|
1021
|
+
} finally {
|
|
1022
|
+
fs.closeSync(descriptor);
|
|
1023
|
+
}
|
|
1024
|
+
const afterRead = fs.statSync(absPath);
|
|
1025
|
+
if (!sameFileSnapshot(opened, afterRead)) {
|
|
1026
|
+
throw new Error(`Workspace file changed while reading: ${relPath}`);
|
|
1027
|
+
}
|
|
1028
|
+
const actualBytes = Buffer.byteLength(content, "utf8");
|
|
1029
|
+
if (actualBytes > MAX_INDEX_FILE_BYTES || workspaceBytes + actualBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1030
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
const chunks = chunkFile(this.cwd, absPath, content);
|
|
1034
|
+
if (workspaceChunks + chunks.length > MAX_INDEX_CHUNKS) {
|
|
1035
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
workspaceBytes += actualBytes;
|
|
1039
|
+
workspaceChunks += chunks.length;
|
|
1040
|
+
currentFiles.set(relPath, { hash: computeHash(content), chunks });
|
|
532
1041
|
} catch (error) {
|
|
533
1042
|
kernelDebug(error);
|
|
534
1043
|
}
|
|
@@ -548,7 +1057,7 @@ export class HybridSearchIndex {
|
|
|
548
1057
|
const vector = this.vectors.get(chunk.id);
|
|
549
1058
|
return !vector || vector.length !== this.config.matryoshkaDim;
|
|
550
1059
|
});
|
|
551
|
-
if (forceReindex ||
|
|
1060
|
+
if (forceReindex || !oldHash || oldHash !== info.hash || missingFileVectors) {
|
|
552
1061
|
filesToReindex.push(relPath);
|
|
553
1062
|
}
|
|
554
1063
|
}
|
|
@@ -611,31 +1120,71 @@ export class HybridSearchIndex {
|
|
|
611
1120
|
const sleepMs = this.config.sleepBetweenBatchesMs || 50;
|
|
612
1121
|
const embedStartTime = Date.now();
|
|
613
1122
|
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
1123
|
+
for (let i = 0; i < chunksToEmbed.length; i += batchSize) {
|
|
1124
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
1125
|
+
kernelDebug("[Search Index] Aborting embedding loop due to cancellation signal or newer generation");
|
|
1126
|
+
break;
|
|
1127
|
+
}
|
|
1128
|
+
const batch = chunksToEmbed.slice(i, i + batchSize);
|
|
1129
|
+
const texts = batch.map((c) => c.textForEmbedding);
|
|
1130
|
+
const processed = Math.min(i + batch.length, chunksToEmbed.length);
|
|
1131
|
+
const pct = Math.round((processed / chunksToEmbed.length) * 100);
|
|
1132
|
+
const elapsedSec = Math.max(0.001, (Date.now() - embedStartTime) / 1000);
|
|
1133
|
+
const chunkSpeed = (processed / elapsedSec).toFixed(1);
|
|
1134
|
+
onProgress?.(
|
|
1135
|
+
`Embedding code chunks: ${pct}% (${processed}/${chunksToEmbed.length} • ${chunkSpeed} chunk/s)`,
|
|
1136
|
+
);
|
|
1137
|
+
const vecs = await this.embedder.embedBatch(texts, false, onProgress);
|
|
1138
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
1139
|
+
kernelDebug("[Search Index] Aborting post-embedBatch due to cancellation signal or newer generation");
|
|
1140
|
+
break;
|
|
1141
|
+
}
|
|
631
1142
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
1143
|
+
for (let j = 0; j < batch.length; j++) {
|
|
1144
|
+
const vector = vecs[j];
|
|
1145
|
+
if (!vector || vector.length !== this.config.matryoshkaDim || !Array.from(vector).every(Number.isFinite)) continue;
|
|
1146
|
+
const chunk = batch[j];
|
|
1147
|
+
const activeChunk = this.chunks.get(chunk.id);
|
|
1148
|
+
if (activeChunk?.hash === chunk.hash) this.vectors.set(chunk.id, vector);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// Async sleep to yield CPU and prevent freezing system daemons
|
|
1152
|
+
if (sleepMs > 0 && i + batchSize < chunksToEmbed.length) {
|
|
1153
|
+
await new Promise((r) => {
|
|
1154
|
+
const timeout = setTimeout(r, sleepMs);
|
|
1155
|
+
signal?.addEventListener(
|
|
1156
|
+
"abort",
|
|
1157
|
+
() => {
|
|
1158
|
+
clearTimeout(timeout);
|
|
1159
|
+
r(undefined);
|
|
1160
|
+
},
|
|
1161
|
+
{ once: true },
|
|
1162
|
+
);
|
|
1163
|
+
});
|
|
636
1164
|
}
|
|
637
1165
|
}
|
|
1166
|
+
}
|
|
638
1167
|
|
|
1168
|
+
if (!signal?.aborted && this.generation === syncGeneration) {
|
|
1169
|
+
this.saveToDisk();
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// Track ignore configuration hashes in dedicated metadata
|
|
1174
|
+
const oldIgnoreHashes = new Map(this.ignoreConfigHashes);
|
|
1175
|
+
const currentIgnoreHashes = this.getWorkspaceIgnoreHashes();
|
|
1176
|
+
let ignoreConfigChanged = currentIgnoreHashes.size !== oldIgnoreHashes.size;
|
|
1177
|
+
if (!ignoreConfigChanged) {
|
|
1178
|
+
for (const [k, v] of currentIgnoreHashes.entries()) {
|
|
1179
|
+
if (oldIgnoreHashes.get(k) !== v) {
|
|
1180
|
+
ignoreConfigChanged = true;
|
|
1181
|
+
break;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
this.ignoreConfigHashes = currentIgnoreHashes;
|
|
1186
|
+
|
|
1187
|
+
if (filesToDelete.length > 0 || filesToReindex.length > 0 || ignoreConfigChanged) {
|
|
639
1188
|
this.saveToDisk();
|
|
640
1189
|
}
|
|
641
1190
|
|
|
@@ -651,6 +1200,255 @@ export class HybridSearchIndex {
|
|
|
651
1200
|
}
|
|
652
1201
|
}
|
|
653
1202
|
|
|
1203
|
+
private removeIndexedFile(relPath: string): void {
|
|
1204
|
+
this.bm25.removeFile(relPath);
|
|
1205
|
+
this.fileHashes.delete(relPath);
|
|
1206
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
1207
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1208
|
+
this.chunks.delete(chunkId);
|
|
1209
|
+
this.vectors.delete(chunkId);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/**
|
|
1215
|
+
* Transactional incremental update of a single file in the index.
|
|
1216
|
+
* Chunks only this file, reuses existing vectors for unchanged chunks by content hash,
|
|
1217
|
+
* embeds only new/modified chunks off-to-the-side, and commits atomically.
|
|
1218
|
+
*/
|
|
1219
|
+
public async updateFile(filePath: string): Promise<void> {
|
|
1220
|
+
if (this.isShuttingDown) return;
|
|
1221
|
+
|
|
1222
|
+
const resolvedPath = path.resolve(this.cwd, filePath);
|
|
1223
|
+
const relPath = path
|
|
1224
|
+
.relative(this.cwd, resolvedPath)
|
|
1225
|
+
.replace(/\\/g, "/");
|
|
1226
|
+
if (
|
|
1227
|
+
!relPath ||
|
|
1228
|
+
relPath === ".." ||
|
|
1229
|
+
relPath.startsWith("../") ||
|
|
1230
|
+
path.isAbsolute(relPath)
|
|
1231
|
+
) return;
|
|
1232
|
+
|
|
1233
|
+
// If a full workspace sync is active, mark dirty and let full sync capture the latest file content
|
|
1234
|
+
if (this.isIndexing || this.activeSync) {
|
|
1235
|
+
this.dirtyFiles.add(relPath);
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
if (!SUPPORTED_EXTENSIONS.has(path.extname(resolvedPath).toLowerCase())) {
|
|
1240
|
+
this.removeIndexedFile(relPath);
|
|
1241
|
+
this.dirtyFiles.delete(relPath);
|
|
1242
|
+
this.bm25.recalculateStats();
|
|
1243
|
+
this.scheduleDebouncedSave();
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const currentGen = (this.fileGenerations.get(relPath) ?? 0) + 1;
|
|
1248
|
+
this.fileGenerations.set(relPath, currentGen);
|
|
1249
|
+
|
|
1250
|
+
const task = (async () => {
|
|
1251
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1252
|
+
|
|
1253
|
+
// Check if file was deleted
|
|
1254
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
1255
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1256
|
+
this.bm25.removeFile(relPath);
|
|
1257
|
+
this.fileHashes.delete(relPath);
|
|
1258
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
1259
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1260
|
+
this.chunks.delete(chunkId);
|
|
1261
|
+
this.vectors.delete(chunkId);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
this.dirtyFiles.delete(relPath);
|
|
1265
|
+
this.bm25.recalculateStats();
|
|
1266
|
+
this.scheduleDebouncedSave();
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// Read file content with bounded allocation and TOCTOU protection
|
|
1271
|
+
let content: string;
|
|
1272
|
+
try {
|
|
1273
|
+
const stat = fs.statSync(resolvedPath);
|
|
1274
|
+
if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
|
|
1275
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1276
|
+
this.removeIndexedFile(relPath);
|
|
1277
|
+
this.dirtyFiles.delete(relPath);
|
|
1278
|
+
this.scheduleDebouncedSave();
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
let workspaceBytes = 0;
|
|
1282
|
+
for (const indexedPath of this.fileHashes.keys()) {
|
|
1283
|
+
if (indexedPath === relPath) continue;
|
|
1284
|
+
try {
|
|
1285
|
+
const indexedStat = fs.statSync(path.join(this.cwd, indexedPath));
|
|
1286
|
+
if (indexedStat.isFile()) workspaceBytes += indexedStat.size;
|
|
1287
|
+
} catch {}
|
|
1288
|
+
}
|
|
1289
|
+
if (workspaceBytes + stat.size > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1290
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1291
|
+
this.removeIndexedFile(relPath);
|
|
1292
|
+
this.dirtyFiles.delete(relPath);
|
|
1293
|
+
this.scheduleDebouncedSave();
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
const descriptor = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
1297
|
+
let opened: fs.Stats;
|
|
1298
|
+
try {
|
|
1299
|
+
opened = fs.fstatSync(descriptor);
|
|
1300
|
+
if (!opened.isFile() || opened.size > MAX_INDEX_FILE_BYTES) throw new Error(`Invalid workspace file: ${relPath}`);
|
|
1301
|
+
content = readDescriptorBounded(descriptor, MAX_INDEX_FILE_BYTES).toString("utf8");
|
|
1302
|
+
} finally {
|
|
1303
|
+
fs.closeSync(descriptor);
|
|
1304
|
+
}
|
|
1305
|
+
const afterRead = fs.statSync(resolvedPath);
|
|
1306
|
+
if (!sameFileSnapshot(opened, afterRead)) {
|
|
1307
|
+
throw new Error(`Workspace file changed while reading: ${relPath}`);
|
|
1308
|
+
}
|
|
1309
|
+
if (Buffer.byteLength(content, "utf8") > MAX_INDEX_FILE_BYTES) {
|
|
1310
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1311
|
+
this.removeIndexedFile(relPath);
|
|
1312
|
+
this.dirtyFiles.delete(relPath);
|
|
1313
|
+
this.scheduleDebouncedSave();
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
} catch (err: any) {
|
|
1317
|
+
if (err?.code === "ENOENT") {
|
|
1318
|
+
// File was removed concurrently between existsSync and readFileSync
|
|
1319
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1320
|
+
this.bm25.removeFile(relPath);
|
|
1321
|
+
this.fileHashes.delete(relPath);
|
|
1322
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
1323
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1324
|
+
this.chunks.delete(chunkId);
|
|
1325
|
+
this.vectors.delete(chunkId);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
this.dirtyFiles.delete(relPath);
|
|
1329
|
+
this.bm25.recalculateStats();
|
|
1330
|
+
this.scheduleDebouncedSave();
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
kernelDebug(`Failed reading ${resolvedPath} for updateFile: ${err}`);
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
const fileHash = computeHash(content);
|
|
1338
|
+
const wantsVectors =
|
|
1339
|
+
this.config.effectiveProfile === "hybrid" ||
|
|
1340
|
+
this.config.effectiveProfile === "full";
|
|
1341
|
+
const fileChunks = Array.from(this.chunks.values()).filter((chunk) => chunk.filePath === relPath);
|
|
1342
|
+
const fileVectorsReady = !wantsVectors || fileChunks.every((chunk) => {
|
|
1343
|
+
const vector = this.vectors.get(chunk.id);
|
|
1344
|
+
return !!vector && vector.length === this.config.matryoshkaDim;
|
|
1345
|
+
});
|
|
1346
|
+
if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath) && fileVectorsReady) {
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// Ensure TreeSitter parser for this file's language is loaded
|
|
1351
|
+
const ext = path.extname(resolvedPath).toLowerCase();
|
|
1352
|
+
if (ext) {
|
|
1353
|
+
try {
|
|
1354
|
+
await TreeSitterEngine.getInstance().loadLanguages([ext]);
|
|
1355
|
+
} catch (e) {
|
|
1356
|
+
kernelDebug(e);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
const newChunks = chunkFile(this.cwd, resolvedPath, content);
|
|
1361
|
+
const currentChunksForFile = Array.from(this.chunks.keys()).filter((id) => id.startsWith(`${relPath}:`)).length;
|
|
1362
|
+
if (this.chunks.size - currentChunksForFile + newChunks.length > MAX_INDEX_CHUNKS) {
|
|
1363
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1364
|
+
this.removeIndexedFile(relPath);
|
|
1365
|
+
this.dirtyFiles.delete(relPath);
|
|
1366
|
+
this.scheduleDebouncedSave();
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
this.skippedOversizedFiles.delete(relPath);
|
|
1370
|
+
// Map content hash -> vector from existing chunks
|
|
1371
|
+
const hashToVector = new Map<string, Float32Array>();
|
|
1372
|
+
for (const chunk of this.chunks.values()) {
|
|
1373
|
+
const vec = this.vectors.get(chunk.id);
|
|
1374
|
+
if (vec && vec.length === this.config.matryoshkaDim) {
|
|
1375
|
+
hashToVector.set(chunk.hash, vec);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
const newVectors = new Map<string, Float32Array>();
|
|
1380
|
+
const missingChunks: CodeChunk[] = [];
|
|
1381
|
+
|
|
1382
|
+
for (const chunk of newChunks) {
|
|
1383
|
+
const reused = hashToVector.get(chunk.hash);
|
|
1384
|
+
if (reused) {
|
|
1385
|
+
newVectors.set(chunk.id, reused);
|
|
1386
|
+
} else if (wantsVectors) {
|
|
1387
|
+
missingChunks.push(chunk);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
// Embed missing chunks off to the side
|
|
1392
|
+
if (wantsVectors && missingChunks.length > 0) {
|
|
1393
|
+
const batchSize = this.config.batchSize || 2;
|
|
1394
|
+
const texts = missingChunks.map((c) => c.textForEmbedding);
|
|
1395
|
+
for (let i = 0; i < missingChunks.length; i += batchSize) {
|
|
1396
|
+
// Check generation before each batch
|
|
1397
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1398
|
+
const batchChunks = missingChunks.slice(i, i + batchSize);
|
|
1399
|
+
const batchTexts = texts.slice(i, i + batchSize);
|
|
1400
|
+
const vecs = await this.embedder.embedBatch(batchTexts, false);
|
|
1401
|
+
for (let j = 0; j < batchChunks.length; j++) {
|
|
1402
|
+
const vector = vecs[j];
|
|
1403
|
+
if (vector && vector.length === this.config.matryoshkaDim && Array.from(vector).every(Number.isFinite)) {
|
|
1404
|
+
newVectors.set(batchChunks[j].id, vector);
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// Generation check: if a newer update started, discard this older result
|
|
1411
|
+
if (this.fileGenerations.get(relPath) !== currentGen) {
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// Atomic in-memory swap:
|
|
1416
|
+
this.bm25.removeFile(relPath);
|
|
1417
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
1418
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1419
|
+
this.chunks.delete(chunkId);
|
|
1420
|
+
this.vectors.delete(chunkId);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
this.fileHashes.set(relPath, fileHash);
|
|
1425
|
+
for (const chunk of newChunks) {
|
|
1426
|
+
this.chunks.set(chunk.id, chunk);
|
|
1427
|
+
this.bm25.addChunk(chunk);
|
|
1428
|
+
const vec = newVectors.get(chunk.id);
|
|
1429
|
+
if (vec) {
|
|
1430
|
+
this.vectors.set(chunk.id, vec);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
this.bm25.recalculateStats();
|
|
1434
|
+
this.dirtyFiles.delete(relPath);
|
|
1435
|
+
if (this.dirtyFiles.size === 0) {
|
|
1436
|
+
this.isInitialized = true;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
this.scheduleDebouncedSave();
|
|
1440
|
+
})();
|
|
1441
|
+
|
|
1442
|
+
this.activeFileUpdates.set(relPath, task);
|
|
1443
|
+
try {
|
|
1444
|
+
await task;
|
|
1445
|
+
} finally {
|
|
1446
|
+
if (this.activeFileUpdates.get(relPath) === task) {
|
|
1447
|
+
this.activeFileUpdates.delete(relPath);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
|
|
654
1452
|
/**
|
|
655
1453
|
* Drop cached chunks for a file; the next search performs an incremental rescan.
|
|
656
1454
|
*/
|
|
@@ -692,32 +1490,31 @@ export class HybridSearchIndex {
|
|
|
692
1490
|
profile?: SearchProfile;
|
|
693
1491
|
/** Bounded RRF smoothing constant; defaults to 60. */
|
|
694
1492
|
rrfK?: number;
|
|
695
|
-
/** Search scope. Code is the default; all/prose are explicit opt-ins. */
|
|
696
|
-
scope?: "code" | "all" | "prose";
|
|
697
1493
|
} = {},
|
|
698
1494
|
): Promise<SearchHit[]> {
|
|
1495
|
+
if (this.config.effectiveProfile === "off") {
|
|
1496
|
+
return [];
|
|
1497
|
+
}
|
|
699
1498
|
// Do not return the previous snapshot while a background synchronization
|
|
700
1499
|
// is active. This also covers startup/reindex work where the old index is
|
|
701
1500
|
// still initialized and would otherwise look usable.
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
if (
|
|
1501
|
+
for (;;) {
|
|
1502
|
+
await this.waitForActiveSync();
|
|
1503
|
+
if (this.activeFileUpdates.size > 0) {
|
|
1504
|
+
await Promise.all(Array.from(this.activeFileUpdates.values()));
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
if (this.dirtyFiles.size > 0 || !this.isInitialized) {
|
|
705
1508
|
await this.syncWorkspace(false);
|
|
1509
|
+
continue;
|
|
706
1510
|
}
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
if (this.isInitialized && !this.isIndexing) {
|
|
710
1511
|
await this.ensureWorkspaceSnapshotFresh();
|
|
1512
|
+
if (!this.isInitialized || this.isIndexing || this.activeSync || this.dirtyFiles.size > 0) continue;
|
|
1513
|
+
break;
|
|
711
1514
|
}
|
|
712
1515
|
|
|
713
1516
|
const limit = options.limit || 5;
|
|
714
1517
|
const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
|
|
715
|
-
const scope = options.scope ?? "code";
|
|
716
|
-
const isProsePath = isProseFilePath;
|
|
717
|
-
const matchesScope = (chunk: CodeChunk): boolean => {
|
|
718
|
-
const isProse = isProsePath(chunk.filePath);
|
|
719
|
-
return scope === "all" || (scope === "prose" ? isProse : !isProse);
|
|
720
|
-
};
|
|
721
1518
|
const matchesFilePattern = (chunk: CodeChunk): boolean =>
|
|
722
1519
|
!options.filePattern ||
|
|
723
1520
|
chunk.filePath
|
|
@@ -725,13 +1522,13 @@ export class HybridSearchIndex {
|
|
|
725
1522
|
.toLowerCase()
|
|
726
1523
|
.includes(options.filePattern.replace(/\\/g, "/").toLowerCase());
|
|
727
1524
|
const activeConfig = options.profile
|
|
728
|
-
? getSearchConfig(options.profile)
|
|
1525
|
+
? getSearchConfig(options.profile, this.cwd, this.projectTrusted)
|
|
729
1526
|
: this.config;
|
|
730
1527
|
|
|
731
1528
|
// 1. BM25 Search (Instant AST-tokenized lexical retrieval)
|
|
732
1529
|
const bm25Results = this.bm25.search(query, 100, (chunkId) => {
|
|
733
1530
|
const chunk = this.chunks.get(chunkId);
|
|
734
|
-
return !!chunk &&
|
|
1531
|
+
return !!chunk && matchesFilePattern(chunk);
|
|
735
1532
|
});
|
|
736
1533
|
const bm25RankMap = new Map<
|
|
737
1534
|
string,
|
|
@@ -765,7 +1562,7 @@ export class HybridSearchIndex {
|
|
|
765
1562
|
const vecScores: { chunkId: string; score: number }[] = [];
|
|
766
1563
|
for (const [chunkId, vec] of this.vectors.entries()) {
|
|
767
1564
|
const chunk = this.chunks.get(chunkId);
|
|
768
|
-
if (!chunk || !
|
|
1565
|
+
if (!chunk || !matchesFilePattern(chunk)) continue;
|
|
769
1566
|
const score = LocalEmbedder.cosineSimilarity(queryVec, vec);
|
|
770
1567
|
vecScores.push({ chunkId, score });
|
|
771
1568
|
}
|
|
@@ -830,6 +1627,7 @@ export class HybridSearchIndex {
|
|
|
830
1627
|
profile: SearchProfile;
|
|
831
1628
|
effectiveProfile: "lean" | "hybrid" | "full" | "off";
|
|
832
1629
|
fileCount: number;
|
|
1630
|
+
skippedFiles: number;
|
|
833
1631
|
chunkCount: number;
|
|
834
1632
|
vectorCount: number;
|
|
835
1633
|
isModelLoaded: boolean;
|
|
@@ -840,6 +1638,7 @@ export class HybridSearchIndex {
|
|
|
840
1638
|
pipelineDesc: string;
|
|
841
1639
|
hardwareInfo: string;
|
|
842
1640
|
} {
|
|
1641
|
+
const modelRevision = this.config.modelRevision.slice(0, 12);
|
|
843
1642
|
const isModelLoaded = this.embedder.isLoaded();
|
|
844
1643
|
const isModelCached = this.embedder.isCachedOnDisk();
|
|
845
1644
|
let modelStatus = "";
|
|
@@ -853,20 +1652,20 @@ export class HybridSearchIndex {
|
|
|
853
1652
|
pipelineDesc = "AST-tokenized BM25 Lexical Retrieval";
|
|
854
1653
|
} else if (this.config.effectiveProfile === "hybrid") {
|
|
855
1654
|
if (isModelLoaded) {
|
|
856
|
-
modelStatus =
|
|
1655
|
+
modelStatus = `Active in RAM (Nomic v1.5 Matryoshka 256-dim, rev ${modelRevision})`;
|
|
857
1656
|
} else if (isModelCached) {
|
|
858
|
-
modelStatus =
|
|
1657
|
+
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
859
1658
|
} else {
|
|
860
|
-
modelStatus =
|
|
1659
|
+
modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
|
|
861
1660
|
}
|
|
862
1661
|
pipelineDesc = "Hybrid BM25 + 256-dim Matryoshka Vector Search";
|
|
863
1662
|
} else {
|
|
864
1663
|
if (isModelLoaded) {
|
|
865
|
-
modelStatus =
|
|
1664
|
+
modelStatus = `Active in RAM (Nomic v1.5 768-dim, rev ${modelRevision})`;
|
|
866
1665
|
} else if (isModelCached) {
|
|
867
|
-
modelStatus =
|
|
1666
|
+
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
868
1667
|
} else {
|
|
869
|
-
modelStatus =
|
|
1668
|
+
modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
|
|
870
1669
|
}
|
|
871
1670
|
pipelineDesc = "Full BM25 + 768-dim Semantic Vector Search";
|
|
872
1671
|
}
|
|
@@ -888,6 +1687,7 @@ export class HybridSearchIndex {
|
|
|
888
1687
|
profile: this.config.profile,
|
|
889
1688
|
effectiveProfile: this.config.effectiveProfile,
|
|
890
1689
|
fileCount: this.fileHashes.size,
|
|
1690
|
+
skippedFiles: this.skippedOversizedFiles.size,
|
|
891
1691
|
chunkCount: this.chunks.size,
|
|
892
1692
|
vectorCount: this.vectors.size,
|
|
893
1693
|
isModelLoaded,
|