@floydous/pi-agent-kernel 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -2
- package/README.md +24 -1
- package/config.example.toml +36 -0
- package/docs/configuration.md +11 -3
- package/docs/retrieval.md +15 -1
- package/docs/testing.md +5 -3
- package/package.json +3 -2
- package/src/config/agent_kernel_command.ts +834 -0
- package/src/config/index.ts +1 -0
- package/src/config/kernel_config.ts +78 -14
- package/src/config/toml.ts +15 -4
- package/src/context/session_repair.ts +24 -6
- package/src/editing/smart_anchor.ts +16 -7
- package/src/editing/syntax-verify.ts +17 -7
- package/src/index.ts +117 -86
- package/src/lsp/lsp_client.ts +37 -3
- package/src/lsp/lsp_formatter.ts +4 -2
- package/src/lsp/lsp_installer.ts +46 -115
- package/src/lsp/lsp_registry.ts +36 -28
- package/src/retrieval/ast_search.ts +136 -172
- package/src/retrieval/repomap.ts +8 -47
- package/src/retrieval/search_chunker.ts +9 -34
- package/src/retrieval/search_config.ts +59 -14
- package/src/retrieval/search_index.ts +396 -27
- package/src/retrieval/workspace_walker.ts +262 -0
- package/src/safety/epistemic_guard.ts +1 -1
- package/src/safety/output_clamper.ts +32 -9
- package/src/tools/edit_tool.ts +11 -8
- package/src/tools/lsp_tool.ts +12 -2
- package/src/tools/read_tool.ts +4 -4
- package/config.toml +0 -30
|
@@ -15,7 +15,6 @@ import {
|
|
|
15
15
|
getSearchConfig,
|
|
16
16
|
type SearchConfig,
|
|
17
17
|
type SearchProfile,
|
|
18
|
-
savePersistedProfile,
|
|
19
18
|
} from "./search_config";
|
|
20
19
|
import { kernelDebug } from "../safety/kernel_debug";
|
|
21
20
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
@@ -51,17 +50,27 @@ export class HybridSearchIndex {
|
|
|
51
50
|
private chunks: Map<string, CodeChunk> = new Map();
|
|
52
51
|
private vectors: Map<string, Float32Array> = new Map();
|
|
53
52
|
private fileHashes: Map<string, string> = new Map(); // relPath -> SHA256 hash
|
|
53
|
+
private ignoreConfigHashes: Map<string, string> = new Map(); // ignore config file -> SHA256 hash
|
|
54
54
|
private isInitialized = false;
|
|
55
55
|
private isIndexing = false;
|
|
56
56
|
private dirtyFiles = new Set<string>();
|
|
57
57
|
private generation = 0;
|
|
58
|
+
private syncAbortController: AbortController | null = null;
|
|
59
|
+
private fileGenerations = new Map<string, number>();
|
|
60
|
+
private activeFileUpdates = new Map<string, Promise<void>>();
|
|
61
|
+
private debouncedSaveTimer: NodeJS.Timeout | null = null;
|
|
62
|
+
private debouncedSaveDeadline: number | null = null;
|
|
63
|
+
private isSaving = false;
|
|
64
|
+
private hasPendingSave = false;
|
|
65
|
+
private isShuttingDown = false;
|
|
66
|
+
private activeSavePromise: Promise<void> | null = null;
|
|
58
67
|
private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
|
|
59
68
|
private liveCheckPromise: Promise<boolean> | null = null;
|
|
60
69
|
private persistedVectorCaches: PersistedVectorCache[] = [];
|
|
61
70
|
|
|
62
71
|
constructor(cwd: string, profile?: SearchProfile) {
|
|
63
72
|
this.cwd = cwd;
|
|
64
|
-
this.config = getSearchConfig(profile);
|
|
73
|
+
this.config = getSearchConfig(profile, cwd);
|
|
65
74
|
this.embedder = new LocalEmbedder(this.config);
|
|
66
75
|
this.loadFromDisk();
|
|
67
76
|
}
|
|
@@ -76,15 +85,28 @@ export class HybridSearchIndex {
|
|
|
76
85
|
|
|
77
86
|
public setProfile(profile: SearchProfile): void {
|
|
78
87
|
const oldEffective = this.config.effectiveProfile;
|
|
79
|
-
|
|
80
|
-
this.config = getSearchConfig(profile);
|
|
88
|
+
const oldProfile = this.config.profile;
|
|
89
|
+
this.config = getSearchConfig(profile, this.cwd);
|
|
81
90
|
this.embedder.updateConfig(this.config);
|
|
82
91
|
|
|
83
|
-
if (oldEffective !== this.config.effectiveProfile) {
|
|
92
|
+
if (oldProfile !== this.config.profile || oldEffective !== this.config.effectiveProfile) {
|
|
93
|
+
this.generation++;
|
|
94
|
+
if (this.debouncedSaveTimer) {
|
|
95
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
96
|
+
this.debouncedSaveTimer = null;
|
|
97
|
+
this.debouncedSaveDeadline = null;
|
|
98
|
+
}
|
|
99
|
+
if (this.syncAbortController) {
|
|
100
|
+
this.syncAbortController.abort();
|
|
101
|
+
this.syncAbortController = null;
|
|
102
|
+
}
|
|
103
|
+
this.activeSync = null;
|
|
104
|
+
|
|
84
105
|
// Keep vector caches on disk; only the active in-memory representation
|
|
85
106
|
// changes when switching profiles.
|
|
86
107
|
this.vectors.clear();
|
|
87
108
|
this.isInitialized = false;
|
|
109
|
+
this.loadFromDisk();
|
|
88
110
|
}
|
|
89
111
|
|
|
90
112
|
if (
|
|
@@ -270,6 +292,15 @@ export class HybridSearchIndex {
|
|
|
270
292
|
this.fileHashes.set(f, h as string);
|
|
271
293
|
}
|
|
272
294
|
|
|
295
|
+
this.ignoreConfigHashes.clear();
|
|
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
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
273
304
|
this.persistedVectorCaches = this.getPersistedVectorCaches(data);
|
|
274
305
|
const wantsVectors =
|
|
275
306
|
this.config.effectiveProfile === "hybrid" ||
|
|
@@ -369,6 +400,7 @@ export class HybridSearchIndex {
|
|
|
369
400
|
updatedAt: new Date().toISOString(),
|
|
370
401
|
profile: this.config.profile,
|
|
371
402
|
fileHashes: fileHashesObj,
|
|
403
|
+
ignoreConfigHashes: Object.fromEntries(this.ignoreConfigHashes),
|
|
372
404
|
chunks: chunkList,
|
|
373
405
|
vectorCaches: this.persistedVectorCaches,
|
|
374
406
|
};
|
|
@@ -382,6 +414,71 @@ export class HybridSearchIndex {
|
|
|
382
414
|
}
|
|
383
415
|
}
|
|
384
416
|
|
|
417
|
+
/**
|
|
418
|
+
* Schedule debounced disk persistence to coalesce rapid edits.
|
|
419
|
+
*/
|
|
420
|
+
public scheduleDebouncedSave(delayMs = 500, maxDelayMs = 2000): void {
|
|
421
|
+
const now = Date.now();
|
|
422
|
+
if (!this.debouncedSaveDeadline) {
|
|
423
|
+
this.debouncedSaveDeadline = now + maxDelayMs;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (this.debouncedSaveTimer) {
|
|
427
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
428
|
+
this.debouncedSaveTimer = null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const remainingMax = Math.max(0, this.debouncedSaveDeadline - now);
|
|
432
|
+
const actualDelay = Math.min(delayMs, remainingMax);
|
|
433
|
+
|
|
434
|
+
this.debouncedSaveTimer = setTimeout(() => {
|
|
435
|
+
this.debouncedSaveTimer = null;
|
|
436
|
+
this.debouncedSaveDeadline = null;
|
|
437
|
+
void this.flushPendingSave();
|
|
438
|
+
}, actualDelay);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Flush any pending index updates to disk cache.
|
|
443
|
+
*/
|
|
444
|
+
public async flushPendingSave(isFinalShutdown = false): Promise<void> {
|
|
445
|
+
if (isFinalShutdown) {
|
|
446
|
+
this.isShuttingDown = true;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Disarm debounce timer immediately to prevent reentrancy while awaiting tasks
|
|
450
|
+
if (this.debouncedSaveTimer) {
|
|
451
|
+
clearTimeout(this.debouncedSaveTimer);
|
|
452
|
+
this.debouncedSaveTimer = null;
|
|
453
|
+
this.debouncedSaveDeadline = null;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Await any in-flight full workspace sync
|
|
457
|
+
await this.waitForActiveSync();
|
|
458
|
+
|
|
459
|
+
// Drain all active in-flight file updates first so latest edits commit to RAM before saving
|
|
460
|
+
while (this.activeFileUpdates.size > 0) {
|
|
461
|
+
await Promise.allSettled(Array.from(this.activeFileUpdates.values()));
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Await any active in-flight save before starting final save
|
|
465
|
+
while (this.activeSavePromise) {
|
|
466
|
+
await this.activeSavePromise;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const saveTask = (async () => {
|
|
470
|
+
this.saveToDisk();
|
|
471
|
+
})();
|
|
472
|
+
this.activeSavePromise = saveTask;
|
|
473
|
+
try {
|
|
474
|
+
await saveTask;
|
|
475
|
+
} finally {
|
|
476
|
+
if (this.activeSavePromise === saveTask) {
|
|
477
|
+
this.activeSavePromise = null;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
385
482
|
/**
|
|
386
483
|
* Synchronize and incrementally update workspace index.
|
|
387
484
|
*/
|
|
@@ -391,14 +488,24 @@ export class HybridSearchIndex {
|
|
|
391
488
|
): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
|
|
392
489
|
if (this.activeSync) return this.activeSync;
|
|
393
490
|
|
|
491
|
+
const abortController = new AbortController();
|
|
492
|
+
this.syncAbortController = abortController;
|
|
493
|
+
const syncGeneration = ++this.generation;
|
|
494
|
+
|
|
394
495
|
const sync = (async () => {
|
|
395
496
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
396
|
-
|
|
497
|
+
if (abortController.signal.aborted) {
|
|
498
|
+
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
|
|
499
|
+
}
|
|
397
500
|
const result = await this.performSyncWorkspace(
|
|
398
501
|
forceReindex && attempt === 0,
|
|
399
502
|
onProgress,
|
|
400
503
|
syncGeneration,
|
|
504
|
+
abortController.signal,
|
|
401
505
|
);
|
|
506
|
+
if (abortController.signal.aborted) {
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
402
509
|
if (
|
|
403
510
|
this.generation !== syncGeneration ||
|
|
404
511
|
!this.isWorkspaceSnapshotFresh()
|
|
@@ -416,8 +523,43 @@ export class HybridSearchIndex {
|
|
|
416
523
|
try {
|
|
417
524
|
return await sync;
|
|
418
525
|
} finally {
|
|
419
|
-
if (this.activeSync === sync)
|
|
526
|
+
if (this.activeSync === sync) {
|
|
527
|
+
this.activeSync = null;
|
|
528
|
+
if (this.syncAbortController === abortController) {
|
|
529
|
+
this.syncAbortController = null;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private getWorkspaceIgnoreHashes(): Map<string, string> {
|
|
536
|
+
const hashes = new Map<string, string>();
|
|
537
|
+
const gitIgnorePath = path.join(this.cwd, ".gitignore");
|
|
538
|
+
if (fs.existsSync(gitIgnorePath)) {
|
|
539
|
+
try {
|
|
540
|
+
hashes.set(".gitignore", computeHash(fs.readFileSync(gitIgnorePath, "utf8")));
|
|
541
|
+
} catch (e) {
|
|
542
|
+
kernelDebug(e);
|
|
543
|
+
}
|
|
420
544
|
}
|
|
545
|
+
const piIgnorePath = path.join(this.cwd, ".piignore");
|
|
546
|
+
if (fs.existsSync(piIgnorePath)) {
|
|
547
|
+
try {
|
|
548
|
+
hashes.set(".piignore", computeHash(fs.readFileSync(piIgnorePath, "utf8")));
|
|
549
|
+
} catch (e) {
|
|
550
|
+
kernelDebug(e);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return hashes;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
private isIgnoreConfigFresh(): boolean {
|
|
557
|
+
const current = this.getWorkspaceIgnoreHashes();
|
|
558
|
+
if (current.size !== this.ignoreConfigHashes.size) return false;
|
|
559
|
+
for (const [k, v] of this.ignoreConfigHashes.entries()) {
|
|
560
|
+
if (current.get(k) !== v) return false;
|
|
561
|
+
}
|
|
562
|
+
return true;
|
|
421
563
|
}
|
|
422
564
|
|
|
423
565
|
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
@@ -435,6 +577,7 @@ export class HybridSearchIndex {
|
|
|
435
577
|
}
|
|
436
578
|
|
|
437
579
|
private isWorkspaceSnapshotFresh(): boolean {
|
|
580
|
+
if (!this.isIgnoreConfigFresh()) return false;
|
|
438
581
|
const currentHashes = this.getWorkspaceFileHashes();
|
|
439
582
|
if (!currentHashes || currentHashes.size !== this.fileHashes.size) return false;
|
|
440
583
|
for (const [relPath, hash] of this.fileHashes.entries()) {
|
|
@@ -492,7 +635,14 @@ export class HybridSearchIndex {
|
|
|
492
635
|
forceReindex: boolean,
|
|
493
636
|
onProgress: ((msg: string) => void) | undefined,
|
|
494
637
|
syncGeneration: number,
|
|
638
|
+
signal?: AbortSignal,
|
|
495
639
|
): Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> {
|
|
640
|
+
if (this.config.effectiveProfile === "off") {
|
|
641
|
+
return { chunkCount: 0, fileCount: 0, indexedCount: 0 };
|
|
642
|
+
}
|
|
643
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
644
|
+
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
|
|
645
|
+
}
|
|
496
646
|
this.isIndexing = true;
|
|
497
647
|
try {
|
|
498
648
|
if (
|
|
@@ -611,31 +761,69 @@ export class HybridSearchIndex {
|
|
|
611
761
|
const sleepMs = this.config.sleepBetweenBatchesMs || 50;
|
|
612
762
|
const embedStartTime = Date.now();
|
|
613
763
|
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
764
|
+
for (let i = 0; i < chunksToEmbed.length; i += batchSize) {
|
|
765
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
766
|
+
kernelDebug("[Search Index] Aborting embedding loop due to cancellation signal or newer generation");
|
|
767
|
+
break;
|
|
768
|
+
}
|
|
769
|
+
const batch = chunksToEmbed.slice(i, i + batchSize);
|
|
770
|
+
const texts = batch.map((c) => c.textForEmbedding);
|
|
771
|
+
const processed = Math.min(i + batch.length, chunksToEmbed.length);
|
|
772
|
+
const pct = Math.round((processed / chunksToEmbed.length) * 100);
|
|
773
|
+
const elapsedSec = Math.max(0.001, (Date.now() - embedStartTime) / 1000);
|
|
774
|
+
const chunkSpeed = (processed / elapsedSec).toFixed(1);
|
|
775
|
+
onProgress?.(
|
|
776
|
+
`Embedding code chunks: ${pct}% (${processed}/${chunksToEmbed.length} • ${chunkSpeed} chunk/s)`,
|
|
777
|
+
);
|
|
778
|
+
const vecs = await this.embedder.embedBatch(texts, false, onProgress);
|
|
779
|
+
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
780
|
+
kernelDebug("[Search Index] Aborting post-embedBatch due to cancellation signal or newer generation");
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
631
783
|
|
|
632
|
-
|
|
633
|
-
if (
|
|
634
|
-
|
|
784
|
+
for (let j = 0; j < batch.length; j++) {
|
|
785
|
+
if (vecs[j] && vecs[j].length === this.config.matryoshkaDim) {
|
|
786
|
+
this.vectors.set(batch[j].id, vecs[j]);
|
|
635
787
|
}
|
|
636
788
|
}
|
|
789
|
+
|
|
790
|
+
// Async sleep to yield CPU and prevent freezing system daemons
|
|
791
|
+
if (sleepMs > 0 && i + batchSize < chunksToEmbed.length) {
|
|
792
|
+
await new Promise((r) => {
|
|
793
|
+
const timeout = setTimeout(r, sleepMs);
|
|
794
|
+
signal?.addEventListener(
|
|
795
|
+
"abort",
|
|
796
|
+
() => {
|
|
797
|
+
clearTimeout(timeout);
|
|
798
|
+
r(undefined);
|
|
799
|
+
},
|
|
800
|
+
{ once: true },
|
|
801
|
+
);
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
if (!signal?.aborted && this.generation === syncGeneration) {
|
|
808
|
+
this.saveToDisk();
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// Track ignore configuration hashes in dedicated metadata
|
|
813
|
+
const oldIgnoreHashes = new Map(this.ignoreConfigHashes);
|
|
814
|
+
const currentIgnoreHashes = this.getWorkspaceIgnoreHashes();
|
|
815
|
+
let ignoreConfigChanged = currentIgnoreHashes.size !== oldIgnoreHashes.size;
|
|
816
|
+
if (!ignoreConfigChanged) {
|
|
817
|
+
for (const [k, v] of currentIgnoreHashes.entries()) {
|
|
818
|
+
if (oldIgnoreHashes.get(k) !== v) {
|
|
819
|
+
ignoreConfigChanged = true;
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
637
822
|
}
|
|
823
|
+
}
|
|
824
|
+
this.ignoreConfigHashes = currentIgnoreHashes;
|
|
638
825
|
|
|
826
|
+
if (filesToDelete.length > 0 || filesToReindex.length > 0 || ignoreConfigChanged) {
|
|
639
827
|
this.saveToDisk();
|
|
640
828
|
}
|
|
641
829
|
|
|
@@ -651,6 +839,181 @@ export class HybridSearchIndex {
|
|
|
651
839
|
}
|
|
652
840
|
}
|
|
653
841
|
|
|
842
|
+
/**
|
|
843
|
+
* Transactional incremental update of a single file in the index.
|
|
844
|
+
* Chunks only this file, reuses existing vectors for unchanged chunks by content hash,
|
|
845
|
+
* embeds only new/modified chunks off-to-the-side, and commits atomically.
|
|
846
|
+
*/
|
|
847
|
+
public async updateFile(filePath: string): Promise<void> {
|
|
848
|
+
if (this.isShuttingDown) return;
|
|
849
|
+
|
|
850
|
+
const resolvedPath = path.resolve(this.cwd, filePath);
|
|
851
|
+
const relPath = path
|
|
852
|
+
.relative(this.cwd, resolvedPath)
|
|
853
|
+
.replace(/\\/g, "/");
|
|
854
|
+
if (
|
|
855
|
+
!relPath ||
|
|
856
|
+
relPath === ".." ||
|
|
857
|
+
relPath.startsWith("../") ||
|
|
858
|
+
path.isAbsolute(relPath)
|
|
859
|
+
) return;
|
|
860
|
+
|
|
861
|
+
// If a full workspace sync is active, mark dirty and let full sync capture the latest file content
|
|
862
|
+
if (this.isIndexing || this.activeSync) {
|
|
863
|
+
this.dirtyFiles.add(relPath);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const currentGen = (this.fileGenerations.get(relPath) ?? 0) + 1;
|
|
868
|
+
this.fileGenerations.set(relPath, currentGen);
|
|
869
|
+
|
|
870
|
+
const task = (async () => {
|
|
871
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
872
|
+
|
|
873
|
+
// Check if file was deleted
|
|
874
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
875
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
876
|
+
this.bm25.removeFile(relPath);
|
|
877
|
+
this.fileHashes.delete(relPath);
|
|
878
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
879
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
880
|
+
this.chunks.delete(chunkId);
|
|
881
|
+
this.vectors.delete(chunkId);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
this.dirtyFiles.delete(relPath);
|
|
885
|
+
this.bm25.recalculateStats();
|
|
886
|
+
this.scheduleDebouncedSave();
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// Read file content with TOCTOU protection
|
|
891
|
+
let content: string;
|
|
892
|
+
try {
|
|
893
|
+
content = fs.readFileSync(resolvedPath, "utf-8");
|
|
894
|
+
} catch (err: any) {
|
|
895
|
+
if (err?.code === "ENOENT") {
|
|
896
|
+
// File was removed concurrently between existsSync and readFileSync
|
|
897
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
898
|
+
this.bm25.removeFile(relPath);
|
|
899
|
+
this.fileHashes.delete(relPath);
|
|
900
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
901
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
902
|
+
this.chunks.delete(chunkId);
|
|
903
|
+
this.vectors.delete(chunkId);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
this.dirtyFiles.delete(relPath);
|
|
907
|
+
this.bm25.recalculateStats();
|
|
908
|
+
this.scheduleDebouncedSave();
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
kernelDebug(`Failed reading ${resolvedPath} for updateFile: ${err}`);
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
const fileHash = computeHash(content);
|
|
916
|
+
// If file hasn't changed at all and is already indexed, nothing to do
|
|
917
|
+
if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath)) {
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// Ensure TreeSitter parser for this file's language is loaded
|
|
922
|
+
const ext = path.extname(resolvedPath).toLowerCase();
|
|
923
|
+
if (ext) {
|
|
924
|
+
try {
|
|
925
|
+
await TreeSitterEngine.getInstance().loadLanguages([ext]);
|
|
926
|
+
} catch (e) {
|
|
927
|
+
kernelDebug(e);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const newChunks = chunkFile(this.cwd, resolvedPath, content);
|
|
932
|
+
const wantsVectors =
|
|
933
|
+
this.config.effectiveProfile === "hybrid" ||
|
|
934
|
+
this.config.effectiveProfile === "full";
|
|
935
|
+
|
|
936
|
+
// Map content hash -> vector from existing chunks
|
|
937
|
+
const hashToVector = new Map<string, Float32Array>();
|
|
938
|
+
for (const chunk of this.chunks.values()) {
|
|
939
|
+
const vec = this.vectors.get(chunk.id);
|
|
940
|
+
if (vec && vec.length === this.config.matryoshkaDim) {
|
|
941
|
+
hashToVector.set(chunk.hash, vec);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
const newVectors = new Map<string, Float32Array>();
|
|
946
|
+
const missingChunks: CodeChunk[] = [];
|
|
947
|
+
|
|
948
|
+
for (const chunk of newChunks) {
|
|
949
|
+
const reused = hashToVector.get(chunk.hash);
|
|
950
|
+
if (reused) {
|
|
951
|
+
newVectors.set(chunk.id, reused);
|
|
952
|
+
} else if (wantsVectors) {
|
|
953
|
+
missingChunks.push(chunk);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// Embed missing chunks off to the side
|
|
958
|
+
if (wantsVectors && missingChunks.length > 0) {
|
|
959
|
+
const batchSize = this.config.batchSize || 2;
|
|
960
|
+
const texts = missingChunks.map((c) => c.textForEmbedding);
|
|
961
|
+
for (let i = 0; i < missingChunks.length; i += batchSize) {
|
|
962
|
+
// Check generation before each batch
|
|
963
|
+
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
964
|
+
const batchChunks = missingChunks.slice(i, i + batchSize);
|
|
965
|
+
const batchTexts = texts.slice(i, i + batchSize);
|
|
966
|
+
const vecs = await this.embedder.embedBatch(batchTexts, false);
|
|
967
|
+
for (let j = 0; j < batchChunks.length; j++) {
|
|
968
|
+
if (vecs[j]) {
|
|
969
|
+
newVectors.set(batchChunks[j].id, vecs[j]);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// Generation check: if a newer update started, discard this older result
|
|
976
|
+
if (this.fileGenerations.get(relPath) !== currentGen) {
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// Atomic in-memory swap:
|
|
981
|
+
this.bm25.removeFile(relPath);
|
|
982
|
+
for (const chunkId of Array.from(this.chunks.keys())) {
|
|
983
|
+
if (chunkId.startsWith(`${relPath}:`)) {
|
|
984
|
+
this.chunks.delete(chunkId);
|
|
985
|
+
this.vectors.delete(chunkId);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
this.fileHashes.set(relPath, fileHash);
|
|
990
|
+
for (const chunk of newChunks) {
|
|
991
|
+
this.chunks.set(chunk.id, chunk);
|
|
992
|
+
this.bm25.addChunk(chunk);
|
|
993
|
+
const vec = newVectors.get(chunk.id);
|
|
994
|
+
if (vec) {
|
|
995
|
+
this.vectors.set(chunk.id, vec);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
this.bm25.recalculateStats();
|
|
999
|
+
this.dirtyFiles.delete(relPath);
|
|
1000
|
+
if (this.dirtyFiles.size === 0) {
|
|
1001
|
+
this.isInitialized = true;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
this.scheduleDebouncedSave();
|
|
1005
|
+
})();
|
|
1006
|
+
|
|
1007
|
+
this.activeFileUpdates.set(relPath, task);
|
|
1008
|
+
try {
|
|
1009
|
+
await task;
|
|
1010
|
+
} finally {
|
|
1011
|
+
if (this.activeFileUpdates.get(relPath) === task) {
|
|
1012
|
+
this.activeFileUpdates.delete(relPath);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
654
1017
|
/**
|
|
655
1018
|
* Drop cached chunks for a file; the next search performs an incremental rescan.
|
|
656
1019
|
*/
|
|
@@ -696,10 +1059,16 @@ export class HybridSearchIndex {
|
|
|
696
1059
|
scope?: "code" | "all" | "prose";
|
|
697
1060
|
} = {},
|
|
698
1061
|
): Promise<SearchHit[]> {
|
|
1062
|
+
if (this.config.effectiveProfile === "off") {
|
|
1063
|
+
return [];
|
|
1064
|
+
}
|
|
699
1065
|
// Do not return the previous snapshot while a background synchronization
|
|
700
1066
|
// is active. This also covers startup/reindex work where the old index is
|
|
701
1067
|
// still initialized and would otherwise look usable.
|
|
702
1068
|
await this.waitForActiveSync();
|
|
1069
|
+
if (this.activeFileUpdates.size > 0) {
|
|
1070
|
+
await Promise.all(Array.from(this.activeFileUpdates.values()));
|
|
1071
|
+
}
|
|
703
1072
|
if (this.dirtyFiles.size > 0 || !this.isInitialized) {
|
|
704
1073
|
if (!this.isIndexing) {
|
|
705
1074
|
await this.syncWorkspace(false);
|