@floydous/pi-agent-kernel 0.4.0 → 0.4.2
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 +8 -4
- package/CHANGELOG.md +40 -87
- package/README.md +39 -74
- package/config.example.toml +1 -1
- package/docs/retrieval.md +2 -0
- package/package.json +7 -6
- package/src/config/agent_kernel_command.ts +29 -14
- package/src/config/kernel_config.ts +175 -30
- package/src/context/session_repair.ts +166 -85
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +13 -29
- package/src/editing/syntax-verify.ts +35 -11
- package/src/index.ts +161 -141
- package/src/lsp/lsp_client.ts +101 -20
- package/src/lsp/lsp_formatter.ts +57 -22
- package/src/lsp/lsp_installer.ts +272 -487
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +75 -46
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +12 -9
- package/src/retrieval/search_config.ts +20 -8
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +552 -121
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +440 -67
- package/src/safety/output_clamper.ts +316 -76
- 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 +114 -36
- package/src/tools/lsp_tool.ts +5 -2
- package/src/tools/read_tool.ts +44 -3
|
@@ -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";
|
|
@@ -19,8 +22,13 @@ import {
|
|
|
19
22
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
20
23
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
21
24
|
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
25
|
+
import { getSearchCacheDir } from "./search_cache";
|
|
26
|
+
export { getSearchCacheDir } from "./search_cache";
|
|
22
27
|
|
|
23
|
-
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;
|
|
24
32
|
const EXTRACTOR_GENERATION = "tree-sitter-wasm-v2";
|
|
25
33
|
|
|
26
34
|
interface PersistedVectorCache {
|
|
@@ -31,6 +39,274 @@ interface PersistedVectorCache {
|
|
|
31
39
|
fileName: string;
|
|
32
40
|
}
|
|
33
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
|
+
|
|
34
310
|
export interface SearchHit {
|
|
35
311
|
chunk: CodeChunk;
|
|
36
312
|
rrfScore: number;
|
|
@@ -67,10 +343,17 @@ export class HybridSearchIndex {
|
|
|
67
343
|
private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
|
|
68
344
|
private liveCheckPromise: Promise<boolean> | null = null;
|
|
69
345
|
private persistedVectorCaches: PersistedVectorCache[] = [];
|
|
70
|
-
|
|
71
|
-
|
|
346
|
+
private skippedOversizedFiles = new Set<string>();
|
|
347
|
+
private projectTrusted: boolean;
|
|
348
|
+
|
|
349
|
+
constructor(
|
|
350
|
+
cwd: string,
|
|
351
|
+
profile?: SearchProfile,
|
|
352
|
+
options: { projectTrusted?: boolean } = {},
|
|
353
|
+
) {
|
|
72
354
|
this.cwd = cwd;
|
|
73
|
-
this.
|
|
355
|
+
this.projectTrusted = options.projectTrusted === true;
|
|
356
|
+
this.config = getSearchConfig(profile, cwd, this.projectTrusted);
|
|
74
357
|
this.embedder = new LocalEmbedder(this.config);
|
|
75
358
|
this.loadFromDisk();
|
|
76
359
|
}
|
|
@@ -86,7 +369,7 @@ export class HybridSearchIndex {
|
|
|
86
369
|
public setProfile(profile: SearchProfile): void {
|
|
87
370
|
const oldEffective = this.config.effectiveProfile;
|
|
88
371
|
const oldProfile = this.config.profile;
|
|
89
|
-
this.config = getSearchConfig(profile, this.cwd);
|
|
372
|
+
this.config = getSearchConfig(profile, this.cwd, this.projectTrusted);
|
|
90
373
|
this.embedder.updateConfig(this.config);
|
|
91
374
|
|
|
92
375
|
if (oldProfile !== this.config.profile || oldEffective !== this.config.effectiveProfile) {
|
|
@@ -140,7 +423,7 @@ export class HybridSearchIndex {
|
|
|
140
423
|
}
|
|
141
424
|
|
|
142
425
|
private getCacheDir(): string {
|
|
143
|
-
return
|
|
426
|
+
return getSearchCacheDir(this.cwd);
|
|
144
427
|
}
|
|
145
428
|
|
|
146
429
|
private getIndexFilePath(): string {
|
|
@@ -161,19 +444,32 @@ export class HybridSearchIndex {
|
|
|
161
444
|
(cache: any): cache is PersistedVectorCache =>
|
|
162
445
|
cache &&
|
|
163
446
|
Number.isInteger(cache.vectorDim) &&
|
|
164
|
-
cache.vectorDim
|
|
165
|
-
|
|
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 &&
|
|
166
456
|
typeof cache.vectorHash === "string" &&
|
|
457
|
+
/^[0-9a-f]{64}$/i.test(cache.vectorHash) &&
|
|
167
458
|
typeof cache.fileName === "string" &&
|
|
168
|
-
|
|
459
|
+
(cache.fileName === "vectors.bin" || cache.fileName === `vectors-${cache.vectorDim}d.bin`),
|
|
169
460
|
);
|
|
170
461
|
}
|
|
171
462
|
|
|
172
463
|
if (
|
|
173
464
|
Number.isInteger(data.vectorDim) &&
|
|
174
|
-
data.vectorDim
|
|
465
|
+
(data.vectorDim === 256 || data.vectorDim === 768) &&
|
|
175
466
|
Array.isArray(data.vectorChunkIds) &&
|
|
176
|
-
|
|
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)
|
|
177
473
|
) {
|
|
178
474
|
return [{
|
|
179
475
|
vectorDim: data.vectorDim,
|
|
@@ -193,7 +489,11 @@ export class HybridSearchIndex {
|
|
|
193
489
|
);
|
|
194
490
|
}
|
|
195
491
|
|
|
196
|
-
private loadVectorCache(
|
|
492
|
+
private loadVectorCache(
|
|
493
|
+
cache: PersistedVectorCache,
|
|
494
|
+
persistedChunkHashes: Map<string, string>,
|
|
495
|
+
allowUnhashedVectors = false,
|
|
496
|
+
): void {
|
|
197
497
|
const vectorChunkIds = cache.vectorChunkIds;
|
|
198
498
|
const vectorPath = this.getVectorsFilePath(cache.fileName);
|
|
199
499
|
if (
|
|
@@ -202,8 +502,18 @@ export class HybridSearchIndex {
|
|
|
202
502
|
new Set(vectorChunkIds).size !== vectorChunkIds.length
|
|
203
503
|
) return;
|
|
204
504
|
|
|
205
|
-
const buffer = fs.readFileSync(vectorPath);
|
|
206
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
|
+
}
|
|
207
517
|
if (
|
|
208
518
|
buffer.byteLength !== expectedBytes ||
|
|
209
519
|
cache.vectorHash !==
|
|
@@ -219,25 +529,27 @@ export class HybridSearchIndex {
|
|
|
219
529
|
Array.isArray(cache.vectorChunkHashes) &&
|
|
220
530
|
cache.vectorChunkHashes.length === vectorChunkIds.length;
|
|
221
531
|
if (Array.isArray(cache.vectorChunkHashes) && !hasChunkHashes) return;
|
|
222
|
-
if (!hasChunkHashes &&
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
) return;
|
|
228
|
-
|
|
532
|
+
if (!hasChunkHashes && (
|
|
533
|
+
!allowUnhashedVectors ||
|
|
534
|
+
vectorChunkIds.length !== this.chunks.size ||
|
|
535
|
+
vectorChunkIds.some((id) => !this.chunks.has(id)) ||
|
|
536
|
+
!this.isWorkspaceSnapshotFresh()
|
|
537
|
+
)) return;
|
|
229
538
|
const floatArray = new Float32Array(
|
|
230
539
|
buffer.buffer,
|
|
231
540
|
buffer.byteOffset,
|
|
232
541
|
buffer.byteLength / 4,
|
|
233
542
|
);
|
|
543
|
+
for (const value of floatArray) {
|
|
544
|
+
if (!Number.isFinite(value)) return;
|
|
545
|
+
}
|
|
234
546
|
for (let index = 0; index < vectorChunkIds.length; index++) {
|
|
235
547
|
const chunkId = vectorChunkIds[index];
|
|
236
548
|
if (!this.chunks.has(chunkId)) continue;
|
|
237
|
-
if (
|
|
238
|
-
|
|
549
|
+
if (hasChunkHashes && (
|
|
550
|
+
cache.vectorChunkHashes?.[index] !== persistedChunkHashes.get(chunkId) ||
|
|
239
551
|
cache.vectorChunkHashes?.[index] !== currentHashes.get(chunkId)
|
|
240
|
-
) continue;
|
|
552
|
+
)) continue;
|
|
241
553
|
const vector = new Float32Array(cache.vectorDim);
|
|
242
554
|
vector.set(
|
|
243
555
|
floatArray.subarray(
|
|
@@ -258,50 +570,45 @@ export class HybridSearchIndex {
|
|
|
258
570
|
if (!fs.existsSync(indexPath)) return false;
|
|
259
571
|
|
|
260
572
|
try {
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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);
|
|
269
587
|
}
|
|
588
|
+
const persistedVectorCaches = this.getPersistedVectorCaches(data).filter((cache) =>
|
|
589
|
+
cache.vectorChunkIds.every((id) => validated.chunkFiles.has(id)),
|
|
590
|
+
);
|
|
270
591
|
|
|
271
592
|
this.chunks.clear();
|
|
272
593
|
this.bm25.clear();
|
|
273
594
|
this.fileHashes.clear();
|
|
595
|
+
this.ignoreConfigHashes.clear();
|
|
274
596
|
this.vectors.clear();
|
|
275
597
|
this.persistedVectorCaches = [];
|
|
276
598
|
|
|
277
|
-
for (const chunk of
|
|
278
|
-
// Normalize chunk.filePath alias if chunk was serialized with file
|
|
279
|
-
if (!chunk.filePath && (chunk as any).file) {
|
|
280
|
-
chunk.filePath = (chunk as any).file;
|
|
281
|
-
}
|
|
282
|
-
// Rebase absolutePath to the current workspace root if paths differ
|
|
283
|
-
if (chunk.filePath && this.cwd) {
|
|
284
|
-
chunk.absolutePath = path.resolve(this.cwd, chunk.filePath);
|
|
285
|
-
}
|
|
599
|
+
for (const chunk of validated.chunks) {
|
|
286
600
|
this.chunks.set(chunk.id, chunk);
|
|
287
601
|
this.bm25.addChunk(chunk);
|
|
288
602
|
}
|
|
289
603
|
this.bm25.recalculateStats();
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
this.fileHashes.set(f, h as string);
|
|
604
|
+
for (const [file, hash] of validated.fileHashes) {
|
|
605
|
+
this.fileHashes.set(file, hash);
|
|
293
606
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
if (data.ignoreConfigHashes && typeof data.ignoreConfigHashes === "object") {
|
|
297
|
-
for (const [f, h] of Object.entries(data.ignoreConfigHashes)) {
|
|
298
|
-
if (typeof h === "string") {
|
|
299
|
-
this.ignoreConfigHashes.set(f, h);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
607
|
+
for (const [file, hash] of validated.ignoreConfigHashes) {
|
|
608
|
+
this.ignoreConfigHashes.set(file, hash);
|
|
302
609
|
}
|
|
303
610
|
|
|
304
|
-
this.persistedVectorCaches =
|
|
611
|
+
this.persistedVectorCaches = persistedVectorCaches;
|
|
305
612
|
const wantsVectors =
|
|
306
613
|
this.config.effectiveProfile === "hybrid" ||
|
|
307
614
|
this.config.effectiveProfile === "full";
|
|
@@ -309,7 +616,16 @@ export class HybridSearchIndex {
|
|
|
309
616
|
(cache) => cache.vectorDim === this.config.matryoshkaDim,
|
|
310
617
|
);
|
|
311
618
|
if (wantsVectors && activeCache) {
|
|
312
|
-
|
|
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
|
+
}
|
|
313
629
|
}
|
|
314
630
|
|
|
315
631
|
const vectorsReady =
|
|
@@ -319,9 +635,10 @@ export class HybridSearchIndex {
|
|
|
319
635
|
Array.from(this.vectors.values()).every(
|
|
320
636
|
(vector) => vector.length === this.config.matryoshkaDim,
|
|
321
637
|
));
|
|
322
|
-
this.isInitialized = vectorsReady;
|
|
638
|
+
this.isInitialized = vectorsReady && validated.staleFiles.size === 0;
|
|
323
639
|
return true;
|
|
324
|
-
} catch {
|
|
640
|
+
} catch (error) {
|
|
641
|
+
kernelDebug(error);
|
|
325
642
|
return false;
|
|
326
643
|
}
|
|
327
644
|
}
|
|
@@ -332,19 +649,6 @@ export class HybridSearchIndex {
|
|
|
332
649
|
public saveToDisk(): void {
|
|
333
650
|
try {
|
|
334
651
|
const cacheDir = this.getCacheDir();
|
|
335
|
-
if (!fs.existsSync(cacheDir)) {
|
|
336
|
-
fs.mkdirSync(cacheDir, { recursive: true });
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
// Ensure .gitignore exists in .pi/cache
|
|
340
|
-
const gitignorePath = path.join(this.cwd, ".pi", "cache", ".gitignore");
|
|
341
|
-
if (!fs.existsSync(gitignorePath)) {
|
|
342
|
-
try {
|
|
343
|
-
fs.writeFileSync(gitignorePath, "*\n!.gitignore\n", "utf-8");
|
|
344
|
-
} catch (e) {
|
|
345
|
-
kernelDebug(e);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
652
|
|
|
349
653
|
const chunkList = Array.from(this.chunks.values());
|
|
350
654
|
const fileHashesObj: Record<string, string> = {};
|
|
@@ -382,6 +686,7 @@ export class HybridSearchIndex {
|
|
|
382
686
|
const vectorChunkHashes = vectorChunkIds.map(
|
|
383
687
|
(id) => this.chunks.get(id)?.hash || "",
|
|
384
688
|
);
|
|
689
|
+
if (vectorChunkHashes.some((hash) => !hash)) return;
|
|
385
690
|
const fileName = this.getVectorCacheFileName(vectorDim);
|
|
386
691
|
vectorCaches.set(vectorDim, {
|
|
387
692
|
vectorDim,
|
|
@@ -564,10 +869,33 @@ export class HybridSearchIndex {
|
|
|
564
869
|
|
|
565
870
|
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
566
871
|
const hashes = new Map<string, string>();
|
|
567
|
-
|
|
872
|
+
let workspaceBytes = 0;
|
|
873
|
+
const files = findChunkableFiles(this.cwd).sort();
|
|
874
|
+
for (const filePath of files) {
|
|
568
875
|
const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
|
|
569
876
|
try {
|
|
570
|
-
|
|
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));
|
|
571
899
|
} catch (error) {
|
|
572
900
|
kernelDebug(error);
|
|
573
901
|
return null;
|
|
@@ -656,7 +984,8 @@ export class HybridSearchIndex {
|
|
|
656
984
|
onProgress?.("Scanning workspace files...");
|
|
657
985
|
|
|
658
986
|
// Ensure Tree-sitter parsers are warm for languages present in this workspace
|
|
659
|
-
const chunkableFiles = findChunkableFiles(this.cwd);
|
|
987
|
+
const chunkableFiles = findChunkableFiles(this.cwd).sort();
|
|
988
|
+
this.skippedOversizedFiles.clear();
|
|
660
989
|
const workspaceExts = new Set<string>();
|
|
661
990
|
for (const f of chunkableFiles) {
|
|
662
991
|
const ext = path.extname(f).toLowerCase();
|
|
@@ -667,18 +996,48 @@ export class HybridSearchIndex {
|
|
|
667
996
|
// Read each file once and derive both its chunks and hash from that same
|
|
668
997
|
// snapshot. A second read could pair old chunks with a new hash and make
|
|
669
998
|
// the final freshness check falsely accept stale content.
|
|
670
|
-
const currentFiles = new Map<
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
>();
|
|
999
|
+
const currentFiles = new Map<string, { hash: string; chunks: CodeChunk[] }>();
|
|
1000
|
+
let workspaceBytes = 0;
|
|
1001
|
+
let workspaceChunks = 0;
|
|
674
1002
|
for (const absPath of chunkableFiles) {
|
|
675
1003
|
const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
|
|
676
1004
|
try {
|
|
677
|
-
const
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
}
|
|
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 });
|
|
682
1041
|
} catch (error) {
|
|
683
1042
|
kernelDebug(error);
|
|
684
1043
|
}
|
|
@@ -698,7 +1057,7 @@ export class HybridSearchIndex {
|
|
|
698
1057
|
const vector = this.vectors.get(chunk.id);
|
|
699
1058
|
return !vector || vector.length !== this.config.matryoshkaDim;
|
|
700
1059
|
});
|
|
701
|
-
if (forceReindex ||
|
|
1060
|
+
if (forceReindex || !oldHash || oldHash !== info.hash || missingFileVectors) {
|
|
702
1061
|
filesToReindex.push(relPath);
|
|
703
1062
|
}
|
|
704
1063
|
}
|
|
@@ -782,9 +1141,11 @@ export class HybridSearchIndex {
|
|
|
782
1141
|
}
|
|
783
1142
|
|
|
784
1143
|
for (let j = 0; j < batch.length; j++) {
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
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);
|
|
788
1149
|
}
|
|
789
1150
|
|
|
790
1151
|
// Async sleep to yield CPU and prevent freezing system daemons
|
|
@@ -839,6 +1200,17 @@ export class HybridSearchIndex {
|
|
|
839
1200
|
}
|
|
840
1201
|
}
|
|
841
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
|
+
|
|
842
1214
|
/**
|
|
843
1215
|
* Transactional incremental update of a single file in the index.
|
|
844
1216
|
* Chunks only this file, reuses existing vectors for unchanged chunks by content hash,
|
|
@@ -864,6 +1236,14 @@ export class HybridSearchIndex {
|
|
|
864
1236
|
return;
|
|
865
1237
|
}
|
|
866
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
|
+
|
|
867
1247
|
const currentGen = (this.fileGenerations.get(relPath) ?? 0) + 1;
|
|
868
1248
|
this.fileGenerations.set(relPath, currentGen);
|
|
869
1249
|
|
|
@@ -887,10 +1267,52 @@ export class HybridSearchIndex {
|
|
|
887
1267
|
return;
|
|
888
1268
|
}
|
|
889
1269
|
|
|
890
|
-
// Read file content with TOCTOU protection
|
|
1270
|
+
// Read file content with bounded allocation and TOCTOU protection
|
|
891
1271
|
let content: string;
|
|
892
1272
|
try {
|
|
893
|
-
|
|
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
|
+
}
|
|
894
1316
|
} catch (err: any) {
|
|
895
1317
|
if (err?.code === "ENOENT") {
|
|
896
1318
|
// File was removed concurrently between existsSync and readFileSync
|
|
@@ -913,8 +1335,15 @@ export class HybridSearchIndex {
|
|
|
913
1335
|
}
|
|
914
1336
|
|
|
915
1337
|
const fileHash = computeHash(content);
|
|
916
|
-
|
|
917
|
-
|
|
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) {
|
|
918
1347
|
return;
|
|
919
1348
|
}
|
|
920
1349
|
|
|
@@ -929,10 +1358,15 @@ export class HybridSearchIndex {
|
|
|
929
1358
|
}
|
|
930
1359
|
|
|
931
1360
|
const newChunks = chunkFile(this.cwd, resolvedPath, content);
|
|
932
|
-
const
|
|
933
|
-
|
|
934
|
-
this.
|
|
935
|
-
|
|
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);
|
|
936
1370
|
// Map content hash -> vector from existing chunks
|
|
937
1371
|
const hashToVector = new Map<string, Float32Array>();
|
|
938
1372
|
for (const chunk of this.chunks.values()) {
|
|
@@ -965,8 +1399,9 @@ export class HybridSearchIndex {
|
|
|
965
1399
|
const batchTexts = texts.slice(i, i + batchSize);
|
|
966
1400
|
const vecs = await this.embedder.embedBatch(batchTexts, false);
|
|
967
1401
|
for (let j = 0; j < batchChunks.length; j++) {
|
|
968
|
-
|
|
969
|
-
|
|
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);
|
|
970
1405
|
}
|
|
971
1406
|
}
|
|
972
1407
|
}
|
|
@@ -1055,8 +1490,6 @@ export class HybridSearchIndex {
|
|
|
1055
1490
|
profile?: SearchProfile;
|
|
1056
1491
|
/** Bounded RRF smoothing constant; defaults to 60. */
|
|
1057
1492
|
rrfK?: number;
|
|
1058
|
-
/** Search scope. Code is the default; all/prose are explicit opt-ins. */
|
|
1059
|
-
scope?: "code" | "all" | "prose";
|
|
1060
1493
|
} = {},
|
|
1061
1494
|
): Promise<SearchHit[]> {
|
|
1062
1495
|
if (this.config.effectiveProfile === "off") {
|
|
@@ -1065,28 +1498,23 @@ export class HybridSearchIndex {
|
|
|
1065
1498
|
// Do not return the previous snapshot while a background synchronization
|
|
1066
1499
|
// is active. This also covers startup/reindex work where the old index is
|
|
1067
1500
|
// still initialized and would otherwise look usable.
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
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) {
|
|
1074
1508
|
await this.syncWorkspace(false);
|
|
1509
|
+
continue;
|
|
1075
1510
|
}
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
if (this.isInitialized && !this.isIndexing) {
|
|
1079
1511
|
await this.ensureWorkspaceSnapshotFresh();
|
|
1512
|
+
if (!this.isInitialized || this.isIndexing || this.activeSync || this.dirtyFiles.size > 0) continue;
|
|
1513
|
+
break;
|
|
1080
1514
|
}
|
|
1081
1515
|
|
|
1082
1516
|
const limit = options.limit || 5;
|
|
1083
1517
|
const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
|
|
1084
|
-
const scope = options.scope ?? "code";
|
|
1085
|
-
const isProsePath = isProseFilePath;
|
|
1086
|
-
const matchesScope = (chunk: CodeChunk): boolean => {
|
|
1087
|
-
const isProse = isProsePath(chunk.filePath);
|
|
1088
|
-
return scope === "all" || (scope === "prose" ? isProse : !isProse);
|
|
1089
|
-
};
|
|
1090
1518
|
const matchesFilePattern = (chunk: CodeChunk): boolean =>
|
|
1091
1519
|
!options.filePattern ||
|
|
1092
1520
|
chunk.filePath
|
|
@@ -1094,13 +1522,13 @@ export class HybridSearchIndex {
|
|
|
1094
1522
|
.toLowerCase()
|
|
1095
1523
|
.includes(options.filePattern.replace(/\\/g, "/").toLowerCase());
|
|
1096
1524
|
const activeConfig = options.profile
|
|
1097
|
-
? getSearchConfig(options.profile)
|
|
1525
|
+
? getSearchConfig(options.profile, this.cwd, this.projectTrusted)
|
|
1098
1526
|
: this.config;
|
|
1099
1527
|
|
|
1100
1528
|
// 1. BM25 Search (Instant AST-tokenized lexical retrieval)
|
|
1101
1529
|
const bm25Results = this.bm25.search(query, 100, (chunkId) => {
|
|
1102
1530
|
const chunk = this.chunks.get(chunkId);
|
|
1103
|
-
return !!chunk &&
|
|
1531
|
+
return !!chunk && matchesFilePattern(chunk);
|
|
1104
1532
|
});
|
|
1105
1533
|
const bm25RankMap = new Map<
|
|
1106
1534
|
string,
|
|
@@ -1134,7 +1562,7 @@ export class HybridSearchIndex {
|
|
|
1134
1562
|
const vecScores: { chunkId: string; score: number }[] = [];
|
|
1135
1563
|
for (const [chunkId, vec] of this.vectors.entries()) {
|
|
1136
1564
|
const chunk = this.chunks.get(chunkId);
|
|
1137
|
-
if (!chunk || !
|
|
1565
|
+
if (!chunk || !matchesFilePattern(chunk)) continue;
|
|
1138
1566
|
const score = LocalEmbedder.cosineSimilarity(queryVec, vec);
|
|
1139
1567
|
vecScores.push({ chunkId, score });
|
|
1140
1568
|
}
|
|
@@ -1199,6 +1627,7 @@ export class HybridSearchIndex {
|
|
|
1199
1627
|
profile: SearchProfile;
|
|
1200
1628
|
effectiveProfile: "lean" | "hybrid" | "full" | "off";
|
|
1201
1629
|
fileCount: number;
|
|
1630
|
+
skippedFiles: number;
|
|
1202
1631
|
chunkCount: number;
|
|
1203
1632
|
vectorCount: number;
|
|
1204
1633
|
isModelLoaded: boolean;
|
|
@@ -1209,6 +1638,7 @@ export class HybridSearchIndex {
|
|
|
1209
1638
|
pipelineDesc: string;
|
|
1210
1639
|
hardwareInfo: string;
|
|
1211
1640
|
} {
|
|
1641
|
+
const modelRevision = this.config.modelRevision.slice(0, 12);
|
|
1212
1642
|
const isModelLoaded = this.embedder.isLoaded();
|
|
1213
1643
|
const isModelCached = this.embedder.isCachedOnDisk();
|
|
1214
1644
|
let modelStatus = "";
|
|
@@ -1222,20 +1652,20 @@ export class HybridSearchIndex {
|
|
|
1222
1652
|
pipelineDesc = "AST-tokenized BM25 Lexical Retrieval";
|
|
1223
1653
|
} else if (this.config.effectiveProfile === "hybrid") {
|
|
1224
1654
|
if (isModelLoaded) {
|
|
1225
|
-
modelStatus =
|
|
1655
|
+
modelStatus = `Active in RAM (Nomic v1.5 Matryoshka 256-dim, rev ${modelRevision})`;
|
|
1226
1656
|
} else if (isModelCached) {
|
|
1227
|
-
modelStatus =
|
|
1657
|
+
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
1228
1658
|
} else {
|
|
1229
|
-
modelStatus =
|
|
1659
|
+
modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
|
|
1230
1660
|
}
|
|
1231
1661
|
pipelineDesc = "Hybrid BM25 + 256-dim Matryoshka Vector Search";
|
|
1232
1662
|
} else {
|
|
1233
1663
|
if (isModelLoaded) {
|
|
1234
|
-
modelStatus =
|
|
1664
|
+
modelStatus = `Active in RAM (Nomic v1.5 768-dim, rev ${modelRevision})`;
|
|
1235
1665
|
} else if (isModelCached) {
|
|
1236
|
-
modelStatus =
|
|
1666
|
+
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
1237
1667
|
} else {
|
|
1238
|
-
modelStatus =
|
|
1668
|
+
modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
|
|
1239
1669
|
}
|
|
1240
1670
|
pipelineDesc = "Full BM25 + 768-dim Semantic Vector Search";
|
|
1241
1671
|
}
|
|
@@ -1257,6 +1687,7 @@ export class HybridSearchIndex {
|
|
|
1257
1687
|
profile: this.config.profile,
|
|
1258
1688
|
effectiveProfile: this.config.effectiveProfile,
|
|
1259
1689
|
fileCount: this.fileHashes.size,
|
|
1690
|
+
skippedFiles: this.skippedOversizedFiles.size,
|
|
1260
1691
|
chunkCount: this.chunks.size,
|
|
1261
1692
|
vectorCount: this.vectors.size,
|
|
1262
1693
|
isModelLoaded,
|