@floydous/pi-agent-kernel 0.3.1 → 0.3.3

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.
@@ -130,9 +130,9 @@ export function getSearchConfig(
130
130
  profile,
131
131
  effectiveProfile: "hybrid",
132
132
  matryoshkaDim: 256,
133
- // Initial conservative floor from the bounded feedback fixture; larger
134
- // labeled-corpus calibration remains planned.
135
- vectorSimilarityThreshold: 0.6,
133
+ // Empirically calibrated: 0.55 admits natural-language cross-domain queries
134
+ // while cleanly blocking off-topic noise (unrelated queries score ~0.48-0.52).
135
+ vectorSimilarityThreshold: 0.55,
136
136
  numThreads: 1,
137
137
  modelId: "nomic-ai/nomic-embed-text-v1.5",
138
138
  dtype: "q8",
@@ -148,9 +148,8 @@ export function getSearchConfig(
148
148
  profile,
149
149
  effectiveProfile: "full",
150
150
  matryoshkaDim: 768,
151
- // Use the same initial floor until a larger labeled corpus justifies
152
- // profile-specific calibration.
153
- vectorSimilarityThreshold: 0.6,
151
+ // Empirically calibrated floor for 768-dim embeddings.
152
+ vectorSimilarityThreshold: 0.55,
154
153
  numThreads: Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))),
155
154
  modelId: "nomic-ai/nomic-embed-text-v1.5",
156
155
  dtype: "q8",
@@ -24,6 +24,14 @@ import { TreeSitterEngine } from "./tree_sitter_engine";
24
24
  const INDEX_VERSION = 3;
25
25
  const EXTRACTOR_GENERATION = "tree-sitter-wasm-v2";
26
26
 
27
+ interface PersistedVectorCache {
28
+ vectorDim: number;
29
+ vectorChunkIds: string[];
30
+ vectorChunkHashes?: string[];
31
+ vectorHash: string;
32
+ fileName: string;
33
+ }
34
+
27
35
  export interface SearchHit {
28
36
  chunk: CodeChunk;
29
37
  rrfScore: number;
@@ -47,8 +55,9 @@ export class HybridSearchIndex {
47
55
  private isIndexing = false;
48
56
  private dirtyFiles = new Set<string>();
49
57
  private generation = 0;
50
- private activeSync: Promise<{ chunkCount: number; fileCount: number }> | null = null;
58
+ private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
51
59
  private liveCheckPromise: Promise<boolean> | null = null;
60
+ private persistedVectorCaches: PersistedVectorCache[] = [];
52
61
 
53
62
  constructor(cwd: string, profile?: SearchProfile) {
54
63
  this.cwd = cwd;
@@ -66,15 +75,23 @@ export class HybridSearchIndex {
66
75
  }
67
76
 
68
77
  public setProfile(profile: SearchProfile): void {
78
+ const oldEffective = this.config.effectiveProfile;
69
79
  savePersistedProfile(profile);
70
80
  this.config = getSearchConfig(profile);
71
81
  this.embedder.updateConfig(this.config);
82
+
83
+ if (oldEffective !== this.config.effectiveProfile) {
84
+ // Keep vector caches on disk; only the active in-memory representation
85
+ // changes when switching profiles.
86
+ this.vectors.clear();
87
+ this.isInitialized = false;
88
+ }
89
+
72
90
  if (
73
91
  this.config.effectiveProfile === "off" ||
74
92
  this.config.effectiveProfile === "lean"
75
93
  ) {
76
94
  void this.embedder.dispose();
77
- this.vectors.clear();
78
95
  try {
79
96
  if (typeof (global as any).gc === "function") {
80
97
  (global as any).gc();
@@ -108,8 +125,106 @@ export class HybridSearchIndex {
108
125
  return path.join(this.getCacheDir(), "index.json");
109
126
  }
110
127
 
111
- private getVectorsFilePath(): string {
112
- return path.join(this.getCacheDir(), "vectors.bin");
128
+ private getVectorsFilePath(fileName = "vectors.bin"): string {
129
+ return path.join(this.getCacheDir(), fileName);
130
+ }
131
+
132
+ private getVectorCacheFileName(dim: number): string {
133
+ return `vectors-${dim}d.bin`;
134
+ }
135
+
136
+ private getPersistedVectorCaches(data: any): PersistedVectorCache[] {
137
+ if (Array.isArray(data.vectorCaches)) {
138
+ return data.vectorCaches.filter(
139
+ (cache: any): cache is PersistedVectorCache =>
140
+ cache &&
141
+ Number.isInteger(cache.vectorDim) &&
142
+ cache.vectorDim > 0 &&
143
+ Array.isArray(cache.vectorChunkIds) &&
144
+ typeof cache.vectorHash === "string" &&
145
+ typeof cache.fileName === "string" &&
146
+ path.basename(cache.fileName) === cache.fileName,
147
+ );
148
+ }
149
+
150
+ if (
151
+ Number.isInteger(data.vectorDim) &&
152
+ data.vectorDim > 0 &&
153
+ Array.isArray(data.vectorChunkIds) &&
154
+ typeof data.vectorHash === "string"
155
+ ) {
156
+ return [{
157
+ vectorDim: data.vectorDim,
158
+ vectorChunkIds: data.vectorChunkIds,
159
+ vectorChunkHashes: data.vectorChunkHashes,
160
+ vectorHash: data.vectorHash,
161
+ fileName: "vectors.bin",
162
+ }];
163
+ }
164
+
165
+ return [];
166
+ }
167
+
168
+ private getChunkHashMap(): Map<string, string> {
169
+ return new Map(
170
+ Array.from(this.chunks.values()).map((chunk) => [chunk.id, chunk.hash]),
171
+ );
172
+ }
173
+
174
+ private loadVectorCache(cache: PersistedVectorCache): void {
175
+ const vectorChunkIds = cache.vectorChunkIds;
176
+ const vectorPath = this.getVectorsFilePath(cache.fileName);
177
+ if (
178
+ !fs.existsSync(vectorPath) ||
179
+ vectorChunkIds.length === 0 ||
180
+ new Set(vectorChunkIds).size !== vectorChunkIds.length
181
+ ) return;
182
+
183
+ const buffer = fs.readFileSync(vectorPath);
184
+ const expectedBytes = vectorChunkIds.length * cache.vectorDim * 4;
185
+ if (
186
+ buffer.byteLength !== expectedBytes ||
187
+ cache.vectorHash !==
188
+ crypto
189
+ .createHash("sha256")
190
+ .update(JSON.stringify(vectorChunkIds))
191
+ .update(buffer)
192
+ .digest("hex")
193
+ ) return;
194
+
195
+ const currentHashes = this.getChunkHashMap();
196
+ const hasChunkHashes =
197
+ Array.isArray(cache.vectorChunkHashes) &&
198
+ cache.vectorChunkHashes.length === vectorChunkIds.length;
199
+ if (Array.isArray(cache.vectorChunkHashes) && !hasChunkHashes) return;
200
+ if (!hasChunkHashes && !this.isWorkspaceSnapshotFresh()) return;
201
+ if (
202
+ !hasChunkHashes &&
203
+ (vectorChunkIds.length !== this.chunks.size ||
204
+ vectorChunkIds.some((id) => !this.chunks.has(id)))
205
+ ) return;
206
+
207
+ const floatArray = new Float32Array(
208
+ buffer.buffer,
209
+ buffer.byteOffset,
210
+ buffer.byteLength / 4,
211
+ );
212
+ for (let index = 0; index < vectorChunkIds.length; index++) {
213
+ const chunkId = vectorChunkIds[index];
214
+ if (!this.chunks.has(chunkId)) continue;
215
+ if (
216
+ hasChunkHashes &&
217
+ cache.vectorChunkHashes?.[index] !== currentHashes.get(chunkId)
218
+ ) continue;
219
+ const vector = new Float32Array(cache.vectorDim);
220
+ vector.set(
221
+ floatArray.subarray(
222
+ index * cache.vectorDim,
223
+ (index + 1) * cache.vectorDim,
224
+ ),
225
+ );
226
+ this.vectors.set(chunkId, vector);
227
+ }
113
228
  }
114
229
 
115
230
  /**
@@ -117,7 +232,6 @@ export class HybridSearchIndex {
117
232
  */
118
233
  public loadFromDisk(): boolean {
119
234
  const indexPath = this.getIndexFilePath();
120
- const vectorsPath = this.getVectorsFilePath();
121
235
 
122
236
  if (!fs.existsSync(indexPath)) return false;
123
237
 
@@ -136,8 +250,17 @@ export class HybridSearchIndex {
136
250
  this.bm25.clear();
137
251
  this.fileHashes.clear();
138
252
  this.vectors.clear();
253
+ this.persistedVectorCaches = [];
139
254
 
140
255
  for (const chunk of data.chunks as CodeChunk[]) {
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
+ }
141
264
  this.chunks.set(chunk.id, chunk);
142
265
  this.bm25.addChunk(chunk);
143
266
  }
@@ -147,53 +270,25 @@ export class HybridSearchIndex {
147
270
  this.fileHashes.set(f, h as string);
148
271
  }
149
272
 
150
- // Only load binary vectors when metadata proves a complete, one-to-one
151
- // chunk/vector mapping. Otherwise retain the safe BM25 index only.
273
+ this.persistedVectorCaches = this.getPersistedVectorCaches(data);
152
274
  const wantsVectors =
153
275
  this.config.effectiveProfile === "hybrid" ||
154
276
  this.config.effectiveProfile === "full";
155
- const vectorChunkIds = data.vectorChunkIds;
156
- const validVectorMetadata =
157
- wantsVectors &&
158
- data.profile === this.config.profile &&
159
- fs.existsSync(vectorsPath) &&
160
- Number.isInteger(data.vectorDim) &&
161
- data.vectorDim > 0 &&
162
- Array.isArray(vectorChunkIds) &&
163
- vectorChunkIds.length > 0 &&
164
- new Set(vectorChunkIds).size === vectorChunkIds.length &&
165
- vectorChunkIds.every(
166
- (id: unknown) => typeof id === "string" && this.chunks.has(id),
167
- );
168
- if (validVectorMetadata) {
169
- const buf = fs.readFileSync(vectorsPath);
170
- const dim = data.vectorDim as number;
171
- const expectedBytes = vectorChunkIds.length * dim * 4;
172
- if (
173
- buf.byteLength === expectedBytes &&
174
- typeof data.vectorHash === "string" &&
175
- data.vectorHash ===
176
- crypto
177
- .createHash("sha256")
178
- .update(JSON.stringify(vectorChunkIds))
179
- .update(buf)
180
- .digest("hex")
181
- ) {
182
- const floatArray = new Float32Array(
183
- buf.buffer,
184
- buf.byteOffset,
185
- buf.byteLength / 4,
186
- );
187
-
188
- for (let index = 0; index < vectorChunkIds.length; index++) {
189
- const vec = new Float32Array(dim);
190
- vec.set(floatArray.subarray(index * dim, (index + 1) * dim));
191
- this.vectors.set(vectorChunkIds[index], vec);
192
- }
193
- }
277
+ const activeCache = this.persistedVectorCaches.find(
278
+ (cache) => cache.vectorDim === this.config.matryoshkaDim,
279
+ );
280
+ if (wantsVectors && activeCache) {
281
+ this.loadVectorCache(activeCache);
194
282
  }
195
283
 
196
- this.isInitialized = true;
284
+ const vectorsReady =
285
+ !wantsVectors ||
286
+ (this.vectors.size === this.chunks.size &&
287
+ this.vectors.size > 0 &&
288
+ Array.from(this.vectors.values()).every(
289
+ (vector) => vector.length === this.config.matryoshkaDim,
290
+ ));
291
+ this.isInitialized = vectorsReady;
197
292
  return true;
198
293
  } catch {
199
294
  return false;
@@ -226,52 +321,62 @@ export class HybridSearchIndex {
226
321
  fileHashesObj[f] = h;
227
322
  }
228
323
 
229
- const vectorChunkIds: string[] = [];
230
- let vectorDim = 0;
231
- const vectorArrays: Float32Array[] = [];
232
-
233
- for (const [id, vec] of this.vectors.entries()) {
234
- vectorChunkIds.push(id);
235
- vectorArrays.push(vec);
236
- if (vectorDim === 0) vectorDim = vec.length;
324
+ const vectorCaches = new Map<number, PersistedVectorCache>();
325
+ for (const cache of this.persistedVectorCaches) {
326
+ vectorCaches.set(cache.vectorDim, cache);
237
327
  }
238
328
 
239
- const vectorBuffer = Buffer.alloc(vectorArrays.length * vectorDim * 4);
240
- for (let i = 0; i < vectorArrays.length; i++) {
241
- const bytes = Buffer.from(
242
- vectorArrays[i].buffer,
243
- vectorArrays[i].byteOffset,
244
- vectorArrays[i].byteLength,
329
+ if (
330
+ this.vectors.size > 0 &&
331
+ this.vectors.size === this.chunks.size &&
332
+ Array.from(this.vectors.keys()).every((id) => this.chunks.has(id))
333
+ ) {
334
+ const vectorChunkIds = Array.from(this.vectors.keys());
335
+ const vectorArrays = vectorChunkIds.map((id) => this.vectors.get(id)!);
336
+ const vectorDim = vectorArrays[0].length;
337
+ const vectorBuffer = Buffer.alloc(vectorArrays.length * vectorDim * 4);
338
+ for (let i = 0; i < vectorArrays.length; i++) {
339
+ const bytes = Buffer.from(
340
+ vectorArrays[i].buffer,
341
+ vectorArrays[i].byteOffset,
342
+ vectorArrays[i].byteLength,
343
+ );
344
+ bytes.copy(vectorBuffer, i * vectorDim * 4);
345
+ }
346
+ const vectorHash = crypto
347
+ .createHash("sha256")
348
+ .update(JSON.stringify(vectorChunkIds))
349
+ .update(vectorBuffer)
350
+ .digest("hex");
351
+ const vectorChunkHashes = vectorChunkIds.map(
352
+ (id) => this.chunks.get(id)?.hash || "",
245
353
  );
246
- bytes.copy(vectorBuffer, i * vectorDim * 4);
354
+ const fileName = this.getVectorCacheFileName(vectorDim);
355
+ vectorCaches.set(vectorDim, {
356
+ vectorDim,
357
+ vectorChunkIds,
358
+ vectorChunkHashes,
359
+ vectorHash,
360
+ fileName,
361
+ });
362
+ writeFileSyncAtomic(this.getVectorsFilePath(fileName), vectorBuffer);
247
363
  }
248
- const vectorHash = crypto
249
- .createHash("sha256")
250
- .update(JSON.stringify(vectorChunkIds))
251
- .update(vectorBuffer)
252
- .digest("hex");
253
364
 
365
+ this.persistedVectorCaches = Array.from(vectorCaches.values());
254
366
  const indexData = {
255
367
  version: INDEX_VERSION,
256
368
  extractorGeneration: EXTRACTOR_GENERATION,
257
369
  updatedAt: new Date().toISOString(),
258
370
  profile: this.config.profile,
259
- vectorDim,
260
371
  fileHashes: fileHashesObj,
261
372
  chunks: chunkList,
262
- vectorChunkIds,
263
- vectorHash,
373
+ vectorCaches: this.persistedVectorCaches,
264
374
  };
265
375
 
266
376
  writeFileSyncAtomic(
267
377
  this.getIndexFilePath(),
268
378
  JSON.stringify(indexData, null, 2),
269
379
  );
270
-
271
- // Write binary vectors
272
- if (vectorBuffer.length > 0) {
273
- writeFileSyncAtomic(this.getVectorsFilePath(), vectorBuffer);
274
- }
275
380
  } catch (err) {
276
381
  console.error("[Search Index] Failed saving cache:", err);
277
382
  }
@@ -283,7 +388,7 @@ export class HybridSearchIndex {
283
388
  public async syncWorkspace(
284
389
  forceReindex = false,
285
390
  onProgress?: (msg: string) => void,
286
- ): Promise<{ chunkCount: number; fileCount: number }> {
391
+ ): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
287
392
  if (this.activeSync) return this.activeSync;
288
393
 
289
394
  const sync = (async () => {
@@ -387,7 +492,7 @@ export class HybridSearchIndex {
387
492
  forceReindex: boolean,
388
493
  onProgress: ((msg: string) => void) | undefined,
389
494
  syncGeneration: number,
390
- ): Promise<{ chunkCount: number; fileCount: number }> {
495
+ ): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
391
496
  this.isIndexing = true;
392
497
  try {
393
498
  if (
@@ -429,13 +534,21 @@ export class HybridSearchIndex {
429
534
  }
430
535
  }
431
536
 
432
- // Identify changed, added, or deleted files
537
+ // Identify changed, added, or deleted files. A profile upgrade from BM25
538
+ // to vector retrieval must also embed unchanged chunks that have no vector.
433
539
  const filesToReindex: string[] = [];
434
540
  const filesToDelete: string[] = [];
541
+ const wantsVectors =
542
+ this.config.effectiveProfile === "hybrid" ||
543
+ this.config.effectiveProfile === "full";
435
544
 
436
545
  for (const [relPath, info] of currentFiles.entries()) {
437
546
  const oldHash = this.fileHashes.get(relPath);
438
- if (forceReindex || !oldHash || oldHash !== info.hash) {
547
+ const missingFileVectors = wantsVectors && info.chunks.some((chunk) => {
548
+ const vector = this.vectors.get(chunk.id);
549
+ return !vector || vector.length !== this.config.matryoshkaDim;
550
+ });
551
+ if (forceReindex || missingFileVectors || !oldHash || oldHash !== info.hash) {
439
552
  filesToReindex.push(relPath);
440
553
  }
441
554
  }
@@ -496,14 +609,17 @@ export class HybridSearchIndex {
496
609
  if (isVectorEnabled && chunksToEmbed.length > 0) {
497
610
  const batchSize = this.config.batchSize || 2;
498
611
  const sleepMs = this.config.sleepBetweenBatchesMs || 50;
612
+ const embedStartTime = Date.now();
499
613
 
500
614
  for (let i = 0; i < chunksToEmbed.length; i += batchSize) {
501
615
  const batch = chunksToEmbed.slice(i, i + batchSize);
502
616
  const texts = batch.map((c) => c.textForEmbedding);
503
617
  const processed = Math.min(i + batch.length, chunksToEmbed.length);
504
618
  const pct = Math.round((processed / chunksToEmbed.length) * 100);
619
+ const elapsedSec = Math.max(0.001, (Date.now() - embedStartTime) / 1000);
620
+ const chunkSpeed = (processed / elapsedSec).toFixed(1);
505
621
  onProgress?.(
506
- `Embedding code chunks: ${pct}% (${processed}/${chunksToEmbed.length})`,
622
+ `Embedding code chunks: ${pct}% (${processed}/${chunksToEmbed.length} • ${chunkSpeed} chunk/s)`,
507
623
  );
508
624
  const vecs = await this.embedder.embedBatch(texts, false, onProgress);
509
625
 
@@ -524,7 +640,11 @@ export class HybridSearchIndex {
524
640
  }
525
641
 
526
642
  this.isInitialized = true;
527
- return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size };
643
+ return {
644
+ chunkCount: this.chunks.size,
645
+ fileCount: this.fileHashes.size,
646
+ indexedCount: filesToReindex.length + filesToDelete.length,
647
+ };
528
648
  } finally {
529
649
  this.isIndexing = false;
530
650
  if (this.generation !== syncGeneration) this.isInitialized = false;
@@ -631,7 +751,13 @@ export class HybridSearchIndex {
631
751
  activeConfig.effectiveProfile === "hybrid" ||
632
752
  activeConfig.effectiveProfile === "full";
633
753
  const isVectorReady =
634
- wantsVectors && !this.isIndexing && this.vectors.size > 0;
754
+ wantsVectors &&
755
+ !this.isIndexing &&
756
+ this.vectors.size === this.chunks.size &&
757
+ this.vectors.size > 0 &&
758
+ Array.from(this.vectors.values()).every(
759
+ (vector) => vector.length === activeConfig.matryoshkaDim,
760
+ );
635
761
 
636
762
  if (isVectorReady) {
637
763
  const queryVec = await this.embedder.embed(query, true);
@@ -173,8 +173,9 @@ export function extractSymbolContent(
173
173
  }
174
174
  }
175
175
 
176
- // Apply surrounding context if requested
177
- const extra = options.surroundingLines || 0;
176
+ // Apply surrounding context if requested (capped at 10 lines to prevent context bloat)
177
+ const requestedExtra = options.surroundingLines || 0;
178
+ const extra = Math.min(10, Math.max(0, requestedExtra));
178
179
  const finalStart = Math.max(0, actualStartIdx - extra);
179
180
  const finalEnd = Math.min(lines.length - 1, endIdx + extra);
180
181
 
@@ -191,8 +192,37 @@ export function extractSymbolContent(
191
192
  });
192
193
  }
193
194
 
195
+ // Deduplicate strictly overlapping companion symbols (e.g. interface + companion const at the same lines)
196
+ // Only merge if one range actually contains or directly overlaps the other (not distinct separate functions)
197
+ const deduped: SymbolLocation[] = [];
198
+ for (const m of matches) {
199
+ const existingIdx = deduped.findIndex(
200
+ (d) =>
201
+ d.name.toLowerCase() === m.name.toLowerCase() &&
202
+ // Overlap condition: ranges must strictly intersect
203
+ d.startLine <= m.endLine && m.startLine <= d.endLine,
204
+ );
205
+ if (existingIdx !== -1) {
206
+ const ex = deduped[existingIdx];
207
+ // Merge the overlapping range
208
+ const mergedStart = Math.min(ex.startLine, m.startLine);
209
+ const mergedEnd = Math.max(ex.endLine, m.endLine);
210
+ deduped[existingIdx] = {
211
+ name: ex.name,
212
+ kind: ex.kind === "interface" || ex.kind === "type" ? m.kind : ex.kind,
213
+ signature: ex.signature || m.signature,
214
+ startLine: mergedStart,
215
+ endLine: mergedEnd,
216
+ content: lines.slice(mergedStart - 1, mergedEnd).join("\n"),
217
+ filePath: ex.filePath,
218
+ };
219
+ } else {
220
+ deduped.push(m);
221
+ }
222
+ }
223
+
194
224
  return {
195
- found: matches.length > 0,
196
- symbols: matches,
225
+ found: deduped.length > 0,
226
+ symbols: deduped,
197
227
  };
198
228
  }