@floydous/pi-agent-kernel 0.4.3 → 0.6.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/AGENT_KERNEL_SYS_PROMPT.md +15 -12
- package/CHANGELOG.md +87 -0
- package/README.md +6 -54
- package/config.example.toml +1 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +11 -10
- package/docs/editing-and-verification.md +21 -8
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +21 -23
- package/docs/testing.md +3 -3
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +5 -3
- package/src/config/agent_kernel_command.ts +60 -625
- package/src/config/kernel_config.ts +53 -69
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +75 -37
- package/src/editing/post_edit_verification.ts +20 -14
- package/src/editing/smart_anchor.ts +9 -6
- package/src/editing/syntax-verify.ts +79 -222
- package/src/index.ts +36 -453
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +39 -28
- package/src/retrieval/search_chunker.ts +69 -7
- package/src/retrieval/search_config.ts +21 -40
- package/src/retrieval/search_embedder.ts +14 -31
- package/src/retrieval/search_index.ts +338 -129
- package/src/retrieval/search_modal.ts +1208 -222
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
- package/src/retrieval/tree_sitter_engine.ts +171 -36
- package/src/retrieval/workspace_walker.ts +78 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +97 -27
- package/src/tools/code_search_output.ts +11 -2
- package/src/tools/code_search_tool.ts +25 -13
- package/src/tools/context.ts +11 -10
- package/src/tools/edit_tool.ts +243 -154
- package/src/tools/read_tool.ts +285 -214
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
|
@@ -5,11 +5,14 @@ import * as crypto from "node:crypto";
|
|
|
5
5
|
import {
|
|
6
6
|
MAX_INDEX_CHUNKS,
|
|
7
7
|
MAX_INDEX_FILE_BYTES,
|
|
8
|
+
MAX_INDEX_FILES,
|
|
8
9
|
MAX_INDEX_WORKSPACE_BYTES,
|
|
10
|
+
MAX_WALK_FILES,
|
|
9
11
|
type CodeChunk,
|
|
12
|
+
type RankedFile,
|
|
10
13
|
chunkFile,
|
|
11
14
|
computeHash,
|
|
12
|
-
|
|
15
|
+
rankChunkableFiles,
|
|
13
16
|
SUPPORTED_EXTENSIONS,
|
|
14
17
|
} from "./search_chunker";
|
|
15
18
|
import { BM25Engine } from "./search_bm25";
|
|
@@ -23,15 +26,26 @@ import { kernelDebug } from "../safety/kernel_debug";
|
|
|
23
26
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
24
27
|
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
25
28
|
import { getSearchCacheDir } from "./search_cache";
|
|
29
|
+
import { WorkspaceWalkCache } from "./workspace_walker";
|
|
30
|
+
import { isTestPath } from "./tag_extractor";
|
|
31
|
+
import { loadKernelConfig } from "../config/kernel_config";
|
|
26
32
|
export { getSearchCacheDir } from "./search_cache";
|
|
27
33
|
|
|
28
34
|
const INDEX_VERSION = 4;
|
|
29
35
|
const LEGACY_INDEX_VERSION = 3;
|
|
30
36
|
const MAX_PERSISTED_INDEX_BYTES = 128 * 1024 * 1024;
|
|
31
37
|
const MAX_PERSISTED_VECTOR_BYTES = MAX_INDEX_CHUNKS * 768 * 4;
|
|
32
|
-
|
|
38
|
+
// Bump when extraction/chunking output changes: unchanged files reuse cached chunks, so stale chunks
|
|
39
|
+
// would otherwise persist. v3: export declarations no longer yield spurious "x as y" aliases.
|
|
40
|
+
// v4: .cc/.cxx/.hh/.hxx are indexed and C++ headers named .h are parsed with the C++ grammar.
|
|
41
|
+
// v5: Rust items under test attributes are chunked as kind "test".
|
|
42
|
+
// v6: C/C++ struct/class references and forward declarations (no body) are no longer chunked as definitions.
|
|
43
|
+
// v7: HTML files (.html, .htm) are indexed using structural semantic DOM group chunking.
|
|
44
|
+
const EXTRACTOR_GENERATION = "tree-sitter-wasm-v7";
|
|
33
45
|
|
|
34
46
|
interface PersistedVectorCache {
|
|
47
|
+
/** "<model id>@<revision>" that produced the vectors; caches from any other model are not loaded. */
|
|
48
|
+
model: string;
|
|
35
49
|
vectorDim: number;
|
|
36
50
|
vectorChunkIds: string[];
|
|
37
51
|
vectorChunkHashes?: string[];
|
|
@@ -49,7 +63,13 @@ interface PersistedIndexSnapshot {
|
|
|
49
63
|
}
|
|
50
64
|
|
|
51
65
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
52
|
-
return
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function compareStrings(a: string, b: string): number {
|
|
70
|
+
if (a < b) return -1;
|
|
71
|
+
if (a > b) return 1;
|
|
72
|
+
return 0;
|
|
53
73
|
}
|
|
54
74
|
|
|
55
75
|
function readDescriptorBounded(descriptor: number, maxBytes: number): Buffer {
|
|
@@ -70,8 +90,23 @@ function sameFileSnapshot(before: fs.Stats, after: fs.Stats): boolean {
|
|
|
70
90
|
return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs;
|
|
71
91
|
}
|
|
72
92
|
|
|
93
|
+
/** Stat + content hash of a file as last read, letting freshness checks skip unchanged files. */
|
|
94
|
+
interface FreshnessSnapshot {
|
|
95
|
+
stats: fs.Stats;
|
|
96
|
+
hash: string;
|
|
97
|
+
bytes: number;
|
|
98
|
+
/** Modified within the timestamp-granularity window of the read; a same-size rewrite could share its mtime. */
|
|
99
|
+
racy: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const RACY_MTIME_WINDOW_MS = 2_000;
|
|
103
|
+
|
|
104
|
+
function freshnessSnapshot(stats: fs.Stats, hash: string, bytes: number): FreshnessSnapshot {
|
|
105
|
+
return { stats, hash, bytes, racy: stats.mtimeMs >= Date.now() - RACY_MTIME_WINDOW_MS };
|
|
106
|
+
}
|
|
107
|
+
|
|
73
108
|
function isValidChunkKind(kind: string): boolean {
|
|
74
|
-
return kind === "file" || ["function", "class", "interface", "type", "enum", "variable", "constant", "method", "alias", "test"].includes(kind);
|
|
109
|
+
return kind === "file" || ["function", "class", "interface", "type", "enum", "variable", "constant", "method", "alias", "test", "html"].includes(kind);
|
|
75
110
|
}
|
|
76
111
|
|
|
77
112
|
function assertSafeWorkspaceRelativePath(relativePath: string): void {
|
|
@@ -150,6 +185,8 @@ export function validatePersistedIndex(
|
|
|
150
185
|
const chunkFiles = new Map<string, string>();
|
|
151
186
|
for (const value of data.chunks) {
|
|
152
187
|
if (!isRecord(value)) throw new Error("Persisted chunk must be an object");
|
|
188
|
+
// SAFETY: value is confirmed to be an object via isRecord, and each property of CodeChunk
|
|
189
|
+
// is individually runtime-validated below (id, filePath, lines, content, hash) before acceptance.
|
|
153
190
|
const chunk = value as unknown as CodeChunk;
|
|
154
191
|
if (
|
|
155
192
|
typeof chunk.id !== "string" ||
|
|
@@ -318,12 +355,61 @@ export interface SearchHit {
|
|
|
318
355
|
matches: string[];
|
|
319
356
|
}
|
|
320
357
|
|
|
358
|
+
/** The code_search file_pattern rule: case-insensitive substring of the slash-normalized relative path. */
|
|
359
|
+
function pathMatchesPattern(filePath: string, pattern: string): boolean {
|
|
360
|
+
return filePath.replace(/\\/g, "/").toLowerCase().includes(pattern.replace(/\\/g, "/").toLowerCase());
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Chunk map that also indexes chunk ids by file, so per-file lookups and removals avoid full scans. */
|
|
364
|
+
class ChunkStore extends Map<string, CodeChunk> {
|
|
365
|
+
private idsByFile = new Map<string, Set<string>>();
|
|
366
|
+
|
|
367
|
+
override set(id: string, chunk: CodeChunk): this {
|
|
368
|
+
const previous = super.get(id);
|
|
369
|
+
if (previous && previous.filePath !== chunk.filePath) this.unlink(id, previous.filePath);
|
|
370
|
+
super.set(id, chunk);
|
|
371
|
+
let ids = this.idsByFile.get(chunk.filePath);
|
|
372
|
+
if (!ids) {
|
|
373
|
+
ids = new Set();
|
|
374
|
+
this.idsByFile.set(chunk.filePath, ids);
|
|
375
|
+
}
|
|
376
|
+
ids.add(id);
|
|
377
|
+
return this;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
override delete(id: string): boolean {
|
|
381
|
+
const previous = super.get(id);
|
|
382
|
+
if (previous) this.unlink(id, previous.filePath);
|
|
383
|
+
return super.delete(id);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
override clear(): void {
|
|
387
|
+
this.idsByFile.clear();
|
|
388
|
+
super.clear();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
idsForFile(filePath: string): string[] {
|
|
392
|
+
return Array.from(this.idsByFile.get(filePath) ?? []);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
files(): IterableIterator<string> {
|
|
396
|
+
return this.idsByFile.keys();
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
private unlink(id: string, filePath: string): void {
|
|
400
|
+
const ids = this.idsByFile.get(filePath);
|
|
401
|
+
if (!ids) return;
|
|
402
|
+
ids.delete(id);
|
|
403
|
+
if (ids.size === 0) this.idsByFile.delete(filePath);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
321
407
|
export class HybridSearchIndex {
|
|
322
408
|
private cwd: string;
|
|
323
409
|
private config: SearchConfig;
|
|
324
410
|
private bm25: BM25Engine = new BM25Engine();
|
|
325
411
|
private embedder: LocalEmbedder;
|
|
326
|
-
private chunks
|
|
412
|
+
private chunks = new ChunkStore();
|
|
327
413
|
private vectors: Map<string, Float32Array> = new Map();
|
|
328
414
|
private fileHashes: Map<string, string> = new Map(); // relPath -> SHA256 hash
|
|
329
415
|
private ignoreConfigHashes: Map<string, string> = new Map(); // ignore config file -> SHA256 hash
|
|
@@ -336,15 +422,20 @@ export class HybridSearchIndex {
|
|
|
336
422
|
private activeFileUpdates = new Map<string, Promise<void>>();
|
|
337
423
|
private debouncedSaveTimer: NodeJS.Timeout | null = null;
|
|
338
424
|
private debouncedSaveDeadline: number | null = null;
|
|
339
|
-
private isSaving = false;
|
|
340
|
-
private hasPendingSave = false;
|
|
341
425
|
private isShuttingDown = false;
|
|
342
426
|
private activeSavePromise: Promise<void> | null = null;
|
|
343
427
|
private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
|
|
344
428
|
private liveCheckPromise: Promise<boolean> | null = null;
|
|
345
429
|
private persistedVectorCaches: PersistedVectorCache[] = [];
|
|
346
430
|
private skippedOversizedFiles = new Set<string>();
|
|
431
|
+
/** relPath -> hash of content skipped by MAX_INDEX_CHUNKS; freshness checks cannot count chunks, so they match this. */
|
|
432
|
+
private chunkCapSkips = new Map<string, string>();
|
|
433
|
+
private freshnessSnapshots = new Map<string, FreshnessSnapshot>();
|
|
434
|
+
private walkCache = new WorkspaceWalkCache();
|
|
435
|
+
/** Every indexable file of the last walk, in priority order (up to MAX_WALK_FILES), for coverage reporting. */
|
|
436
|
+
private walkedFiles: readonly RankedFile[] = [];
|
|
347
437
|
private projectTrusted: boolean;
|
|
438
|
+
private excludedPaths = new Set<string>();
|
|
348
439
|
|
|
349
440
|
constructor(
|
|
350
441
|
cwd: string,
|
|
@@ -354,15 +445,69 @@ export class HybridSearchIndex {
|
|
|
354
445
|
this.cwd = cwd;
|
|
355
446
|
this.projectTrusted = options.projectTrusted === true;
|
|
356
447
|
this.config = getSearchConfig(profile, cwd, this.projectTrusted);
|
|
448
|
+
try {
|
|
449
|
+
const kernelCfg = loadKernelConfig(cwd, { projectTrusted: this.projectTrusted });
|
|
450
|
+
if (Array.isArray(kernelCfg.retrieval?.excluded_paths)) {
|
|
451
|
+
this.excludedPaths = new Set(
|
|
452
|
+
kernelCfg.retrieval.excluded_paths.map((p) => p.replace(/\\/g, "/").replace(/\/$/, "")).filter(Boolean),
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
} catch {
|
|
456
|
+
// Best-effort config load
|
|
457
|
+
}
|
|
357
458
|
this.embedder = new LocalEmbedder(this.config);
|
|
358
459
|
this.loadFromDisk();
|
|
359
460
|
}
|
|
360
461
|
|
|
462
|
+
public getCwd(): string {
|
|
463
|
+
return this.cwd;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
public isPathExcluded(relPath: string): boolean {
|
|
467
|
+
const norm = relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+|\/+$/g, "");
|
|
468
|
+
for (const p of this.excludedPaths) {
|
|
469
|
+
const cleanP = p.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+|\/+$/g, "");
|
|
470
|
+
if (!cleanP) continue;
|
|
471
|
+
if (norm === cleanP || norm.startsWith(cleanP + "/")) {
|
|
472
|
+
return true;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
public getExcludedPaths(): Set<string> {
|
|
479
|
+
return new Set(this.excludedPaths);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
public setExcludedPaths(paths: Iterable<string>): void {
|
|
483
|
+
this.excludedPaths = new Set(
|
|
484
|
+
Array.from(paths)
|
|
485
|
+
.map((p) => p.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+|\/+$/g, ""))
|
|
486
|
+
.filter(Boolean),
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
public getIndexableFiles(): string[] {
|
|
491
|
+
this.walkedFiles = rankChunkableFiles(this.cwd, this.walkCache);
|
|
492
|
+
return this.walkedFiles.map((r) => r.rel);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
public getChunkCountForFile(relPath: string): number {
|
|
496
|
+
const norm = relPath.replace(/\\/g, "/");
|
|
497
|
+
const ids = this.chunks.idsForFile(norm);
|
|
498
|
+
if (ids && ids.length > 0) return ids.length;
|
|
499
|
+
try {
|
|
500
|
+
return chunkFile(this.cwd, norm).length;
|
|
501
|
+
} catch {
|
|
502
|
+
return 0;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
361
506
|
public getProfile(): SearchProfile {
|
|
362
507
|
return this.config.profile;
|
|
363
508
|
}
|
|
364
509
|
|
|
365
|
-
public getEffectiveProfile(): "lean" | "
|
|
510
|
+
public getEffectiveProfile(): "lean" | "full" | "off" {
|
|
366
511
|
return this.config.effectiveProfile;
|
|
367
512
|
}
|
|
368
513
|
|
|
@@ -398,8 +543,9 @@ export class HybridSearchIndex {
|
|
|
398
543
|
) {
|
|
399
544
|
void this.embedder.dispose();
|
|
400
545
|
try {
|
|
401
|
-
|
|
402
|
-
|
|
546
|
+
const globalWithGc = globalThis as typeof globalThis & { gc?: () => void };
|
|
547
|
+
if (typeof globalWithGc.gc === "function") {
|
|
548
|
+
globalWithGc.gc();
|
|
403
549
|
}
|
|
404
550
|
} catch (e) {
|
|
405
551
|
kernelDebug(e);
|
|
@@ -413,11 +559,8 @@ export class HybridSearchIndex {
|
|
|
413
559
|
public async preloadModel(
|
|
414
560
|
onProgress?: (msg: string) => void,
|
|
415
561
|
): Promise<boolean> {
|
|
416
|
-
if (
|
|
417
|
-
this.
|
|
418
|
-
this.config.effectiveProfile === "full"
|
|
419
|
-
) {
|
|
420
|
-
return await this.embedder.initialize(onProgress);
|
|
562
|
+
if (this.config.effectiveProfile === "full") {
|
|
563
|
+
return this.embedder.initialize(onProgress);
|
|
421
564
|
}
|
|
422
565
|
return false;
|
|
423
566
|
}
|
|
@@ -438,11 +581,17 @@ export class HybridSearchIndex {
|
|
|
438
581
|
return `vectors-${dim}d.bin`;
|
|
439
582
|
}
|
|
440
583
|
|
|
584
|
+
private vectorModel(): string {
|
|
585
|
+
return `${this.config.modelId}@${this.config.modelRevision}`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Vector caches from the current embedding model only; untagged (older) caches came from a previous model. */
|
|
441
589
|
private getPersistedVectorCaches(data: any): PersistedVectorCache[] {
|
|
442
590
|
if (Array.isArray(data.vectorCaches)) {
|
|
443
591
|
return data.vectorCaches.filter(
|
|
444
592
|
(cache: any): cache is PersistedVectorCache =>
|
|
445
593
|
cache &&
|
|
594
|
+
cache.model === this.vectorModel() &&
|
|
446
595
|
Number.isInteger(cache.vectorDim) &&
|
|
447
596
|
(cache.vectorDim === 256 || cache.vectorDim === 768) &&
|
|
448
597
|
Array.isArray(cache.vectorChunkIds) &&
|
|
@@ -459,27 +608,7 @@ export class HybridSearchIndex {
|
|
|
459
608
|
(cache.fileName === "vectors.bin" || cache.fileName === `vectors-${cache.vectorDim}d.bin`),
|
|
460
609
|
);
|
|
461
610
|
}
|
|
462
|
-
|
|
463
|
-
if (
|
|
464
|
-
Number.isInteger(data.vectorDim) &&
|
|
465
|
-
(data.vectorDim === 256 || data.vectorDim === 768) &&
|
|
466
|
-
Array.isArray(data.vectorChunkIds) &&
|
|
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)
|
|
473
|
-
) {
|
|
474
|
-
return [{
|
|
475
|
-
vectorDim: data.vectorDim,
|
|
476
|
-
vectorChunkIds: data.vectorChunkIds,
|
|
477
|
-
vectorChunkHashes: data.vectorChunkHashes,
|
|
478
|
-
vectorHash: data.vectorHash,
|
|
479
|
-
fileName: "vectors.bin",
|
|
480
|
-
}];
|
|
481
|
-
}
|
|
482
|
-
|
|
611
|
+
// The single-cache layout (vectorDim at the top level) predates model tags, so it is never from this model.
|
|
483
612
|
return [];
|
|
484
613
|
}
|
|
485
614
|
|
|
@@ -597,11 +726,13 @@ export class HybridSearchIndex {
|
|
|
597
726
|
this.persistedVectorCaches = [];
|
|
598
727
|
|
|
599
728
|
for (const chunk of validated.chunks) {
|
|
729
|
+
if (this.isPathExcluded(chunk.filePath)) continue;
|
|
600
730
|
this.chunks.set(chunk.id, chunk);
|
|
601
731
|
this.bm25.addChunk(chunk);
|
|
602
732
|
}
|
|
603
733
|
this.bm25.recalculateStats();
|
|
604
734
|
for (const [file, hash] of validated.fileHashes) {
|
|
735
|
+
if (this.isPathExcluded(file)) continue;
|
|
605
736
|
this.fileHashes.set(file, hash);
|
|
606
737
|
}
|
|
607
738
|
for (const [file, hash] of validated.ignoreConfigHashes) {
|
|
@@ -609,9 +740,7 @@ export class HybridSearchIndex {
|
|
|
609
740
|
}
|
|
610
741
|
|
|
611
742
|
this.persistedVectorCaches = persistedVectorCaches;
|
|
612
|
-
const wantsVectors =
|
|
613
|
-
this.config.effectiveProfile === "hybrid" ||
|
|
614
|
-
this.config.effectiveProfile === "full";
|
|
743
|
+
const wantsVectors = this.config.effectiveProfile === "full";
|
|
615
744
|
const activeCache = this.persistedVectorCaches.find(
|
|
616
745
|
(cache) => cache.vectorDim === this.config.matryoshkaDim,
|
|
617
746
|
);
|
|
@@ -648,8 +777,6 @@ export class HybridSearchIndex {
|
|
|
648
777
|
*/
|
|
649
778
|
public saveToDisk(): void {
|
|
650
779
|
try {
|
|
651
|
-
const cacheDir = this.getCacheDir();
|
|
652
|
-
|
|
653
780
|
const chunkList = Array.from(this.chunks.values());
|
|
654
781
|
const fileHashesObj: Record<string, string> = {};
|
|
655
782
|
for (const [f, h] of this.fileHashes.entries()) {
|
|
@@ -667,7 +794,14 @@ export class HybridSearchIndex {
|
|
|
667
794
|
Array.from(this.vectors.keys()).every((id) => this.chunks.has(id))
|
|
668
795
|
) {
|
|
669
796
|
const vectorChunkIds = Array.from(this.vectors.keys());
|
|
670
|
-
const vectorArrays =
|
|
797
|
+
const vectorArrays: Float32Array[] = [];
|
|
798
|
+
for (const id of vectorChunkIds) {
|
|
799
|
+
const vec = this.vectors.get(id);
|
|
800
|
+
if (vec) vectorArrays.push(vec);
|
|
801
|
+
}
|
|
802
|
+
if (vectorArrays.length !== vectorChunkIds.length || vectorArrays.length === 0) {
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
671
805
|
const vectorDim = vectorArrays[0].length;
|
|
672
806
|
const vectorBuffer = Buffer.alloc(vectorArrays.length * vectorDim * 4);
|
|
673
807
|
for (let i = 0; i < vectorArrays.length; i++) {
|
|
@@ -689,6 +823,7 @@ export class HybridSearchIndex {
|
|
|
689
823
|
if (vectorChunkHashes.some((hash) => !hash)) return;
|
|
690
824
|
const fileName = this.getVectorCacheFileName(vectorDim);
|
|
691
825
|
vectorCaches.set(vectorDim, {
|
|
826
|
+
model: this.vectorModel(),
|
|
692
827
|
vectorDim,
|
|
693
828
|
vectorChunkIds,
|
|
694
829
|
vectorChunkHashes,
|
|
@@ -869,11 +1004,34 @@ export class HybridSearchIndex {
|
|
|
869
1004
|
|
|
870
1005
|
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
871
1006
|
const hashes = new Map<string, string>();
|
|
1007
|
+
const snapshots = new Map<string, FreshnessSnapshot>();
|
|
872
1008
|
let workspaceBytes = 0;
|
|
873
|
-
|
|
1009
|
+
// Priority order, as in sync, so the byte caps keep the same files.
|
|
1010
|
+
this.walkedFiles = rankChunkableFiles(this.cwd, this.walkCache);
|
|
1011
|
+
const files = this.walkedFiles.slice(0, MAX_INDEX_FILES).map((entry) => entry.file);
|
|
874
1012
|
for (const filePath of files) {
|
|
875
1013
|
const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
|
|
1014
|
+
if (this.isPathExcluded(relPath)) {
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
876
1017
|
try {
|
|
1018
|
+
// Fast path: a regular file whose stat matches the snapshot taken when it was last read keeps
|
|
1019
|
+
// that read's hash. Recently modified ("racy") snapshots are always re-read.
|
|
1020
|
+
const known = this.freshnessSnapshots.get(relPath);
|
|
1021
|
+
if (known && !known.racy) {
|
|
1022
|
+
const current = fs.lstatSync(filePath);
|
|
1023
|
+
if (current.isFile() && sameFileSnapshot(known.stats, current)) {
|
|
1024
|
+
if (current.size > MAX_INDEX_FILE_BYTES || workspaceBytes + known.bytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1025
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
snapshots.set(relPath, known);
|
|
1029
|
+
if (this.chunkCapSkips.get(relPath) === known.hash) continue;
|
|
1030
|
+
workspaceBytes += known.bytes;
|
|
1031
|
+
hashes.set(relPath, known.hash);
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
877
1035
|
const descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
878
1036
|
let content: string;
|
|
879
1037
|
let opened: fs.Stats;
|
|
@@ -894,13 +1052,17 @@ export class HybridSearchIndex {
|
|
|
894
1052
|
this.skippedOversizedFiles.add(relPath);
|
|
895
1053
|
continue;
|
|
896
1054
|
}
|
|
1055
|
+
const hash = computeHash(content);
|
|
1056
|
+
snapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
|
|
1057
|
+
if (this.chunkCapSkips.get(relPath) === hash) continue;
|
|
897
1058
|
workspaceBytes += actualBytes;
|
|
898
|
-
hashes.set(relPath,
|
|
1059
|
+
hashes.set(relPath, hash);
|
|
899
1060
|
} catch (error) {
|
|
900
1061
|
kernelDebug(error);
|
|
901
1062
|
return null;
|
|
902
1063
|
}
|
|
903
1064
|
}
|
|
1065
|
+
this.freshnessSnapshots = snapshots;
|
|
904
1066
|
return hashes;
|
|
905
1067
|
}
|
|
906
1068
|
|
|
@@ -983,24 +1145,31 @@ export class HybridSearchIndex {
|
|
|
983
1145
|
|
|
984
1146
|
onProgress?.("Scanning workspace files...");
|
|
985
1147
|
|
|
986
|
-
//
|
|
987
|
-
|
|
1148
|
+
// Priority order (source, tests, vendored): the byte and chunk budgets go to project code first.
|
|
1149
|
+
this.walkedFiles = rankChunkableFiles(this.cwd, this.walkCache);
|
|
1150
|
+
const chunkableFiles = this.walkedFiles.slice(0, MAX_INDEX_FILES).map((entry) => entry.file);
|
|
988
1151
|
this.skippedOversizedFiles.clear();
|
|
1152
|
+
this.chunkCapSkips.clear();
|
|
989
1153
|
const workspaceExts = new Set<string>();
|
|
990
1154
|
for (const f of chunkableFiles) {
|
|
991
1155
|
const ext = path.extname(f).toLowerCase();
|
|
992
1156
|
if (ext) workspaceExts.add(ext);
|
|
993
1157
|
}
|
|
994
|
-
|
|
1158
|
+
// Tree-sitter grammars are only needed when a file must be (re)chunked.
|
|
1159
|
+
let languagesLoaded = false;
|
|
995
1160
|
|
|
996
1161
|
// Read each file once and derive both its chunks and hash from that same
|
|
997
1162
|
// snapshot. A second read could pair old chunks with a new hash and make
|
|
998
|
-
// the final freshness check falsely accept stale content.
|
|
999
|
-
|
|
1163
|
+
// the final freshness check falsely accept stale content. Files whose hash
|
|
1164
|
+
// matches the indexed hash reuse their indexed chunks instead of re-parsing.
|
|
1165
|
+
const selectedFiles = new Map<string, { absPath: string; hash: string; chunks: CodeChunk[] }>();
|
|
1000
1166
|
let workspaceBytes = 0;
|
|
1001
1167
|
let workspaceChunks = 0;
|
|
1002
1168
|
for (const absPath of chunkableFiles) {
|
|
1003
1169
|
const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
|
|
1170
|
+
if (this.isPathExcluded(relPath)) {
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1004
1173
|
try {
|
|
1005
1174
|
const stat = fs.statSync(absPath);
|
|
1006
1175
|
if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
|
|
@@ -1030,26 +1199,42 @@ export class HybridSearchIndex {
|
|
|
1030
1199
|
this.skippedOversizedFiles.add(relPath);
|
|
1031
1200
|
continue;
|
|
1032
1201
|
}
|
|
1033
|
-
const
|
|
1202
|
+
const hash = computeHash(content);
|
|
1203
|
+
const cachedIds = !forceReindex && this.fileHashes.get(relPath) === hash
|
|
1204
|
+
? this.chunks.idsForFile(relPath)
|
|
1205
|
+
: [];
|
|
1206
|
+
let chunks: CodeChunk[];
|
|
1207
|
+
if (cachedIds.length > 0) {
|
|
1208
|
+
chunks = cachedIds.map((id) => this.chunks.get(id)!);
|
|
1209
|
+
} else {
|
|
1210
|
+
if (!languagesLoaded) {
|
|
1211
|
+
await TreeSitterEngine.getInstance().loadLanguages(Array.from(workspaceExts));
|
|
1212
|
+
languagesLoaded = true;
|
|
1213
|
+
}
|
|
1214
|
+
chunks = chunkFile(this.cwd, absPath, content);
|
|
1215
|
+
}
|
|
1034
1216
|
if (workspaceChunks + chunks.length > MAX_INDEX_CHUNKS) {
|
|
1035
1217
|
this.skippedOversizedFiles.add(relPath);
|
|
1218
|
+
this.chunkCapSkips.set(relPath, hash);
|
|
1219
|
+
this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
|
|
1036
1220
|
continue;
|
|
1037
1221
|
}
|
|
1038
1222
|
workspaceBytes += actualBytes;
|
|
1039
1223
|
workspaceChunks += chunks.length;
|
|
1040
|
-
|
|
1224
|
+
selectedFiles.set(relPath, { absPath, hash, chunks });
|
|
1225
|
+
this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
|
|
1041
1226
|
} catch (error) {
|
|
1042
1227
|
kernelDebug(error);
|
|
1043
1228
|
}
|
|
1044
1229
|
}
|
|
1230
|
+
// Index in path order, so BM25 tie-breaking does not depend on the file priority.
|
|
1231
|
+
const currentFiles = new Map([...selectedFiles].sort((a, b) => compareStrings(a[1].absPath, b[1].absPath)));
|
|
1045
1232
|
|
|
1046
1233
|
// Identify changed, added, or deleted files. A profile upgrade from BM25
|
|
1047
1234
|
// to vector retrieval must also embed unchanged chunks that have no vector.
|
|
1048
1235
|
const filesToReindex: string[] = [];
|
|
1049
1236
|
const filesToDelete: string[] = [];
|
|
1050
|
-
const wantsVectors =
|
|
1051
|
-
this.config.effectiveProfile === "hybrid" ||
|
|
1052
|
-
this.config.effectiveProfile === "full";
|
|
1237
|
+
const wantsVectors = this.config.effectiveProfile === "full";
|
|
1053
1238
|
|
|
1054
1239
|
for (const [relPath, info] of currentFiles.entries()) {
|
|
1055
1240
|
const oldHash = this.fileHashes.get(relPath);
|
|
@@ -1072,12 +1257,7 @@ export class HybridSearchIndex {
|
|
|
1072
1257
|
for (const delPath of filesToDelete) {
|
|
1073
1258
|
this.bm25.removeFile(delPath);
|
|
1074
1259
|
this.fileHashes.delete(delPath);
|
|
1075
|
-
|
|
1076
|
-
if (chunkId.startsWith(`${delPath}:`)) {
|
|
1077
|
-
this.chunks.delete(chunkId);
|
|
1078
|
-
this.vectors.delete(chunkId);
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1260
|
+
this.deleteFileChunks(delPath);
|
|
1081
1261
|
}
|
|
1082
1262
|
if (filesToDelete.length > 0) {
|
|
1083
1263
|
this.bm25.recalculateStats();
|
|
@@ -1091,12 +1271,7 @@ export class HybridSearchIndex {
|
|
|
1091
1271
|
for (const relPath of filesToReindex) {
|
|
1092
1272
|
// Clean old chunks for this file
|
|
1093
1273
|
this.bm25.removeFile(relPath);
|
|
1094
|
-
|
|
1095
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1096
|
-
this.chunks.delete(chunkId);
|
|
1097
|
-
this.vectors.delete(chunkId);
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1274
|
+
this.deleteFileChunks(relPath);
|
|
1100
1275
|
|
|
1101
1276
|
const fileInfo = currentFiles.get(relPath);
|
|
1102
1277
|
if (fileInfo) {
|
|
@@ -1111,10 +1286,8 @@ export class HybridSearchIndex {
|
|
|
1111
1286
|
|
|
1112
1287
|
this.bm25.recalculateStats();
|
|
1113
1288
|
|
|
1114
|
-
// Embed new chunks if semantic vector search is enabled (
|
|
1115
|
-
const isVectorEnabled =
|
|
1116
|
-
this.config.effectiveProfile === "hybrid" ||
|
|
1117
|
-
this.config.effectiveProfile === "full";
|
|
1289
|
+
// Embed new chunks if semantic vector search is enabled (full profile)
|
|
1290
|
+
const isVectorEnabled = this.config.effectiveProfile === "full";
|
|
1118
1291
|
if (isVectorEnabled && chunksToEmbed.length > 0) {
|
|
1119
1292
|
const batchSize = this.config.batchSize || 2;
|
|
1120
1293
|
const sleepMs = this.config.sleepBetweenBatchesMs || 50;
|
|
@@ -1200,15 +1373,17 @@ export class HybridSearchIndex {
|
|
|
1200
1373
|
}
|
|
1201
1374
|
}
|
|
1202
1375
|
|
|
1376
|
+
private deleteFileChunks(relPath: string): void {
|
|
1377
|
+
for (const chunkId of this.chunks.idsForFile(relPath)) {
|
|
1378
|
+
this.chunks.delete(chunkId);
|
|
1379
|
+
this.vectors.delete(chunkId);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1203
1383
|
private removeIndexedFile(relPath: string): void {
|
|
1204
1384
|
this.bm25.removeFile(relPath);
|
|
1205
1385
|
this.fileHashes.delete(relPath);
|
|
1206
|
-
|
|
1207
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1208
|
-
this.chunks.delete(chunkId);
|
|
1209
|
-
this.vectors.delete(chunkId);
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1386
|
+
this.deleteFileChunks(relPath);
|
|
1212
1387
|
}
|
|
1213
1388
|
|
|
1214
1389
|
/**
|
|
@@ -1230,6 +1405,14 @@ export class HybridSearchIndex {
|
|
|
1230
1405
|
path.isAbsolute(relPath)
|
|
1231
1406
|
) return;
|
|
1232
1407
|
|
|
1408
|
+
if (this.isPathExcluded(relPath)) {
|
|
1409
|
+
this.removeIndexedFile(relPath);
|
|
1410
|
+
this.dirtyFiles.delete(relPath);
|
|
1411
|
+
this.bm25.recalculateStats();
|
|
1412
|
+
this.scheduleDebouncedSave();
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1233
1416
|
// If a full workspace sync is active, mark dirty and let full sync capture the latest file content
|
|
1234
1417
|
if (this.isIndexing || this.activeSync) {
|
|
1235
1418
|
this.dirtyFiles.add(relPath);
|
|
@@ -1249,18 +1432,20 @@ export class HybridSearchIndex {
|
|
|
1249
1432
|
|
|
1250
1433
|
const task = (async () => {
|
|
1251
1434
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1435
|
+
if (this.isPathExcluded(relPath)) {
|
|
1436
|
+
this.removeIndexedFile(relPath);
|
|
1437
|
+
this.dirtyFiles.delete(relPath);
|
|
1438
|
+
this.bm25.recalculateStats();
|
|
1439
|
+
this.scheduleDebouncedSave();
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1252
1442
|
|
|
1253
1443
|
// Check if file was deleted
|
|
1254
1444
|
if (!fs.existsSync(resolvedPath)) {
|
|
1255
1445
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1256
1446
|
this.bm25.removeFile(relPath);
|
|
1257
1447
|
this.fileHashes.delete(relPath);
|
|
1258
|
-
|
|
1259
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1260
|
-
this.chunks.delete(chunkId);
|
|
1261
|
-
this.vectors.delete(chunkId);
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1448
|
+
this.deleteFileChunks(relPath);
|
|
1264
1449
|
this.dirtyFiles.delete(relPath);
|
|
1265
1450
|
this.bm25.recalculateStats();
|
|
1266
1451
|
this.scheduleDebouncedSave();
|
|
@@ -1319,12 +1504,7 @@ export class HybridSearchIndex {
|
|
|
1319
1504
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1320
1505
|
this.bm25.removeFile(relPath);
|
|
1321
1506
|
this.fileHashes.delete(relPath);
|
|
1322
|
-
|
|
1323
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1324
|
-
this.chunks.delete(chunkId);
|
|
1325
|
-
this.vectors.delete(chunkId);
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1507
|
+
this.deleteFileChunks(relPath);
|
|
1328
1508
|
this.dirtyFiles.delete(relPath);
|
|
1329
1509
|
this.bm25.recalculateStats();
|
|
1330
1510
|
this.scheduleDebouncedSave();
|
|
@@ -1335,13 +1515,11 @@ export class HybridSearchIndex {
|
|
|
1335
1515
|
}
|
|
1336
1516
|
|
|
1337
1517
|
const fileHash = computeHash(content);
|
|
1338
|
-
const wantsVectors =
|
|
1339
|
-
|
|
1340
|
-
this.config.effectiveProfile === "full";
|
|
1341
|
-
const fileChunks = Array.from(this.chunks.values()).filter((chunk) => chunk.filePath === relPath);
|
|
1518
|
+
const wantsVectors = this.config.effectiveProfile === "full";
|
|
1519
|
+
const fileChunks = this.chunks.idsForFile(relPath).map((id) => this.chunks.get(id)!);
|
|
1342
1520
|
const fileVectorsReady = !wantsVectors || fileChunks.every((chunk) => {
|
|
1343
1521
|
const vector = this.vectors.get(chunk.id);
|
|
1344
|
-
return
|
|
1522
|
+
return Boolean(vector && vector.length === this.config.matryoshkaDim);
|
|
1345
1523
|
});
|
|
1346
1524
|
if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath) && fileVectorsReady) {
|
|
1347
1525
|
return;
|
|
@@ -1358,15 +1536,17 @@ export class HybridSearchIndex {
|
|
|
1358
1536
|
}
|
|
1359
1537
|
|
|
1360
1538
|
const newChunks = chunkFile(this.cwd, resolvedPath, content);
|
|
1361
|
-
const currentChunksForFile =
|
|
1539
|
+
const currentChunksForFile = this.chunks.idsForFile(relPath).length;
|
|
1362
1540
|
if (this.chunks.size - currentChunksForFile + newChunks.length > MAX_INDEX_CHUNKS) {
|
|
1363
1541
|
this.skippedOversizedFiles.add(relPath);
|
|
1542
|
+
this.chunkCapSkips.set(relPath, fileHash);
|
|
1364
1543
|
this.removeIndexedFile(relPath);
|
|
1365
1544
|
this.dirtyFiles.delete(relPath);
|
|
1366
1545
|
this.scheduleDebouncedSave();
|
|
1367
1546
|
return;
|
|
1368
1547
|
}
|
|
1369
1548
|
this.skippedOversizedFiles.delete(relPath);
|
|
1549
|
+
this.chunkCapSkips.delete(relPath);
|
|
1370
1550
|
// Map content hash -> vector from existing chunks
|
|
1371
1551
|
const hashToVector = new Map<string, Float32Array>();
|
|
1372
1552
|
for (const chunk of this.chunks.values()) {
|
|
@@ -1414,12 +1594,7 @@ export class HybridSearchIndex {
|
|
|
1414
1594
|
|
|
1415
1595
|
// Atomic in-memory swap:
|
|
1416
1596
|
this.bm25.removeFile(relPath);
|
|
1417
|
-
|
|
1418
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1419
|
-
this.chunks.delete(chunkId);
|
|
1420
|
-
this.vectors.delete(chunkId);
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1597
|
+
this.deleteFileChunks(relPath);
|
|
1423
1598
|
|
|
1424
1599
|
this.fileHashes.set(relPath, fileHash);
|
|
1425
1600
|
for (const chunk of newChunks) {
|
|
@@ -1465,12 +1640,7 @@ export class HybridSearchIndex {
|
|
|
1465
1640
|
) return;
|
|
1466
1641
|
this.bm25.removeFile(relPath);
|
|
1467
1642
|
this.fileHashes.delete(relPath);
|
|
1468
|
-
|
|
1469
|
-
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1470
|
-
this.chunks.delete(chunkId);
|
|
1471
|
-
this.vectors.delete(chunkId);
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1643
|
+
this.deleteFileChunks(relPath);
|
|
1474
1644
|
this.bm25.recalculateStats();
|
|
1475
1645
|
this.generation++;
|
|
1476
1646
|
this.dirtyFiles.add(relPath);
|
|
@@ -1490,6 +1660,12 @@ export class HybridSearchIndex {
|
|
|
1490
1660
|
profile?: SearchProfile;
|
|
1491
1661
|
/** Bounded RRF smoothing constant; defaults to 60. */
|
|
1492
1662
|
rrfK?: number;
|
|
1663
|
+
/**
|
|
1664
|
+
* Return `limit` source hits followed by up to `testLimit` test hits, so test files that restate
|
|
1665
|
+
* behavior in prose cannot crowd source code out. Ignored when the query or file pattern targets tests.
|
|
1666
|
+
*/
|
|
1667
|
+
separateTests?: boolean;
|
|
1668
|
+
testLimit?: number;
|
|
1493
1669
|
} = {},
|
|
1494
1670
|
): Promise<SearchHit[]> {
|
|
1495
1671
|
if (this.config.effectiveProfile === "off") {
|
|
@@ -1516,11 +1692,7 @@ export class HybridSearchIndex {
|
|
|
1516
1692
|
const limit = options.limit || 5;
|
|
1517
1693
|
const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
|
|
1518
1694
|
const matchesFilePattern = (chunk: CodeChunk): boolean =>
|
|
1519
|
-
!options.filePattern ||
|
|
1520
|
-
chunk.filePath
|
|
1521
|
-
.replace(/\\/g, "/")
|
|
1522
|
-
.toLowerCase()
|
|
1523
|
-
.includes(options.filePattern.replace(/\\/g, "/").toLowerCase());
|
|
1695
|
+
!options.filePattern || pathMatchesPattern(chunk.filePath, options.filePattern);
|
|
1524
1696
|
const activeConfig = options.profile
|
|
1525
1697
|
? getSearchConfig(options.profile, this.cwd, this.projectTrusted)
|
|
1526
1698
|
: this.config;
|
|
@@ -1528,7 +1700,7 @@ export class HybridSearchIndex {
|
|
|
1528
1700
|
// 1. BM25 Search (Instant AST-tokenized lexical retrieval)
|
|
1529
1701
|
const bm25Results = this.bm25.search(query, 100, (chunkId) => {
|
|
1530
1702
|
const chunk = this.chunks.get(chunkId);
|
|
1531
|
-
return
|
|
1703
|
+
return Boolean(chunk && matchesFilePattern(chunk));
|
|
1532
1704
|
});
|
|
1533
1705
|
const bm25RankMap = new Map<
|
|
1534
1706
|
string,
|
|
@@ -1542,11 +1714,9 @@ export class HybridSearchIndex {
|
|
|
1542
1714
|
});
|
|
1543
1715
|
});
|
|
1544
1716
|
|
|
1545
|
-
// 2. Vector Search (if active profile is
|
|
1717
|
+
// 2. Vector Search (if active profile is full AND indexing is not actively in progress)
|
|
1546
1718
|
const vectorRankMap = new Map<string, { rank: number; score: number }>();
|
|
1547
|
-
const wantsVectors =
|
|
1548
|
-
activeConfig.effectiveProfile === "hybrid" ||
|
|
1549
|
-
activeConfig.effectiveProfile === "full";
|
|
1719
|
+
const wantsVectors = activeConfig.effectiveProfile === "full";
|
|
1550
1720
|
const isVectorReady =
|
|
1551
1721
|
wantsVectors &&
|
|
1552
1722
|
!this.isIndexing &&
|
|
@@ -1603,12 +1773,19 @@ export class HybridSearchIndex {
|
|
|
1603
1773
|
const rrfVec = vecData ? 1 / (k + vecRank) : 0;
|
|
1604
1774
|
const rrfScore = rrfBm25 + rrfVec;
|
|
1605
1775
|
|
|
1776
|
+
let signal: "hybrid" | "semantic" | "lexical" = "lexical";
|
|
1777
|
+
if (bmData && vecData) {
|
|
1778
|
+
signal = "hybrid";
|
|
1779
|
+
} else if (vecData) {
|
|
1780
|
+
signal = "semantic";
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1606
1783
|
hits.push({
|
|
1607
1784
|
chunk,
|
|
1608
1785
|
rrfScore,
|
|
1609
1786
|
bm25Score: bmData ? bmData.score : 0,
|
|
1610
1787
|
vectorScore: vecData ? vecData.score : 0,
|
|
1611
|
-
signal
|
|
1788
|
+
signal,
|
|
1612
1789
|
bm25Rank: bmData?.rank,
|
|
1613
1790
|
vectorRank: vecData?.rank,
|
|
1614
1791
|
matches: bmData?.matches || [],
|
|
@@ -1617,15 +1794,29 @@ export class HybridSearchIndex {
|
|
|
1617
1794
|
|
|
1618
1795
|
// Sort by combined RRF score descending
|
|
1619
1796
|
hits.sort((a, b) => b.rrfScore - a.rrfScore);
|
|
1797
|
+
const targetsTests = /\b(tests?|specs?)\b/i.test(query) || /test|spec/i.test(options.filePattern ?? "");
|
|
1798
|
+
if (options.separateTests && !targetsTests) {
|
|
1799
|
+
// A test is a test file or a test chunk inside a source file (Rust #[cfg(test)] / #[test] items).
|
|
1800
|
+
const isTest = (hit: SearchHit) => isTestPath(hit.chunk.filePath) || hit.chunk.kind === "test";
|
|
1801
|
+
const source = hits.filter((hit) => !isTest(hit));
|
|
1802
|
+
const tests = hits.filter(isTest);
|
|
1803
|
+
return [...source.slice(0, limit), ...tests.slice(0, options.testLimit ?? 3)];
|
|
1804
|
+
}
|
|
1620
1805
|
return hits.slice(0, limit);
|
|
1621
1806
|
}
|
|
1622
1807
|
|
|
1808
|
+
/** True if a file in the index matches a code_search file_pattern. */
|
|
1809
|
+
public hasIndexedFile(filePattern: string): boolean {
|
|
1810
|
+
for (const filePath of this.chunks.files()) if (pathMatchesPattern(filePath, filePattern)) return true;
|
|
1811
|
+
return false;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1623
1814
|
/**
|
|
1624
1815
|
* Get active index diagnostic status.
|
|
1625
1816
|
*/
|
|
1626
1817
|
public getStatus(): {
|
|
1627
1818
|
profile: SearchProfile;
|
|
1628
|
-
effectiveProfile: "lean" | "
|
|
1819
|
+
effectiveProfile: "lean" | "full" | "off";
|
|
1629
1820
|
fileCount: number;
|
|
1630
1821
|
skippedFiles: number;
|
|
1631
1822
|
chunkCount: number;
|
|
@@ -1637,6 +1828,15 @@ export class HybridSearchIndex {
|
|
|
1637
1828
|
engineState: string;
|
|
1638
1829
|
pipelineDesc: string;
|
|
1639
1830
|
hardwareInfo: string;
|
|
1831
|
+
/** Grammar load problems for languages present in the workspace (their files fall back to a simpler parser). */
|
|
1832
|
+
grammarIssues: Array<{ extensions: string[]; reason: string }>;
|
|
1833
|
+
/** Indexable files the last walk found; the walk stops at MAX_WALK_FILES (walkTruncated). */
|
|
1834
|
+
indexableFiles: number;
|
|
1835
|
+
/** Indexable files left out by the file, byte or chunk caps, by fileTier. */
|
|
1836
|
+
notIndexed: { source: number; test: number; vendored: number };
|
|
1837
|
+
/** Up to 3 top-level directories ("./" for the root) holding the most not-indexed files. */
|
|
1838
|
+
notIndexedDirs: string[];
|
|
1839
|
+
walkTruncated: boolean;
|
|
1640
1840
|
} {
|
|
1641
1841
|
const modelRevision = this.config.modelRevision.slice(0, 12);
|
|
1642
1842
|
const isModelLoaded = this.embedder.isLoaded();
|
|
@@ -1650,22 +1850,13 @@ export class HybridSearchIndex {
|
|
|
1650
1850
|
} else if (this.config.effectiveProfile === "lean") {
|
|
1651
1851
|
modelStatus = "Active (BM25 Engine - 0 MB Model RAM)";
|
|
1652
1852
|
pipelineDesc = "AST-tokenized BM25 Lexical Retrieval";
|
|
1653
|
-
} else if (this.config.effectiveProfile === "hybrid") {
|
|
1654
|
-
if (isModelLoaded) {
|
|
1655
|
-
modelStatus = `Active in RAM (Nomic v1.5 Matryoshka 256-dim, rev ${modelRevision})`;
|
|
1656
|
-
} else if (isModelCached) {
|
|
1657
|
-
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
1658
|
-
} else {
|
|
1659
|
-
modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
|
|
1660
|
-
}
|
|
1661
|
-
pipelineDesc = "Hybrid BM25 + 256-dim Matryoshka Vector Search";
|
|
1662
1853
|
} else {
|
|
1663
1854
|
if (isModelLoaded) {
|
|
1664
|
-
modelStatus = `Active in RAM (
|
|
1855
|
+
modelStatus = `Active in RAM (gte-modernbert-base 768-dim, rev ${modelRevision})`;
|
|
1665
1856
|
} else if (isModelCached) {
|
|
1666
1857
|
modelStatus = `Cached on disk (revision ${modelRevision})`;
|
|
1667
1858
|
} else {
|
|
1668
|
-
modelStatus = `Not downloaded (~
|
|
1859
|
+
modelStatus = `Not downloaded (~147 MB, revision ${modelRevision})`;
|
|
1669
1860
|
}
|
|
1670
1861
|
pipelineDesc = "Full BM25 + 768-dim Semantic Vector Search";
|
|
1671
1862
|
}
|
|
@@ -1682,6 +1873,19 @@ export class HybridSearchIndex {
|
|
|
1682
1873
|
const cpus = os.cpus().length;
|
|
1683
1874
|
const freeMem = (os.freemem() / (1024 * 1024 * 1024)).toFixed(1);
|
|
1684
1875
|
const hardwareInfo = `${cpus} CPUs, ${freeMem} GB free RAM`;
|
|
1876
|
+
const presentExtensions = new Set(Array.from(this.fileHashes.keys(), (file) => path.extname(file).toLowerCase()));
|
|
1877
|
+
const grammarIssues = TreeSitterEngine.getInstance().getLoadIssues()
|
|
1878
|
+
.map((issue) => ({ extensions: issue.extensions.filter((ext) => presentExtensions.has(ext)), reason: issue.reason }))
|
|
1879
|
+
.filter((issue) => issue.extensions.length > 0);
|
|
1880
|
+
const notIndexed = { source: 0, test: 0, vendored: 0 };
|
|
1881
|
+
const notIndexedByDir = new Map<string, number>();
|
|
1882
|
+
for (const { rel: relPath, tier } of this.walkedFiles) {
|
|
1883
|
+
if (this.fileHashes.has(relPath)) continue;
|
|
1884
|
+
notIndexed[(["source", "test", "vendored"] as const)[tier]]++;
|
|
1885
|
+
const dir = relPath.includes("/") ? `${relPath.slice(0, relPath.indexOf("/"))}/` : "./";
|
|
1886
|
+
notIndexedByDir.set(dir, (notIndexedByDir.get(dir) ?? 0) + 1);
|
|
1887
|
+
}
|
|
1888
|
+
const notIndexedDirs = [...notIndexedByDir].sort((a, b) => b[1] - a[1] || compareStrings(a[0], b[0])).slice(0, 3).map(([dir]) => dir);
|
|
1685
1889
|
|
|
1686
1890
|
return {
|
|
1687
1891
|
profile: this.config.profile,
|
|
@@ -1697,6 +1901,11 @@ export class HybridSearchIndex {
|
|
|
1697
1901
|
engineState,
|
|
1698
1902
|
pipelineDesc,
|
|
1699
1903
|
hardwareInfo,
|
|
1904
|
+
grammarIssues,
|
|
1905
|
+
indexableFiles: this.walkedFiles.length,
|
|
1906
|
+
notIndexed,
|
|
1907
|
+
notIndexedDirs,
|
|
1908
|
+
walkTruncated: this.walkedFiles.length >= MAX_WALK_FILES,
|
|
1700
1909
|
};
|
|
1701
1910
|
}
|
|
1702
1911
|
|