@floydous/pi-agent-kernel 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -60,6 +60,8 @@ interface PersistedIndexSnapshot {
60
60
  chunkFiles: Map<string, string>;
61
61
  ignoreConfigHashes: Map<string, string>;
62
62
  staleFiles: Set<string>;
63
+ freshnessSnapshots: Map<string, FreshnessSnapshot>;
64
+ fileBytes: Map<string, number>;
63
65
  }
64
66
 
65
67
  function isRecord(value: unknown): value is Record<string, unknown> {
@@ -228,6 +230,8 @@ export function validatePersistedIndex(
228
230
 
229
231
  const validatedChunks: CodeChunk[] = [];
230
232
  const staleFiles = new Set<string>();
233
+ const freshnessSnapshots = new Map<string, FreshnessSnapshot>();
234
+ const fileBytes = new Map<string, number>();
231
235
  let validatedWorkspaceBytes = 0;
232
236
  for (const [filePath, expectedHash] of fileHashes) {
233
237
  const fileChunks = chunksByFile.get(filePath) || [];
@@ -298,7 +302,8 @@ export function validatePersistedIndex(
298
302
  if (descriptor !== undefined) fs.closeSync(descriptor);
299
303
  }
300
304
 
301
- validatedWorkspaceBytes += Buffer.byteLength(source, "utf8");
305
+ const sourceBytes = Buffer.byteLength(source, "utf8");
306
+ validatedWorkspaceBytes += sourceBytes;
302
307
  if (validatedWorkspaceBytes > MAX_INDEX_WORKSPACE_BYTES) {
303
308
  throw new Error("Persisted workspace exceeds index size limit");
304
309
  }
@@ -322,6 +327,8 @@ export function validatePersistedIndex(
322
327
  chunk.absolutePath = absolutePath;
323
328
  validatedChunks.push(chunk);
324
329
  }
330
+ freshnessSnapshots.set(filePath, freshnessSnapshot(sourceStat, expectedHash, sourceBytes));
331
+ fileBytes.set(filePath, sourceBytes);
325
332
  }
326
333
 
327
334
  const ignoreConfigHashes = new Map<string, string>();
@@ -341,7 +348,16 @@ export function validatePersistedIndex(
341
348
  }
342
349
  }
343
350
 
344
- return { chunks: validatedChunks, fileHashes, chunkHashes, chunkFiles, ignoreConfigHashes, staleFiles };
351
+ return {
352
+ chunks: validatedChunks,
353
+ fileHashes,
354
+ chunkHashes,
355
+ chunkFiles,
356
+ ignoreConfigHashes,
357
+ staleFiles,
358
+ freshnessSnapshots,
359
+ fileBytes,
360
+ };
345
361
  }
346
362
 
347
363
  export interface SearchHit {
@@ -431,6 +447,7 @@ export class HybridSearchIndex {
431
447
  /** relPath -> hash of content skipped by MAX_INDEX_CHUNKS; freshness checks cannot count chunks, so they match this. */
432
448
  private chunkCapSkips = new Map<string, string>();
433
449
  private freshnessSnapshots = new Map<string, FreshnessSnapshot>();
450
+ private fileBytes = new Map<string, number>();
434
451
  private walkCache = new WorkspaceWalkCache();
435
452
  /** Every indexable file of the last walk, in priority order (up to MAX_WALK_FILES), for coverage reporting. */
436
453
  private walkedFiles: readonly RankedFile[] = [];
@@ -724,6 +741,8 @@ export class HybridSearchIndex {
724
741
  this.ignoreConfigHashes.clear();
725
742
  this.vectors.clear();
726
743
  this.persistedVectorCaches = [];
744
+ this.freshnessSnapshots.clear();
745
+ this.fileBytes.clear();
727
746
 
728
747
  for (const chunk of validated.chunks) {
729
748
  if (this.isPathExcluded(chunk.filePath)) continue;
@@ -735,6 +754,14 @@ export class HybridSearchIndex {
735
754
  if (this.isPathExcluded(file)) continue;
736
755
  this.fileHashes.set(file, hash);
737
756
  }
757
+ for (const [file, snapshot] of validated.freshnessSnapshots) {
758
+ if (this.isPathExcluded(file)) continue;
759
+ this.freshnessSnapshots.set(file, snapshot);
760
+ }
761
+ for (const [file, bytes] of validated.fileBytes) {
762
+ if (this.isPathExcluded(file)) continue;
763
+ this.fileBytes.set(file, bytes);
764
+ }
738
765
  for (const [file, hash] of validated.ignoreConfigHashes) {
739
766
  this.ignoreConfigHashes.set(file, hash);
740
767
  }
@@ -847,7 +874,7 @@ export class HybridSearchIndex {
847
874
 
848
875
  writeFileSyncAtomic(
849
876
  this.getIndexFilePath(),
850
- JSON.stringify(indexData, null, 2),
877
+ JSON.stringify(indexData),
851
878
  );
852
879
  } catch (err) {
853
880
  console.error("[Search Index] Failed saving cache:", err);
@@ -1130,6 +1157,9 @@ export class HybridSearchIndex {
1130
1157
  if (this.config.effectiveProfile === "off") {
1131
1158
  return { chunkCount: 0, fileCount: 0, indexedCount: 0 };
1132
1159
  }
1160
+ if (forceReindex) {
1161
+ this.embedder.resetFailureBackoff();
1162
+ }
1133
1163
  if (signal?.aborted || this.generation !== syncGeneration) {
1134
1164
  return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
1135
1165
  }
@@ -1171,6 +1201,36 @@ export class HybridSearchIndex {
1171
1201
  continue;
1172
1202
  }
1173
1203
  try {
1204
+ // Fast path: reuse verified chunks/hash from loadFromDisk() or a prior sync
1205
+ // when the file's non-racy stat snapshot is unchanged.
1206
+ if (!forceReindex) {
1207
+ const known = this.freshnessSnapshots.get(relPath);
1208
+ if (known && !known.racy) {
1209
+ const currentStat = fs.lstatSync(absPath);
1210
+ if (currentStat.isFile() && sameFileSnapshot(known.stats, currentStat)) {
1211
+ if (currentStat.size > MAX_INDEX_FILE_BYTES || workspaceBytes + known.bytes > MAX_INDEX_WORKSPACE_BYTES) {
1212
+ this.skippedOversizedFiles.add(relPath);
1213
+ continue;
1214
+ }
1215
+ const cachedIds = this.fileHashes.get(relPath) === known.hash
1216
+ ? this.chunks.idsForFile(relPath)
1217
+ : [];
1218
+ if (cachedIds.length > 0) {
1219
+ const chunks = cachedIds.map((id) => this.chunks.get(id)!);
1220
+ if (workspaceChunks + chunks.length > MAX_INDEX_CHUNKS) {
1221
+ this.skippedOversizedFiles.add(relPath);
1222
+ this.chunkCapSkips.set(relPath, known.hash);
1223
+ continue;
1224
+ }
1225
+ workspaceBytes += known.bytes;
1226
+ workspaceChunks += chunks.length;
1227
+ selectedFiles.set(relPath, { absPath, hash: known.hash, chunks });
1228
+ this.fileBytes.set(relPath, known.bytes);
1229
+ continue;
1230
+ }
1231
+ }
1232
+ }
1233
+ }
1174
1234
  const stat = fs.statSync(absPath);
1175
1235
  if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
1176
1236
  this.skippedOversizedFiles.add(relPath);
@@ -1222,6 +1282,7 @@ export class HybridSearchIndex {
1222
1282
  workspaceBytes += actualBytes;
1223
1283
  workspaceChunks += chunks.length;
1224
1284
  selectedFiles.set(relPath, { absPath, hash, chunks });
1285
+ this.fileBytes.set(relPath, actualBytes);
1225
1286
  this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
1226
1287
  } catch (error) {
1227
1288
  kernelDebug(error);
@@ -1257,6 +1318,8 @@ export class HybridSearchIndex {
1257
1318
  for (const delPath of filesToDelete) {
1258
1319
  this.bm25.removeFile(delPath);
1259
1320
  this.fileHashes.delete(delPath);
1321
+ this.fileBytes.delete(delPath);
1322
+ this.freshnessSnapshots.delete(delPath);
1260
1323
  this.deleteFileChunks(delPath);
1261
1324
  }
1262
1325
  if (filesToDelete.length > 0) {
@@ -1383,6 +1446,8 @@ export class HybridSearchIndex {
1383
1446
  private removeIndexedFile(relPath: string): void {
1384
1447
  this.bm25.removeFile(relPath);
1385
1448
  this.fileHashes.delete(relPath);
1449
+ this.fileBytes.delete(relPath);
1450
+ this.freshnessSnapshots.delete(relPath);
1386
1451
  this.deleteFileChunks(relPath);
1387
1452
  }
1388
1453
 
@@ -1443,9 +1508,7 @@ export class HybridSearchIndex {
1443
1508
  // Check if file was deleted
1444
1509
  if (!fs.existsSync(resolvedPath)) {
1445
1510
  if (this.fileGenerations.get(relPath) !== currentGen) return;
1446
- this.bm25.removeFile(relPath);
1447
- this.fileHashes.delete(relPath);
1448
- this.deleteFileChunks(relPath);
1511
+ this.removeIndexedFile(relPath);
1449
1512
  this.dirtyFiles.delete(relPath);
1450
1513
  this.bm25.recalculateStats();
1451
1514
  this.scheduleDebouncedSave();
@@ -1454,6 +1517,8 @@ export class HybridSearchIndex {
1454
1517
 
1455
1518
  // Read file content with bounded allocation and TOCTOU protection
1456
1519
  let content: string;
1520
+ let opened: fs.Stats;
1521
+ let actualBytes: number;
1457
1522
  try {
1458
1523
  const stat = fs.statSync(resolvedPath);
1459
1524
  if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
@@ -1466,9 +1531,17 @@ export class HybridSearchIndex {
1466
1531
  let workspaceBytes = 0;
1467
1532
  for (const indexedPath of this.fileHashes.keys()) {
1468
1533
  if (indexedPath === relPath) continue;
1534
+ const tracked = this.fileBytes.get(indexedPath);
1535
+ if (tracked !== undefined) {
1536
+ workspaceBytes += tracked;
1537
+ continue;
1538
+ }
1469
1539
  try {
1470
1540
  const indexedStat = fs.statSync(path.join(this.cwd, indexedPath));
1471
- if (indexedStat.isFile()) workspaceBytes += indexedStat.size;
1541
+ if (indexedStat.isFile()) {
1542
+ this.fileBytes.set(indexedPath, indexedStat.size);
1543
+ workspaceBytes += indexedStat.size;
1544
+ }
1472
1545
  } catch {}
1473
1546
  }
1474
1547
  if (workspaceBytes + stat.size > MAX_INDEX_WORKSPACE_BYTES) {
@@ -1479,7 +1552,6 @@ export class HybridSearchIndex {
1479
1552
  return;
1480
1553
  }
1481
1554
  const descriptor = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
1482
- let opened: fs.Stats;
1483
1555
  try {
1484
1556
  opened = fs.fstatSync(descriptor);
1485
1557
  if (!opened.isFile() || opened.size > MAX_INDEX_FILE_BYTES) throw new Error(`Invalid workspace file: ${relPath}`);
@@ -1491,7 +1563,8 @@ export class HybridSearchIndex {
1491
1563
  if (!sameFileSnapshot(opened, afterRead)) {
1492
1564
  throw new Error(`Workspace file changed while reading: ${relPath}`);
1493
1565
  }
1494
- if (Buffer.byteLength(content, "utf8") > MAX_INDEX_FILE_BYTES) {
1566
+ actualBytes = Buffer.byteLength(content, "utf8");
1567
+ if (actualBytes > MAX_INDEX_FILE_BYTES || workspaceBytes + actualBytes > MAX_INDEX_WORKSPACE_BYTES) {
1495
1568
  this.skippedOversizedFiles.add(relPath);
1496
1569
  this.removeIndexedFile(relPath);
1497
1570
  this.dirtyFiles.delete(relPath);
@@ -1502,9 +1575,7 @@ export class HybridSearchIndex {
1502
1575
  if (err?.code === "ENOENT") {
1503
1576
  // File was removed concurrently between existsSync and readFileSync
1504
1577
  if (this.fileGenerations.get(relPath) !== currentGen) return;
1505
- this.bm25.removeFile(relPath);
1506
- this.fileHashes.delete(relPath);
1507
- this.deleteFileChunks(relPath);
1578
+ this.removeIndexedFile(relPath);
1508
1579
  this.dirtyFiles.delete(relPath);
1509
1580
  this.bm25.recalculateStats();
1510
1581
  this.scheduleDebouncedSave();
@@ -1522,6 +1593,8 @@ export class HybridSearchIndex {
1522
1593
  return Boolean(vector && vector.length === this.config.matryoshkaDim);
1523
1594
  });
1524
1595
  if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath) && fileVectorsReady) {
1596
+ this.fileBytes.set(relPath, actualBytes);
1597
+ this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, fileHash, actualBytes));
1525
1598
  return;
1526
1599
  }
1527
1600
 
@@ -1547,24 +1620,25 @@ export class HybridSearchIndex {
1547
1620
  }
1548
1621
  this.skippedOversizedFiles.delete(relPath);
1549
1622
  this.chunkCapSkips.delete(relPath);
1550
- // Map content hash -> vector from existing chunks
1551
- const hashToVector = new Map<string, Float32Array>();
1552
- for (const chunk of this.chunks.values()) {
1553
- const vec = this.vectors.get(chunk.id);
1554
- if (vec && vec.length === this.config.matryoshkaDim) {
1555
- hashToVector.set(chunk.hash, vec);
1556
- }
1557
- }
1558
1623
 
1559
1624
  const newVectors = new Map<string, Float32Array>();
1560
1625
  const missingChunks: CodeChunk[] = [];
1561
-
1562
- for (const chunk of newChunks) {
1563
- const reused = hashToVector.get(chunk.hash);
1564
- if (reused) {
1565
- newVectors.set(chunk.id, reused);
1566
- } else if (wantsVectors) {
1567
- missingChunks.push(chunk);
1626
+ if (wantsVectors) {
1627
+ // Map content hash -> vector from existing chunks
1628
+ const hashToVector = new Map<string, Float32Array>();
1629
+ for (const chunk of this.chunks.values()) {
1630
+ const vec = this.vectors.get(chunk.id);
1631
+ if (vec && vec.length === this.config.matryoshkaDim) {
1632
+ hashToVector.set(chunk.hash, vec);
1633
+ }
1634
+ }
1635
+ for (const chunk of newChunks) {
1636
+ const reused = hashToVector.get(chunk.hash);
1637
+ if (reused) {
1638
+ newVectors.set(chunk.id, reused);
1639
+ } else {
1640
+ missingChunks.push(chunk);
1641
+ }
1568
1642
  }
1569
1643
  }
1570
1644
 
@@ -1597,6 +1671,8 @@ export class HybridSearchIndex {
1597
1671
  this.deleteFileChunks(relPath);
1598
1672
 
1599
1673
  this.fileHashes.set(relPath, fileHash);
1674
+ this.fileBytes.set(relPath, actualBytes);
1675
+ this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, fileHash, actualBytes));
1600
1676
  for (const chunk of newChunks) {
1601
1677
  this.chunks.set(chunk.id, chunk);
1602
1678
  this.bm25.addChunk(chunk);
@@ -1640,6 +1716,8 @@ export class HybridSearchIndex {
1640
1716
  ) return;
1641
1717
  this.bm25.removeFile(relPath);
1642
1718
  this.fileHashes.delete(relPath);
1719
+ this.fileBytes.delete(relPath);
1720
+ this.freshnessSnapshots.delete(relPath);
1643
1721
  this.deleteFileChunks(relPath);
1644
1722
  this.bm25.recalculateStats();
1645
1723
  this.generation++;
@@ -9,6 +9,7 @@ import {
9
9
  removeGlobalKernelConfigKey,
10
10
  removeProjectKernelConfigKey,
11
11
  getGlobalRawConfig,
12
+ getProjectRawConfig,
12
13
  mergeDeep,
13
14
  type KernelConfig,
14
15
  type KernelConfigOverrides,
@@ -46,6 +47,7 @@ export interface UnifiedModalOptions {
46
47
  triggerBackgroundIndexing?: (index: any, ctx: any, isFullSync?: boolean) => void;
47
48
  };
48
49
  ctx?: any;
50
+ keybindings?: { matches?: (data: string, keybinding: string) => boolean };
49
51
  }
50
52
 
51
53
  class SearchInput {
@@ -57,8 +59,10 @@ class SearchInput {
57
59
  this.value = v;
58
60
  }
59
61
  handleInput(data: string): void {
60
- if (data === "\x7f" || data === "\b") {
62
+ if (data === "\x7f" || data === "\b" || /^\x1b\[127(?:;1(?::[12])?)?u$/.test(data)) {
61
63
  this.value = this.value.slice(0, -1);
64
+ } else if (matchesKey(data, "space")) {
65
+ this.value += " ";
62
66
  } else if (data.length === 1 && data >= " " && data <= "~") {
63
67
  this.value += data;
64
68
  }
@@ -120,6 +124,7 @@ export class UnifiedControlModal implements Focusable {
120
124
  // TAB 1: RETRIEVAL ENGINE STATE
121
125
  // -------------------------------------------------------------------------
122
126
  private initialProfile: SearchProfile;
127
+ private selectedProfile: SearchProfile;
123
128
  private profileSelectedIndex = 0;
124
129
  private profileItems: Array<{
125
130
  id: string;
@@ -203,8 +208,8 @@ export class UnifiedControlModal implements Focusable {
203
208
 
204
209
  // Initial profile setup
205
210
  this.initialProfile = index?.getProfile ? index.getProfile() : "lean";
206
- const activeProfileName = this.initialProfile === "hybrid" ? "full" : this.initialProfile;
207
- const pIdx = this.profileItems.findIndex((item) => item.profile === activeProfileName);
211
+ this.selectedProfile = this.initialProfile === "hybrid" ? "full" : this.initialProfile;
212
+ const pIdx = this.profileItems.findIndex((item) => item.profile === this.selectedProfile);
208
213
  if (pIdx >= 0) this.profileSelectedIndex = pIdx;
209
214
 
210
215
  // Excluded paths setup
@@ -228,26 +233,41 @@ export class UnifiedControlModal implements Focusable {
228
233
  : loadKernelConfig(this.currentCwd);
229
234
 
230
235
  const globalRaw = getGlobalRawConfig();
236
+ const projectTrusted = this.options.ctx?.isProjectTrusted?.() !== false;
237
+ const projectRaw = projectTrusted ? getProjectRawConfig(this.currentCwd) : {};
238
+ const isOverriddenByProject = (section: string, key: string): boolean =>
239
+ projectRaw[section]?.[key] !== undefined;
231
240
  const checkIsGlobal = (id: string): boolean => {
232
- if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
233
- if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
234
- if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
235
- if (id === "editing") return globalRaw.editing?.mode !== undefined;
236
- if (id === "read_mode") return globalRaw.editing?.read_mode !== undefined;
237
- if (id === "normalize_dots") return globalRaw.editing?.normalize_fullwidth_dots !== undefined;
238
- if (id === "guidance") return globalRaw.instructions?.enabled !== undefined;
239
- if (id === "host_environment") return globalRaw.instructions?.host_environment !== undefined;
240
- if (id === "pi_docs") return globalRaw.instructions?.pi_docs !== undefined;
241
- if (id === "footer") return globalRaw.ui?.enable_pastel_footer !== undefined;
241
+ if (id === "profile") return !isOverriddenByProject("retrieval", "default_profile") && globalRaw.retrieval?.default_profile !== undefined;
242
+ if (id === "epistemic") return !isOverriddenByProject("safety", "enable_epistemic_guard") && globalRaw.safety?.enable_epistemic_guard !== undefined;
243
+ if (id === "max_lines") return !isOverriddenByProject("safety", "max_lines") && globalRaw.safety?.max_lines !== undefined;
244
+ if (id === "editing") return !isOverriddenByProject("editing", "mode") && globalRaw.editing?.mode !== undefined;
245
+ if (id === "read_mode") return !isOverriddenByProject("editing", "read_mode") && globalRaw.editing?.read_mode !== undefined;
246
+ if (id === "normalize_dots") return !isOverriddenByProject("editing", "normalize_fullwidth_dots") && globalRaw.editing?.normalize_fullwidth_dots !== undefined;
247
+ if (id === "syntax_gate") return !isOverriddenByProject("editing", "syntax_gate") && globalRaw.editing?.syntax_gate !== undefined;
248
+ if (id === "guidance") return !isOverriddenByProject("instructions", "enabled") && globalRaw.instructions?.enabled !== undefined;
249
+ if (id === "host_environment") return !isOverriddenByProject("instructions", "host_environment") && globalRaw.instructions?.host_environment !== undefined;
250
+ if (id === "pi_docs") return !isOverriddenByProject("instructions", "pi_docs") && globalRaw.instructions?.pi_docs !== undefined;
251
+ if (id === "footer") return !isOverriddenByProject("ui", "enable_pastel_footer") && globalRaw.ui?.enable_pastel_footer !== undefined;
242
252
  return false;
243
253
  };
244
254
 
255
+ const normalizedProfile = currentConfig.retrieval.default_profile === "hybrid"
256
+ ? "full"
257
+ : currentConfig.retrieval.default_profile;
258
+ if (!this.index?.getProfile) {
259
+ this.initialProfile = normalizedProfile;
260
+ this.selectedProfile = normalizedProfile;
261
+ const pIdx = this.profileItems.findIndex((item) => item.profile === this.selectedProfile);
262
+ if (pIdx >= 0) this.profileSelectedIndex = pIdx;
263
+ }
264
+
245
265
  this.settingsItems = [
246
266
  {
247
267
  category: "Retrieval & Exploration",
248
268
  id: "profile",
249
269
  label: "Retrieval Engine Profile",
250
- currentValue: currentConfig.retrieval.default_profile,
270
+ currentValue: normalizedProfile,
251
271
  values: ["auto", "lean", "full", "off"],
252
272
  isGlobal: checkIsGlobal("profile"),
253
273
  descriptions: {
@@ -255,7 +275,7 @@ export class UnifiedControlModal implements Focusable {
255
275
  lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval.",
256
276
  full: "Full profile: BM25 keyword index fused with 768d gte-modernbert-base code embeddings (~147 MB model).",
257
277
  hybrid: "Hybrid: alias of the full profile.",
258
- off: "Off profile: Retrieval subsystem disabled. Searches return empty results.",
278
+ off: "Off profile: Retrieval subsystem disabled. code_search returns an error.",
259
279
  },
260
280
  },
261
281
  {
@@ -320,6 +340,18 @@ export class UnifiedControlModal implements Focusable {
320
340
  disabled: "Fullwidth dot normalization disabled: Preserves Unicode fullwidth full stop verbatim.",
321
341
  },
322
342
  },
343
+ {
344
+ category: "Editing Engine",
345
+ id: "syntax_gate",
346
+ label: "Post-Edit Syntax Gate",
347
+ currentValue: currentConfig.editing.syntax_gate ?? "warn",
348
+ values: ["warn", "block"],
349
+ isGlobal: checkIsGlobal("syntax_gate"),
350
+ descriptions: {
351
+ warn: "Warn mode (default): Applies edits and reports syntax errors immediately in tool output.",
352
+ block: "Block mode: Rejects edits that fail candidate syntax validation before writing to disk.",
353
+ },
354
+ },
323
355
  {
324
356
  category: "System Guidance & UI",
325
357
  id: "guidance",
@@ -407,6 +439,17 @@ export class UnifiedControlModal implements Focusable {
407
439
  this.settingsSelectedIndex = 0;
408
440
  }
409
441
 
442
+ private syncProfileSelection(profile: SearchProfile): void {
443
+ const normalized = profile === "hybrid" ? "full" : profile;
444
+ this.selectedProfile = normalized;
445
+ const pIdx = this.profileItems.findIndex((pi) => pi.profile === normalized);
446
+ if (pIdx >= 0) this.profileSelectedIndex = pIdx;
447
+ const profileSetting = this.settingsItems.find((s) => s.id === "profile");
448
+ if (profileSetting) {
449
+ profileSetting.currentValue = normalized;
450
+ }
451
+ }
452
+
410
453
  private activateSettingItem(): void {
411
454
  const item = this.filteredSettingsItems[this.settingsSelectedIndex];
412
455
  if (!item || !item.values || item.values.length === 0) return;
@@ -416,9 +459,7 @@ export class UnifiedControlModal implements Focusable {
416
459
 
417
460
  // If profile setting was cycled in Tab 0, keep Tab 1 in sync
418
461
  if (item.id === "profile") {
419
- const newProf = item.currentValue as SearchProfile;
420
- const pIdx = this.profileItems.findIndex((pi) => pi.profile === (newProf === "hybrid" ? "full" : newProf));
421
- if (pIdx >= 0) this.profileSelectedIndex = pIdx;
462
+ this.syncProfileSelection(item.currentValue as SearchProfile);
422
463
  }
423
464
  }
424
465
 
@@ -447,6 +488,8 @@ export class UnifiedControlModal implements Focusable {
447
488
  patch.editing = { read_mode: value as "auto" | "plain" | "anchored" };
448
489
  } else if (id === "normalize_dots") {
449
490
  patch.editing = { normalize_fullwidth_dots: value === "enabled" };
491
+ } else if (id === "syntax_gate") {
492
+ patch.editing = { syntax_gate: value as "warn" | "block" };
450
493
  } else if (id === "guidance") {
451
494
  patch.instructions = { enabled: value === "enabled" };
452
495
  } else if (id === "host_environment") {
@@ -472,6 +515,7 @@ export class UnifiedControlModal implements Focusable {
472
515
  case "editing": return { section: "editing", key: "mode" };
473
516
  case "read_mode": return { section: "editing", key: "read_mode" };
474
517
  case "normalize_dots": return { section: "editing", key: "normalize_fullwidth_dots" };
518
+ case "syntax_gate": return { section: "editing", key: "syntax_gate" };
475
519
  case "guidance": return { section: "instructions", key: "enabled" };
476
520
  case "host_environment": return { section: "instructions", key: "host_environment" };
477
521
  case "pi_docs": return { section: "instructions", key: "pi_docs" };
@@ -732,13 +776,17 @@ export class UnifiedControlModal implements Focusable {
732
776
  return false;
733
777
  }
734
778
 
779
+ private matchesBinding(data: string, keybinding: string, fallbackKey: string): boolean {
780
+ return Boolean(this.options.keybindings?.matches?.(data, keybinding)) || matchesKey(data, fallbackKey);
781
+ }
782
+
735
783
  // =========================================================================
736
784
  // KEYBOARD INPUT DISPATCHER
737
785
  // =========================================================================
738
786
  async handleInput(data: string): Promise<void> {
739
787
  // Universal dismiss on Esc / q
740
788
  if (
741
- matchesKey(data, "escape") ||
789
+ this.matchesBinding(data, "tui.select.cancel", "escape") ||
742
790
  matchesKey(data, "q") ||
743
791
  matchesKey(data, "ctrl+c")
744
792
  ) {
@@ -775,12 +823,15 @@ export class UnifiedControlModal implements Focusable {
775
823
  this.tui?.requestRender?.();
776
824
  return;
777
825
  }
778
- if (matchesKey(data, "return") || (data === " " && this.searchInput.getValue().length === 0)) {
826
+ if (
827
+ this.matchesBinding(data, "tui.select.confirm", "return") ||
828
+ (matchesKey(data, "space") && this.searchInput.getValue().length === 0)
829
+ ) {
779
830
  this.activateSettingItem();
780
831
  this.tui?.requestRender?.();
781
832
  return;
782
833
  }
783
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
834
+ if (this.matchesBinding(data, "tui.select.up", "up") || matchesKey(data, "k")) {
784
835
  if (this.filteredSettingsItems.length > 0) {
785
836
  this.settingsSelectedIndex =
786
837
  this.settingsSelectedIndex === 0
@@ -790,7 +841,7 @@ export class UnifiedControlModal implements Focusable {
790
841
  }
791
842
  return;
792
843
  }
793
- if (matchesKey(data, "down") || matchesKey(data, "j")) {
844
+ if (this.matchesBinding(data, "tui.select.down", "down") || matchesKey(data, "j")) {
794
845
  if (this.filteredSettingsItems.length > 0) {
795
846
  this.settingsSelectedIndex =
796
847
  this.settingsSelectedIndex === this.filteredSettingsItems.length - 1
@@ -821,26 +872,26 @@ export class UnifiedControlModal implements Focusable {
821
872
  return;
822
873
  }
823
874
 
824
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
875
+ if (this.matchesBinding(data, "tui.select.up", "up") || matchesKey(data, "k")) {
825
876
  this.profileSelectedIndex =
826
877
  (this.profileSelectedIndex - 1 + this.profileItems.length) % this.profileItems.length;
827
878
  this.tui?.requestRender?.();
828
879
  return;
829
880
  }
830
881
 
831
- if (matchesKey(data, "down") || matchesKey(data, "j")) {
882
+ if (this.matchesBinding(data, "tui.select.down", "down") || matchesKey(data, "j")) {
832
883
  this.profileSelectedIndex = (this.profileSelectedIndex + 1) % this.profileItems.length;
833
884
  this.tui?.requestRender?.();
834
885
  return;
835
886
  }
836
887
 
837
- if (matchesKey(data, "return") || matchesKey(data, "space")) {
888
+ if (this.matchesBinding(data, "tui.select.confirm", "return") || matchesKey(data, "space")) {
838
889
  const item = this.profileItems[this.profileSelectedIndex];
839
890
  if (!item) return;
840
891
 
841
892
  if (item.category === "profile" && item.profile) {
842
- this.index?.setProfile?.(item.profile);
843
- this.finishModal("select", item.profile);
893
+ this.syncProfileSelection(item.profile);
894
+ this.tui?.requestRender?.();
844
895
  return;
845
896
  }
846
897
 
@@ -872,13 +923,13 @@ export class UnifiedControlModal implements Focusable {
872
923
  }
873
924
  const currentNode = visibleNodes[this.treeCursorIndex];
874
925
 
875
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
926
+ if (this.matchesBinding(data, "tui.select.up", "up") || matchesKey(data, "k")) {
876
927
  this.treeCursorIndex = Math.max(0, this.treeCursorIndex - 1);
877
928
  this.tui?.requestRender?.();
878
929
  return;
879
930
  }
880
931
 
881
- if (matchesKey(data, "down") || matchesKey(data, "j")) {
932
+ if (this.matchesBinding(data, "tui.select.down", "down") || matchesKey(data, "j")) {
882
933
  this.treeCursorIndex = Math.min(visibleNodes.length - 1, this.treeCursorIndex + 1);
883
934
  this.tui?.requestRender?.();
884
935
  return;
@@ -918,7 +969,7 @@ export class UnifiedControlModal implements Focusable {
918
969
  return;
919
970
  }
920
971
 
921
- if (matchesKey(data, "return")) {
972
+ if (this.matchesBinding(data, "tui.select.confirm", "return")) {
922
973
  if (currentNode) {
923
974
  if (currentNode.isDir) {
924
975
  currentNode.expanded = !currentNode.expanded;
@@ -930,15 +981,18 @@ export class UnifiedControlModal implements Focusable {
930
981
  }
931
982
  }
932
983
 
933
- private finishModal(action: "select" | "reindex" | "close", selectedProfile?: SearchProfile): void {
934
- // 1. Commit any changes from Tab 0 Settings
984
+ private finishModal(action: "select" | "reindex" | "close"): void {
985
+ // 1. Commit any changes from Tab 0 & Tab 1 (profile selection is synchronized into Tab 0)
935
986
  this.applySettingsChanges();
936
987
 
937
- // 2. Commit any changes from Tab 1 Retrieval Mode
938
- const currentProfile = this.index?.getProfile ? this.index.getProfile() : this.initialProfile;
939
- const profileChanged = selectedProfile !== undefined && selectedProfile !== this.initialProfile;
988
+ const initialNormalized = this.initialProfile === "hybrid" ? "full" : this.initialProfile;
989
+ const profileChanged = this.selectedProfile !== initialNormalized;
990
+ if (profileChanged && !this.options.deps?.invalidateConfig) {
991
+ this.index?.setProfile?.(this.selectedProfile);
992
+ }
993
+ const currentProfile = this.index?.getProfile ? this.index.getProfile() : this.selectedProfile;
940
994
 
941
- // 3. Commit any changes from Tab 2 Scope
995
+ // 2. Commit any changes from Tab 2 Scope
942
996
  const hasScopeChanges = this.hasExcludedPathsChanged();
943
997
  if (hasScopeChanges) {
944
998
  if (this.index?.setExcludedPaths) {
@@ -956,7 +1010,7 @@ export class UnifiedControlModal implements Focusable {
956
1010
 
957
1011
  this.done({
958
1012
  action,
959
- profile: selectedProfile || currentProfile,
1013
+ profile: this.selectedProfile || currentProfile,
960
1014
  reindexed: action === "reindex" || profileChanged,
961
1015
  excludedPathsChanged: hasScopeChanges,
962
1016
  });
@@ -1098,7 +1152,7 @@ export class UnifiedControlModal implements Focusable {
1098
1152
  isModelCached: false,
1099
1153
  modelStatus: "ready",
1100
1154
  };
1101
- const currentProfile = this.index?.getProfile ? this.index.getProfile() : this.initialProfile;
1155
+ const currentProfile = this.selectedProfile;
1102
1156
 
1103
1157
  const title = this.theme?.fg
1104
1158
  ? this.theme.fg("accent", this.theme.bold("Codebase Retrieval Engine"))
@@ -165,10 +165,14 @@ function extractBalancedSig(
165
165
  }
166
166
 
167
167
  // Fast AST & Signature tag extractor with multi-line support
168
- export function extractFileTags(filePath: string, content: string): FileTags {
168
+ export function extractFileTags(
169
+ filePath: string,
170
+ content: string,
171
+ options?: { includeJsTestBlocks?: boolean; collectReferences?: boolean },
172
+ ): FileTags {
169
173
  const tsEngine = TreeSitterEngine.getInstance();
170
174
  if (tsEngine.isSupported(filePath)) {
171
- const treeTags = tsEngine.extractTags(filePath, content);
175
+ const treeTags = tsEngine.extractTags(filePath, content, options);
172
176
  if (treeTags) {
173
177
  return treeTags;
174
178
  }