@floydous/pi-agent-kernel 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +20 -6
  2. package/CHANGELOG.md +69 -0
  3. package/README.md +23 -20
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +60 -593
  13. package/src/config/kernel_config.ts +46 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +105 -203
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1247 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +190 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +51 -14
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +306 -79
  35. package/src/tools/read_tool.ts +248 -39
  36. package/src/tools/stream_reader.ts +206 -0
  37. package/src/ui/tui_utils.ts +70 -12
@@ -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
- findChunkableFiles,
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
- const EXTRACTOR_GENERATION = "tree-sitter-wasm-v2";
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[];
@@ -76,8 +90,23 @@ function sameFileSnapshot(before: fs.Stats, after: fs.Stats): boolean {
76
90
  return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs;
77
91
  }
78
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
+
79
108
  function isValidChunkKind(kind: string): boolean {
80
- 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);
81
110
  }
82
111
 
83
112
  function assertSafeWorkspaceRelativePath(relativePath: string): void {
@@ -326,12 +355,61 @@ export interface SearchHit {
326
355
  matches: string[];
327
356
  }
328
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
+
329
407
  export class HybridSearchIndex {
330
408
  private cwd: string;
331
409
  private config: SearchConfig;
332
410
  private bm25: BM25Engine = new BM25Engine();
333
411
  private embedder: LocalEmbedder;
334
- private chunks: Map<string, CodeChunk> = new Map();
412
+ private chunks = new ChunkStore();
335
413
  private vectors: Map<string, Float32Array> = new Map();
336
414
  private fileHashes: Map<string, string> = new Map(); // relPath -> SHA256 hash
337
415
  private ignoreConfigHashes: Map<string, string> = new Map(); // ignore config file -> SHA256 hash
@@ -350,7 +428,14 @@ export class HybridSearchIndex {
350
428
  private liveCheckPromise: Promise<boolean> | null = null;
351
429
  private persistedVectorCaches: PersistedVectorCache[] = [];
352
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[] = [];
353
437
  private projectTrusted: boolean;
438
+ private excludedPaths = new Set<string>();
354
439
 
355
440
  constructor(
356
441
  cwd: string,
@@ -360,15 +445,69 @@ export class HybridSearchIndex {
360
445
  this.cwd = cwd;
361
446
  this.projectTrusted = options.projectTrusted === true;
362
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
+ }
363
458
  this.embedder = new LocalEmbedder(this.config);
364
459
  this.loadFromDisk();
365
460
  }
366
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
+
367
506
  public getProfile(): SearchProfile {
368
507
  return this.config.profile;
369
508
  }
370
509
 
371
- public getEffectiveProfile(): "lean" | "hybrid" | "full" | "off" {
510
+ public getEffectiveProfile(): "lean" | "full" | "off" {
372
511
  return this.config.effectiveProfile;
373
512
  }
374
513
 
@@ -420,10 +559,7 @@ export class HybridSearchIndex {
420
559
  public async preloadModel(
421
560
  onProgress?: (msg: string) => void,
422
561
  ): Promise<boolean> {
423
- if (
424
- this.config.effectiveProfile === "hybrid" ||
425
- this.config.effectiveProfile === "full"
426
- ) {
562
+ if (this.config.effectiveProfile === "full") {
427
563
  return this.embedder.initialize(onProgress);
428
564
  }
429
565
  return false;
@@ -445,11 +581,17 @@ export class HybridSearchIndex {
445
581
  return `vectors-${dim}d.bin`;
446
582
  }
447
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. */
448
589
  private getPersistedVectorCaches(data: any): PersistedVectorCache[] {
449
590
  if (Array.isArray(data.vectorCaches)) {
450
591
  return data.vectorCaches.filter(
451
592
  (cache: any): cache is PersistedVectorCache =>
452
593
  cache &&
594
+ cache.model === this.vectorModel() &&
453
595
  Number.isInteger(cache.vectorDim) &&
454
596
  (cache.vectorDim === 256 || cache.vectorDim === 768) &&
455
597
  Array.isArray(cache.vectorChunkIds) &&
@@ -466,27 +608,7 @@ export class HybridSearchIndex {
466
608
  (cache.fileName === "vectors.bin" || cache.fileName === `vectors-${cache.vectorDim}d.bin`),
467
609
  );
468
610
  }
469
-
470
- if (
471
- Number.isInteger(data.vectorDim) &&
472
- (data.vectorDim === 256 || data.vectorDim === 768) &&
473
- Array.isArray(data.vectorChunkIds) &&
474
- data.vectorChunkIds.length <= MAX_INDEX_CHUNKS &&
475
- data.vectorChunkIds.every((id: unknown) => typeof id === "string" && id.length > 0 && id.length <= 4096) &&
476
- new Set(data.vectorChunkIds).size === data.vectorChunkIds.length &&
477
- (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)))) &&
478
- typeof data.vectorHash === "string" &&
479
- /^[0-9a-f]{64}$/i.test(data.vectorHash)
480
- ) {
481
- return [{
482
- vectorDim: data.vectorDim,
483
- vectorChunkIds: data.vectorChunkIds,
484
- vectorChunkHashes: data.vectorChunkHashes,
485
- vectorHash: data.vectorHash,
486
- fileName: "vectors.bin",
487
- }];
488
- }
489
-
611
+ // The single-cache layout (vectorDim at the top level) predates model tags, so it is never from this model.
490
612
  return [];
491
613
  }
492
614
 
@@ -604,11 +726,13 @@ export class HybridSearchIndex {
604
726
  this.persistedVectorCaches = [];
605
727
 
606
728
  for (const chunk of validated.chunks) {
729
+ if (this.isPathExcluded(chunk.filePath)) continue;
607
730
  this.chunks.set(chunk.id, chunk);
608
731
  this.bm25.addChunk(chunk);
609
732
  }
610
733
  this.bm25.recalculateStats();
611
734
  for (const [file, hash] of validated.fileHashes) {
735
+ if (this.isPathExcluded(file)) continue;
612
736
  this.fileHashes.set(file, hash);
613
737
  }
614
738
  for (const [file, hash] of validated.ignoreConfigHashes) {
@@ -616,9 +740,7 @@ export class HybridSearchIndex {
616
740
  }
617
741
 
618
742
  this.persistedVectorCaches = persistedVectorCaches;
619
- const wantsVectors =
620
- this.config.effectiveProfile === "hybrid" ||
621
- this.config.effectiveProfile === "full";
743
+ const wantsVectors = this.config.effectiveProfile === "full";
622
744
  const activeCache = this.persistedVectorCaches.find(
623
745
  (cache) => cache.vectorDim === this.config.matryoshkaDim,
624
746
  );
@@ -701,6 +823,7 @@ export class HybridSearchIndex {
701
823
  if (vectorChunkHashes.some((hash) => !hash)) return;
702
824
  const fileName = this.getVectorCacheFileName(vectorDim);
703
825
  vectorCaches.set(vectorDim, {
826
+ model: this.vectorModel(),
704
827
  vectorDim,
705
828
  vectorChunkIds,
706
829
  vectorChunkHashes,
@@ -881,11 +1004,34 @@ export class HybridSearchIndex {
881
1004
 
882
1005
  private getWorkspaceFileHashes(): Map<string, string> | null {
883
1006
  const hashes = new Map<string, string>();
1007
+ const snapshots = new Map<string, FreshnessSnapshot>();
884
1008
  let workspaceBytes = 0;
885
- const files = findChunkableFiles(this.cwd).sort(compareStrings);
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);
886
1012
  for (const filePath of files) {
887
1013
  const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
1014
+ if (this.isPathExcluded(relPath)) {
1015
+ continue;
1016
+ }
888
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
+ }
889
1035
  const descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
890
1036
  let content: string;
891
1037
  let opened: fs.Stats;
@@ -906,13 +1052,17 @@ export class HybridSearchIndex {
906
1052
  this.skippedOversizedFiles.add(relPath);
907
1053
  continue;
908
1054
  }
1055
+ const hash = computeHash(content);
1056
+ snapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
1057
+ if (this.chunkCapSkips.get(relPath) === hash) continue;
909
1058
  workspaceBytes += actualBytes;
910
- hashes.set(relPath, computeHash(content));
1059
+ hashes.set(relPath, hash);
911
1060
  } catch (error) {
912
1061
  kernelDebug(error);
913
1062
  return null;
914
1063
  }
915
1064
  }
1065
+ this.freshnessSnapshots = snapshots;
916
1066
  return hashes;
917
1067
  }
918
1068
 
@@ -995,24 +1145,31 @@ export class HybridSearchIndex {
995
1145
 
996
1146
  onProgress?.("Scanning workspace files...");
997
1147
 
998
- // Ensure Tree-sitter parsers are warm for languages present in this workspace
999
- const chunkableFiles = findChunkableFiles(this.cwd).sort(compareStrings);
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);
1000
1151
  this.skippedOversizedFiles.clear();
1152
+ this.chunkCapSkips.clear();
1001
1153
  const workspaceExts = new Set<string>();
1002
1154
  for (const f of chunkableFiles) {
1003
1155
  const ext = path.extname(f).toLowerCase();
1004
1156
  if (ext) workspaceExts.add(ext);
1005
1157
  }
1006
- await TreeSitterEngine.getInstance().loadLanguages(Array.from(workspaceExts));
1158
+ // Tree-sitter grammars are only needed when a file must be (re)chunked.
1159
+ let languagesLoaded = false;
1007
1160
 
1008
1161
  // Read each file once and derive both its chunks and hash from that same
1009
1162
  // snapshot. A second read could pair old chunks with a new hash and make
1010
- // the final freshness check falsely accept stale content.
1011
- const currentFiles = new Map<string, { hash: string; chunks: CodeChunk[] }>();
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[] }>();
1012
1166
  let workspaceBytes = 0;
1013
1167
  let workspaceChunks = 0;
1014
1168
  for (const absPath of chunkableFiles) {
1015
1169
  const relPath = path.relative(this.cwd, absPath).replace(/\\/g, "/");
1170
+ if (this.isPathExcluded(relPath)) {
1171
+ continue;
1172
+ }
1016
1173
  try {
1017
1174
  const stat = fs.statSync(absPath);
1018
1175
  if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
@@ -1042,26 +1199,42 @@ export class HybridSearchIndex {
1042
1199
  this.skippedOversizedFiles.add(relPath);
1043
1200
  continue;
1044
1201
  }
1045
- const chunks = chunkFile(this.cwd, absPath, content);
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
+ }
1046
1216
  if (workspaceChunks + chunks.length > MAX_INDEX_CHUNKS) {
1047
1217
  this.skippedOversizedFiles.add(relPath);
1218
+ this.chunkCapSkips.set(relPath, hash);
1219
+ this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
1048
1220
  continue;
1049
1221
  }
1050
1222
  workspaceBytes += actualBytes;
1051
1223
  workspaceChunks += chunks.length;
1052
- currentFiles.set(relPath, { hash: computeHash(content), chunks });
1224
+ selectedFiles.set(relPath, { absPath, hash, chunks });
1225
+ this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
1053
1226
  } catch (error) {
1054
1227
  kernelDebug(error);
1055
1228
  }
1056
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)));
1057
1232
 
1058
1233
  // Identify changed, added, or deleted files. A profile upgrade from BM25
1059
1234
  // to vector retrieval must also embed unchanged chunks that have no vector.
1060
1235
  const filesToReindex: string[] = [];
1061
1236
  const filesToDelete: string[] = [];
1062
- const wantsVectors =
1063
- this.config.effectiveProfile === "hybrid" ||
1064
- this.config.effectiveProfile === "full";
1237
+ const wantsVectors = this.config.effectiveProfile === "full";
1065
1238
 
1066
1239
  for (const [relPath, info] of currentFiles.entries()) {
1067
1240
  const oldHash = this.fileHashes.get(relPath);
@@ -1084,16 +1257,7 @@ export class HybridSearchIndex {
1084
1257
  for (const delPath of filesToDelete) {
1085
1258
  this.bm25.removeFile(delPath);
1086
1259
  this.fileHashes.delete(delPath);
1087
- const toDelete: string[] = [];
1088
- for (const chunkId of this.chunks.keys()) {
1089
- if (chunkId.startsWith(`${delPath}:`)) {
1090
- toDelete.push(chunkId);
1091
- }
1092
- }
1093
- for (const chunkId of toDelete) {
1094
- this.chunks.delete(chunkId);
1095
- this.vectors.delete(chunkId);
1096
- }
1260
+ this.deleteFileChunks(delPath);
1097
1261
  }
1098
1262
  if (filesToDelete.length > 0) {
1099
1263
  this.bm25.recalculateStats();
@@ -1107,16 +1271,7 @@ export class HybridSearchIndex {
1107
1271
  for (const relPath of filesToReindex) {
1108
1272
  // Clean old chunks for this file
1109
1273
  this.bm25.removeFile(relPath);
1110
- const toDelete: string[] = [];
1111
- for (const chunkId of this.chunks.keys()) {
1112
- if (chunkId.startsWith(`${relPath}:`)) {
1113
- toDelete.push(chunkId);
1114
- }
1115
- }
1116
- for (const chunkId of toDelete) {
1117
- this.chunks.delete(chunkId);
1118
- this.vectors.delete(chunkId);
1119
- }
1274
+ this.deleteFileChunks(relPath);
1120
1275
 
1121
1276
  const fileInfo = currentFiles.get(relPath);
1122
1277
  if (fileInfo) {
@@ -1131,10 +1286,8 @@ export class HybridSearchIndex {
1131
1286
 
1132
1287
  this.bm25.recalculateStats();
1133
1288
 
1134
- // Embed new chunks if semantic vector search is enabled (hybrid / full)
1135
- const isVectorEnabled =
1136
- this.config.effectiveProfile === "hybrid" ||
1137
- this.config.effectiveProfile === "full";
1289
+ // Embed new chunks if semantic vector search is enabled (full profile)
1290
+ const isVectorEnabled = this.config.effectiveProfile === "full";
1138
1291
  if (isVectorEnabled && chunksToEmbed.length > 0) {
1139
1292
  const batchSize = this.config.batchSize || 2;
1140
1293
  const sleepMs = this.config.sleepBetweenBatchesMs || 50;
@@ -1220,21 +1373,19 @@ export class HybridSearchIndex {
1220
1373
  }
1221
1374
  }
1222
1375
 
1223
- private removeIndexedFile(relPath: string): void {
1224
- this.bm25.removeFile(relPath);
1225
- this.fileHashes.delete(relPath);
1226
- const toDelete: string[] = [];
1227
- for (const chunkId of this.chunks.keys()) {
1228
- if (chunkId.startsWith(`${relPath}:`)) {
1229
- toDelete.push(chunkId);
1230
- }
1231
- }
1232
- for (const chunkId of toDelete) {
1376
+ private deleteFileChunks(relPath: string): void {
1377
+ for (const chunkId of this.chunks.idsForFile(relPath)) {
1233
1378
  this.chunks.delete(chunkId);
1234
1379
  this.vectors.delete(chunkId);
1235
1380
  }
1236
1381
  }
1237
1382
 
1383
+ private removeIndexedFile(relPath: string): void {
1384
+ this.bm25.removeFile(relPath);
1385
+ this.fileHashes.delete(relPath);
1386
+ this.deleteFileChunks(relPath);
1387
+ }
1388
+
1238
1389
  /**
1239
1390
  * Transactional incremental update of a single file in the index.
1240
1391
  * Chunks only this file, reuses existing vectors for unchanged chunks by content hash,
@@ -1254,6 +1405,14 @@ export class HybridSearchIndex {
1254
1405
  path.isAbsolute(relPath)
1255
1406
  ) return;
1256
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
+
1257
1416
  // If a full workspace sync is active, mark dirty and let full sync capture the latest file content
1258
1417
  if (this.isIndexing || this.activeSync) {
1259
1418
  this.dirtyFiles.add(relPath);
@@ -1273,22 +1432,20 @@ export class HybridSearchIndex {
1273
1432
 
1274
1433
  const task = (async () => {
1275
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
+ }
1276
1442
 
1277
1443
  // Check if file was deleted
1278
1444
  if (!fs.existsSync(resolvedPath)) {
1279
1445
  if (this.fileGenerations.get(relPath) !== currentGen) return;
1280
1446
  this.bm25.removeFile(relPath);
1281
1447
  this.fileHashes.delete(relPath);
1282
- const toDelete: string[] = [];
1283
- for (const chunkId of this.chunks.keys()) {
1284
- if (chunkId.startsWith(`${relPath}:`)) {
1285
- toDelete.push(chunkId);
1286
- }
1287
- }
1288
- for (const chunkId of toDelete) {
1289
- this.chunks.delete(chunkId);
1290
- this.vectors.delete(chunkId);
1291
- }
1448
+ this.deleteFileChunks(relPath);
1292
1449
  this.dirtyFiles.delete(relPath);
1293
1450
  this.bm25.recalculateStats();
1294
1451
  this.scheduleDebouncedSave();
@@ -1347,16 +1504,7 @@ export class HybridSearchIndex {
1347
1504
  if (this.fileGenerations.get(relPath) !== currentGen) return;
1348
1505
  this.bm25.removeFile(relPath);
1349
1506
  this.fileHashes.delete(relPath);
1350
- const toDelete: string[] = [];
1351
- for (const chunkId of this.chunks.keys()) {
1352
- if (chunkId.startsWith(`${relPath}:`)) {
1353
- toDelete.push(chunkId);
1354
- }
1355
- }
1356
- for (const chunkId of toDelete) {
1357
- this.chunks.delete(chunkId);
1358
- this.vectors.delete(chunkId);
1359
- }
1507
+ this.deleteFileChunks(relPath);
1360
1508
  this.dirtyFiles.delete(relPath);
1361
1509
  this.bm25.recalculateStats();
1362
1510
  this.scheduleDebouncedSave();
@@ -1367,10 +1515,8 @@ export class HybridSearchIndex {
1367
1515
  }
1368
1516
 
1369
1517
  const fileHash = computeHash(content);
1370
- const wantsVectors =
1371
- this.config.effectiveProfile === "hybrid" ||
1372
- this.config.effectiveProfile === "full";
1373
- 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)!);
1374
1520
  const fileVectorsReady = !wantsVectors || fileChunks.every((chunk) => {
1375
1521
  const vector = this.vectors.get(chunk.id);
1376
1522
  return Boolean(vector && vector.length === this.config.matryoshkaDim);
@@ -1390,15 +1536,17 @@ export class HybridSearchIndex {
1390
1536
  }
1391
1537
 
1392
1538
  const newChunks = chunkFile(this.cwd, resolvedPath, content);
1393
- const currentChunksForFile = Array.from(this.chunks.keys()).filter((id) => id.startsWith(`${relPath}:`)).length;
1539
+ const currentChunksForFile = this.chunks.idsForFile(relPath).length;
1394
1540
  if (this.chunks.size - currentChunksForFile + newChunks.length > MAX_INDEX_CHUNKS) {
1395
1541
  this.skippedOversizedFiles.add(relPath);
1542
+ this.chunkCapSkips.set(relPath, fileHash);
1396
1543
  this.removeIndexedFile(relPath);
1397
1544
  this.dirtyFiles.delete(relPath);
1398
1545
  this.scheduleDebouncedSave();
1399
1546
  return;
1400
1547
  }
1401
1548
  this.skippedOversizedFiles.delete(relPath);
1549
+ this.chunkCapSkips.delete(relPath);
1402
1550
  // Map content hash -> vector from existing chunks
1403
1551
  const hashToVector = new Map<string, Float32Array>();
1404
1552
  for (const chunk of this.chunks.values()) {
@@ -1446,16 +1594,7 @@ export class HybridSearchIndex {
1446
1594
 
1447
1595
  // Atomic in-memory swap:
1448
1596
  this.bm25.removeFile(relPath);
1449
- const toDelete: string[] = [];
1450
- for (const chunkId of this.chunks.keys()) {
1451
- if (chunkId.startsWith(`${relPath}:`)) {
1452
- toDelete.push(chunkId);
1453
- }
1454
- }
1455
- for (const chunkId of toDelete) {
1456
- this.chunks.delete(chunkId);
1457
- this.vectors.delete(chunkId);
1458
- }
1597
+ this.deleteFileChunks(relPath);
1459
1598
 
1460
1599
  this.fileHashes.set(relPath, fileHash);
1461
1600
  for (const chunk of newChunks) {
@@ -1501,16 +1640,7 @@ export class HybridSearchIndex {
1501
1640
  ) return;
1502
1641
  this.bm25.removeFile(relPath);
1503
1642
  this.fileHashes.delete(relPath);
1504
- const toDelete: string[] = [];
1505
- for (const chunkId of this.chunks.keys()) {
1506
- if (chunkId.startsWith(`${relPath}:`)) {
1507
- toDelete.push(chunkId);
1508
- }
1509
- }
1510
- for (const chunkId of toDelete) {
1511
- this.chunks.delete(chunkId);
1512
- this.vectors.delete(chunkId);
1513
- }
1643
+ this.deleteFileChunks(relPath);
1514
1644
  this.bm25.recalculateStats();
1515
1645
  this.generation++;
1516
1646
  this.dirtyFiles.add(relPath);
@@ -1530,6 +1660,12 @@ export class HybridSearchIndex {
1530
1660
  profile?: SearchProfile;
1531
1661
  /** Bounded RRF smoothing constant; defaults to 60. */
1532
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;
1533
1669
  } = {},
1534
1670
  ): Promise<SearchHit[]> {
1535
1671
  if (this.config.effectiveProfile === "off") {
@@ -1556,11 +1692,7 @@ export class HybridSearchIndex {
1556
1692
  const limit = options.limit || 5;
1557
1693
  const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
1558
1694
  const matchesFilePattern = (chunk: CodeChunk): boolean =>
1559
- !options.filePattern ||
1560
- chunk.filePath
1561
- .replace(/\\/g, "/")
1562
- .toLowerCase()
1563
- .includes(options.filePattern.replace(/\\/g, "/").toLowerCase());
1695
+ !options.filePattern || pathMatchesPattern(chunk.filePath, options.filePattern);
1564
1696
  const activeConfig = options.profile
1565
1697
  ? getSearchConfig(options.profile, this.cwd, this.projectTrusted)
1566
1698
  : this.config;
@@ -1582,11 +1714,9 @@ export class HybridSearchIndex {
1582
1714
  });
1583
1715
  });
1584
1716
 
1585
- // 2. Vector Search (if active profile is hybrid/full AND indexing is not actively in progress)
1717
+ // 2. Vector Search (if active profile is full AND indexing is not actively in progress)
1586
1718
  const vectorRankMap = new Map<string, { rank: number; score: number }>();
1587
- const wantsVectors =
1588
- activeConfig.effectiveProfile === "hybrid" ||
1589
- activeConfig.effectiveProfile === "full";
1719
+ const wantsVectors = activeConfig.effectiveProfile === "full";
1590
1720
  const isVectorReady =
1591
1721
  wantsVectors &&
1592
1722
  !this.isIndexing &&
@@ -1664,15 +1794,29 @@ export class HybridSearchIndex {
1664
1794
 
1665
1795
  // Sort by combined RRF score descending
1666
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
+ }
1667
1805
  return hits.slice(0, limit);
1668
1806
  }
1669
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
+
1670
1814
  /**
1671
1815
  * Get active index diagnostic status.
1672
1816
  */
1673
1817
  public getStatus(): {
1674
1818
  profile: SearchProfile;
1675
- effectiveProfile: "lean" | "hybrid" | "full" | "off";
1819
+ effectiveProfile: "lean" | "full" | "off";
1676
1820
  fileCount: number;
1677
1821
  skippedFiles: number;
1678
1822
  chunkCount: number;
@@ -1684,6 +1828,15 @@ export class HybridSearchIndex {
1684
1828
  engineState: string;
1685
1829
  pipelineDesc: string;
1686
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;
1687
1840
  } {
1688
1841
  const modelRevision = this.config.modelRevision.slice(0, 12);
1689
1842
  const isModelLoaded = this.embedder.isLoaded();
@@ -1697,22 +1850,13 @@ export class HybridSearchIndex {
1697
1850
  } else if (this.config.effectiveProfile === "lean") {
1698
1851
  modelStatus = "Active (BM25 Engine - 0 MB Model RAM)";
1699
1852
  pipelineDesc = "AST-tokenized BM25 Lexical Retrieval";
1700
- } else if (this.config.effectiveProfile === "hybrid") {
1701
- if (isModelLoaded) {
1702
- modelStatus = `Active in RAM (Nomic v1.5 Matryoshka 256-dim, rev ${modelRevision})`;
1703
- } else if (isModelCached) {
1704
- modelStatus = `Cached on disk (revision ${modelRevision})`;
1705
- } else {
1706
- modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
1707
- }
1708
- pipelineDesc = "Hybrid BM25 + 256-dim Matryoshka Vector Search";
1709
1853
  } else {
1710
1854
  if (isModelLoaded) {
1711
- modelStatus = `Active in RAM (Nomic v1.5 768-dim, rev ${modelRevision})`;
1855
+ modelStatus = `Active in RAM (gte-modernbert-base 768-dim, rev ${modelRevision})`;
1712
1856
  } else if (isModelCached) {
1713
1857
  modelStatus = `Cached on disk (revision ${modelRevision})`;
1714
1858
  } else {
1715
- modelStatus = `Not downloaded (~135 MB, revision ${modelRevision})`;
1859
+ modelStatus = `Not downloaded (~147 MB, revision ${modelRevision})`;
1716
1860
  }
1717
1861
  pipelineDesc = "Full BM25 + 768-dim Semantic Vector Search";
1718
1862
  }
@@ -1729,6 +1873,19 @@ export class HybridSearchIndex {
1729
1873
  const cpus = os.cpus().length;
1730
1874
  const freeMem = (os.freemem() / (1024 * 1024 * 1024)).toFixed(1);
1731
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);
1732
1889
 
1733
1890
  return {
1734
1891
  profile: this.config.profile,
@@ -1744,6 +1901,11 @@ export class HybridSearchIndex {
1744
1901
  engineState,
1745
1902
  pipelineDesc,
1746
1903
  hardwareInfo,
1904
+ grammarIssues,
1905
+ indexableFiles: this.walkedFiles.length,
1906
+ notIndexed,
1907
+ notIndexedDirs,
1908
+ walkTruncated: this.walkedFiles.length >= MAX_WALK_FILES,
1747
1909
  };
1748
1910
  }
1749
1911