@floydous/pi-agent-kernel 0.4.3 → 0.5.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.
Files changed (59) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +1 -7
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +6 -53
  4. package/config.example.toml +0 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +10 -9
  8. package/docs/editing-and-verification.md +1 -3
  9. package/docs/retrieval.md +6 -11
  10. package/docs/testing.md +3 -3
  11. package/package.json +4 -2
  12. package/src/config/agent_kernel_command.ts +8 -39
  13. package/src/config/kernel_config.ts +30 -68
  14. package/src/config/toml.ts +6 -1
  15. package/src/editing/auto_heal.ts +1 -1
  16. package/src/editing/patch.ts +27 -16
  17. package/src/editing/post_edit_verification.ts +12 -10
  18. package/src/editing/smart_anchor.ts +7 -5
  19. package/src/editing/syntax-verify.ts +9 -5
  20. package/src/index.ts +15 -257
  21. package/src/retrieval/search_bm25.ts +4 -2
  22. package/src/retrieval/search_chunker.ts +1 -1
  23. package/src/retrieval/search_config.ts +4 -6
  24. package/src/retrieval/search_embedder.ts +3 -2
  25. package/src/retrieval/search_index.ts +82 -35
  26. package/src/retrieval/search_modal.ts +7 -8
  27. package/src/retrieval/{repomap.ts → tag_extractor.ts} +5 -292
  28. package/src/retrieval/tree_sitter_engine.ts +70 -34
  29. package/src/retrieval/workspace_walker.ts +6 -2
  30. package/src/safety/atomic_write.ts +1 -1
  31. package/src/safety/epistemic_guard.ts +105 -31
  32. package/src/safety/output_clamper.ts +14 -8
  33. package/src/tools/code_search_output.ts +2 -1
  34. package/src/tools/code_search_tool.ts +2 -5
  35. package/src/tools/context.ts +0 -14
  36. package/src/tools/edit_tool.ts +82 -115
  37. package/src/tools/read_tool.ts +42 -178
  38. package/src/ui/footer.ts +7 -7
  39. package/docs/lsp.md +0 -31
  40. package/src/lsp/adapters/base.ts +0 -42
  41. package/src/lsp/adapters/index.ts +0 -21
  42. package/src/lsp/adapters/python.ts +0 -37
  43. package/src/lsp/adapters/rust.ts +0 -35
  44. package/src/lsp/adapters/typescript.ts +0 -40
  45. package/src/lsp/index.ts +0 -13
  46. package/src/lsp/lsp_client.ts +0 -765
  47. package/src/lsp/lsp_detector.ts +0 -52
  48. package/src/lsp/lsp_formatter.ts +0 -323
  49. package/src/lsp/lsp_installer.ts +0 -320
  50. package/src/lsp/lsp_manager.ts +0 -202
  51. package/src/lsp/lsp_modal.ts +0 -675
  52. package/src/lsp/lsp_registry.ts +0 -600
  53. package/src/lsp/lsp_types.ts +0 -143
  54. package/src/retrieval/ast_search.ts +0 -999
  55. package/src/retrieval/symbol_reader.ts +0 -228
  56. package/src/tools/ast_search_formatter.ts +0 -161
  57. package/src/tools/ast_search_tool.ts +0 -146
  58. package/src/tools/lsp_tool.ts +0 -794
  59. package/src/tools/repo_map_tool.ts +0 -56
package/src/index.ts CHANGED
@@ -1,7 +1,6 @@
1
- import * as path from "path";
1
+ import * as path from "node:path";
2
2
  import * as fs from "node:fs";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { computeRepoMap } from "./retrieval/repomap";
5
4
  import { HybridSearchIndex } from "./retrieval/search_index";
6
5
  import { type SearchProfile, savePersistedProfile } from "./retrieval/search_config";
7
6
  import { SearchControlModal } from "./retrieval/search_modal";
@@ -12,13 +11,9 @@ import {
12
11
  } from "./safety/epistemic_guard";
13
12
  import { loadKernelConfig, registerAgentKernelCommand } from "./config";
14
13
  import { kernelDebug } from "./safety/kernel_debug";
15
- import { registerRepoMapTool } from "./tools/repo_map_tool";
16
- import { registerAstSearchTool } from "./tools/ast_search_tool";
17
- import { speculativeToolsEnabled } from "./tools/context";
18
14
  import { registerCodeSearchTool } from "./tools/code_search_tool";
19
15
  import { registerReadTool } from "./tools/read_tool";
20
16
  import { registerEditTool } from "./tools/edit_tool";
21
- import { registerLspTool } from "./tools/lsp_tool";
22
17
  import { TreeSitterEngine } from "./retrieval/tree_sitter_engine";
23
18
 
24
19
  /**
@@ -106,7 +101,7 @@ function loadKernelGuidance(
106
101
  rendered,
107
102
  "",
108
103
  "## Tool Integration Notice",
109
- `Pi reports that another extension already owns: ${[...toolCollisions].sort().join(", ")}. Agent Kernel did not replace those tools. Kernel-specific output limits, read-before-write checks, or edit verification may not apply to them.`,
104
+ `Pi reports that another extension already owns: ${[...toolCollisions].sort((a, b) => a.localeCompare(b)).join(", ")}. Agent Kernel did not replace those tools. Kernel-specific output limits, read-before-write checks, or edit verification may not apply to them.`,
110
105
  ].filter(Boolean).join("\n");
111
106
  }
112
107
 
@@ -123,15 +118,6 @@ function appendKernelGuidance(systemPrompt: string, guidance: string): string {
123
118
  import { clampCommandOutput, getSpilloverRoot } from "./safety/output_clamper";
124
119
  import { sanitizeSessionFiles } from "./context/session_repair";
125
120
  import { formatSearchEngineTag, renderFooter } from "./ui/footer";
126
- import {
127
- LspManager,
128
- LspControlModal,
129
- LspDownloadModal,
130
- formatDiagnostics,
131
- installLanguageServer,
132
- LSP_SERVERS,
133
- findExecutable,
134
- } from "./lsp";
135
121
 
136
122
  export default async function unifiedHybridExtension(pi: ExtensionAPI) {
137
123
  // Initialize TreeSitter WASM engine eagerly in background
@@ -139,7 +125,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
139
125
  kernelDebug(`TreeSitter background init error: ${err}`);
140
126
  });
141
127
 
142
- // 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
128
+ // 3. Slash Commands: /engine, /pi-docs
143
129
  let activeTui: any = null;
144
130
  let projectTrusted = false;
145
131
  const configByWorkspace = new Map<
@@ -217,7 +203,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
217
203
  );
218
204
 
219
205
  const runSync = async () => {
220
- return await index.syncWorkspace(
206
+ return index.syncWorkspace(
221
207
  isFullSync,
222
208
  (msg: string) => {
223
209
  if (currentGeneration !== activeIndexingGeneration) return;
@@ -330,9 +316,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
330
316
  invalidateConfig: (cwd, ctx) => {
331
317
  applyConfigChanges(cwd, ctx);
332
318
  },
333
- clearCaches: () => {
334
- cachedRepoMap = "";
335
- },
336
319
  });
337
320
 
338
321
  pi.registerCommand("repair-sessions", {
@@ -395,26 +378,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
395
378
  },
396
379
  });
397
380
 
398
- pi.registerCommand("repomap", {
399
- description: "Display the Tree-Sitter AST & PageRank ranked repository map",
400
- handler: async (args: string, ctx: any) => {
401
- await TreeSitterEngine.getInstance().init();
402
- const budget = args ? parseInt(args, 10) : 1024;
403
- const map = computeRepoMap(
404
- ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd(),
405
- Number.isNaN(budget)
406
- ? getConfig(ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd()).retrieval.repo_map_budget
407
- : budget,
408
- );
409
- ctx.ui?.notify?.("Repository Map Generated", "info");
410
- if (ctx.hasUI && ctx.ui?.setWidget) {
411
- ctx.ui.setWidget("repomap-widget", map.split("\n").slice(0, 25));
412
- } else if (!ctx.hasUI) {
413
- console.log("\n" + map + "\n");
414
- }
415
- },
416
- });
417
-
418
381
  // Slash Command: /engine [auto|lean|hybrid|full|off|status|reindex]
419
382
  pi.registerCommand("engine", {
420
383
  description:
@@ -609,135 +572,12 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
609
572
  },
610
573
  });
611
574
 
612
- // Slash Command: /lsp (Inspect language servers, active daemons, or install language servers)
613
- pi.registerCommand("lsp", {
614
- description:
615
- "Inspect language servers, active daemons, or install servers (/lsp, /lsp install <lang>)",
616
- getArgumentCompletions: (prefix: string) => {
617
- const options = [
618
- {
619
- value: "status",
620
- label: "status - View LSP status and active daemon processes",
621
- },
622
- { value: "stop", label: "stop - Stop all active LSP daemon processes" },
623
- {
624
- value: "install",
625
- label:
626
- "install - Install an LSP server (e.g. pyright, typescript-language-server, gopls, rust-analyzer, clangd)",
627
- },
628
- ];
629
- const filtered = options.filter((o) =>
630
- o.value.startsWith(prefix.toLowerCase()),
631
- );
632
- return filtered.length > 0 ? filtered : null;
633
- },
634
- async handler(args: string, ctx: any) {
635
- const sub = args.trim().split(/\s+/);
636
- const lspMgr = LspManager.getInstance();
637
-
638
- if (sub[0] === "install" && sub[1]) {
639
- const target = sub[1];
640
- if (ctx.hasUI && ctx.ui?.notify) {
641
- ctx.ui.notify(`Installing LSP server for ${target}...`, "info");
642
- }
643
- const res = await installLanguageServer(target, (msg) => {
644
- if (ctx.hasUI && ctx.ui?.notify) {
645
- ctx.ui.notify(msg, "info");
646
- }
647
- });
648
- if (res.success) {
649
- ctx.ui?.notify?.(res.message, "info");
650
- } else {
651
- ctx.ui?.notify?.(res.message, "error");
652
- }
653
- return;
654
- }
655
-
656
- if (sub[0] === "stop" || sub[0] === "kill") {
657
- await lspMgr.stopAll();
658
- ctx.ui?.notify?.("All active LSP servers stopped.", "info");
659
- return;
660
- }
661
-
662
- // Interactive centered modal dialog with full-viewport backdrop scrim
663
- if (ctx.hasUI && ctx.ui?.custom) {
664
- const res: any = await ctx.ui.custom(
665
- (tui: any, theme: any, _keybindings: any, done: any) =>
666
- new LspControlModal(tui, lspMgr, theme, done),
667
- {
668
- overlay: true,
669
- overlayOptions: {
670
- anchor: "center",
671
- width: "100%",
672
- },
673
- },
674
- );
675
-
676
- if (res) {
677
- if (res.action === "stop") {
678
- await lspMgr.stopAll();
679
- ctx.ui?.notify?.("All active LSP servers stopped.", "info");
680
- } else if (res.installTargets && res.installTargets.length > 0) {
681
- // Spawn animated ASCII loading spinner modal
682
- await ctx.ui.custom(
683
- (tui: any, theme: any, _keybindings: any, done: any) =>
684
- new LspDownloadModal(tui, res.installTargets, theme, done),
685
- {
686
- overlay: true,
687
- overlayOptions: {
688
- anchor: "center",
689
- width: "100%",
690
- },
691
- },
692
- );
693
- }
694
- }
695
- return;
696
- }
697
-
698
- const activeClients = lspMgr.getStatus();
699
- if (ctx.hasUI && ctx.ui?.select) {
700
- const lines = [
701
- `── Active LSP Daemons (${activeClients.length}) ────────────────`,
702
- ...activeClients.map(
703
- (c) =>
704
- `[Active] ${c.languageId.toUpperCase()} (State: ${c.state}, Idle: ${c.idleSeconds}s)`,
705
- ),
706
- `── Installed / Available Servers ─────────────────────────────`,
707
- ...Object.entries(LSP_SERVERS)
708
- .slice(0, 10)
709
- .map(([k, cfg]) => {
710
- const primaryBin = cfg.commands[0]?.bin;
711
- const found = findExecutable(primaryBin);
712
- return `[${found ? "✓" : "✗"}] ${k.padEnd(12)} → ${primaryBin} ${found ? `(${found})` : "(not installed)"}`;
713
- }),
714
- `── Actions ───────────────────────────────────────────────────`,
715
- `Stop all active LSP daemons`,
716
- ];
717
-
718
- const choice = await ctx.ui.select("LSP Server Status & Management", lines);
719
- if (choice?.includes("Stop all active")) {
720
- await lspMgr.stopAll();
721
- ctx.ui.notify("All active LSP servers stopped.", "info");
722
- }
723
- return;
724
- }
725
-
726
- // Console fallback
727
- let out = `=== LSP Status ===\nActive Daemons: ${activeClients.length}\n`;
728
- for (const c of activeClients) {
729
- out += ` • ${c.languageId}: ${c.state} (idle: ${c.idleSeconds}s, root: ${c.rootDir})\n`;
730
- }
731
- console.log(out);
732
- },
733
- });
734
-
735
575
  // Background workspace auto-indexer on session startup + setup integrated footer
736
576
  pi.on("session_start", async (_event: any, ctx: any) => {
737
577
  projectTrusted = ctx.isProjectTrusted?.() === true;
738
578
  configByWorkspace.clear();
739
579
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
740
- registerKernelTools(cwd);
580
+ registerKernelTools();
741
581
  setupUnifiedFooter(ctx);
742
582
  try {
743
583
  const index = getSearchIndex(cwd);
@@ -749,19 +589,14 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
749
589
  }
750
590
  });
751
591
 
752
- // 2. Per-session cleanup of the epistemic guard's inspection state and LSP processes.
592
+ // 2. Per-session cleanup of the epistemic guard's inspection state.
753
593
  // Without this, Map<sessionId, Set<filePath>> grows unbounded over a
754
594
  // long-lived process hosting many sessions (e.g. RPC mode). On session
755
- // shutdown we drop only this session's entry and stop running LSP daemons.
595
+ // shutdown we drop only this session's entry.
756
596
  pi.on("session_shutdown", async (_event: any, ctx: any) => {
757
597
  const sessionId = getSessionId(ctx);
758
598
  piDocsEnabledBySession.delete(sessionId);
759
599
  globalEpistemicGuard.resetSession(sessionId);
760
- try {
761
- await LspManager.getInstance().stopAll();
762
- } catch (e) {
763
- kernelDebug(e);
764
- }
765
600
  // Flush any debounced search index writes to disk on shutdown and halt further admissions
766
601
  for (const index of searchIndexes.values()) {
767
602
  try {
@@ -784,7 +619,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
784
619
  kernelDebug(`Incremental updateFile error for ${filePath}: ${err}`);
785
620
  });
786
621
  };
787
- const registerKernelTools = (cwd: string): void => {
622
+ const registerKernelTools = (): void => {
788
623
  if (kernelToolsRegistered) return;
789
624
  kernelToolsRegistered = true;
790
625
  // pi marks its own built-in tools with sourceInfo.source === "builtin" and a
@@ -820,15 +655,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
820
655
  registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
821
656
  kernelRegisteredTools.add("code_search");
822
657
  }
823
-
824
- const enableSpeculativeTools = speculativeToolsEnabled(getConfig, cwd);
825
- if (enableSpeculativeTools) {
826
- if (canRegister("get_repo_map")) registerRepoMapTool(pi);
827
- if (canRegister("ast_search")) {
828
- registerAstSearchTool(pi, { getSessionId, getConfig });
829
- }
830
- if (canRegister("lsp")) registerLspTool(pi, { getSessionId, getConfig });
831
- }
832
658
  };
833
659
 
834
660
  // 9a. Block host writes before the host tool can create parent directories
@@ -839,7 +665,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
839
665
  const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
840
666
  const sessionId = getSessionId(ctx);
841
667
  if (event.toolName !== "write") return;
842
- const targetPath = (event.input as any)?.path;
668
+ const targetPath = (event.input as Record<string, unknown> | undefined)?.path;
843
669
  if (typeof targetPath !== "string" || !targetPath.trim()) {
844
670
  return {
845
671
  block: true,
@@ -886,7 +712,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
886
712
 
887
713
  // 9a. Intercept bash & powershell output to clamp minified lines & massive match floods
888
714
  if (toolName === "bash" || toolName === "powershell") {
889
- const command = (event.input as any)?.command || "";
715
+ const command = String((event.input as Record<string, unknown> | undefined)?.command || "");
890
716
  const outputConfig = getConfig(
891
717
  ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd(),
892
718
  );
@@ -916,8 +742,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
916
742
  getSessionId(ctx),
917
743
  bashOutputComplete,
918
744
  (resultContent || [])
919
- .filter((c: any) => c.type === "text" && typeof c.text === "string")
920
- .map((c: any) => c.text)
745
+ .flatMap((c: any) => (c?.type === "text" && typeof c?.text === "string" ? [c.text] : []))
921
746
  .join(""),
922
747
  );
923
748
  if (event.isError) {
@@ -929,10 +754,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
929
754
 
930
755
  // 9b. Preserve the host write-tool compatibility path. The custom edit
931
756
  // tool owns its complete verification lifecycle; intercepting edit results
932
- // here would duplicate syntax/LSP work.
757
+ // here would duplicate syntax verification work.
933
758
  if (toolName === "write") {
934
- const input = event.input as any;
935
- const targetPath = input?.path;
759
+ const input = event.input as Record<string, unknown> | undefined;
760
+ const targetPath = typeof input?.path === "string" ? input.path : undefined;
936
761
 
937
762
  // The harness does not reliably propagate result-level isError to this
938
763
  // hook, so a failed edit can still reach here. Detect the edit tool's
@@ -980,39 +805,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
980
805
  resultContent = event.content.map((c: any) =>
981
806
  c.type === "text" ? { ...c, text: c.text + warning } : c,
982
807
  );
983
- } else {
984
- // Synchronize with active LSP daemon and fetch post-edit diagnostics if available
985
- let lspNotice = "";
986
- try {
987
- const lspMgr = LspManager.getInstance();
988
- const client = lspMgr.getReadyClientForFile(resolvedPath, resultCwd);
989
- if (client && client.getState() === "ready") {
990
- const fileContent = fs.readFileSync(resolvedPath, "utf8");
991
- await client.changeDocument(resolvedPath, fileContent);
992
- await client.saveDocument(resolvedPath, fileContent);
993
-
994
- // Allow LSP server brief window to compute diagnostics
995
- const diagnostics = await client.getDiagnosticsResult(resolvedPath);
996
- if (diagnostics.diagnostics.length > 0) {
997
- const formattedDiags = formatDiagnostics(
998
- diagnostics.diagnostics,
999
- resolvedPath,
1000
- resultCwd,
1001
- );
1002
- lspNotice = `\n\n[LSP Diagnostics]\n${formattedDiags}`;
1003
- } else if (diagnostics.status !== "clean") {
1004
- lspNotice = `\n\n[LSP ${diagnostics.status.toUpperCase()}] No definitive diagnostics result.`;
1005
- }
1006
- }
1007
- } catch (e) {
1008
- kernelDebug(e);
1009
- }
1010
-
1011
- if (lspNotice) {
1012
- resultContent = event.content.map((c: any) =>
1013
- c.type === "text" ? { ...c, text: c.text + lspNotice } : c,
1014
- );
1015
- }
1016
808
  }
1017
809
  }
1018
810
  }
@@ -1027,39 +819,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
1027
819
  // Custom user instructions remain the primary authority. Repository-controlled
1028
820
  // diffs, source text, filenames, and command output are never promoted into the
1029
821
  // system prompt by this extension.
1030
- let cachedRepoMap = "";
1031
- let cachedRepoMapCwd = "";
1032
- let lastRepoMapCheck = 0;
1033
-
1034
822
  pi.on("before_agent_start", async (event: any, ctx: any) => {
1035
- const now = Date.now();
1036
823
  const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
1037
824
  const kernelConfig = getConfig(currentCwd);
1038
825
 
1039
- let shouldInjectMap = false;
1040
- // Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
1041
- // The `get_repo_map` tool remains available on-demand.
1042
-
1043
- // Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
1044
- if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
1045
- if (shouldInjectMap) {
1046
- await TreeSitterEngine.getInstance().init();
1047
- cachedRepoMap = computeRepoMap(
1048
- currentCwd,
1049
- kernelConfig.retrieval.repo_map_budget,
1050
- );
1051
- } else {
1052
- cachedRepoMap = "";
1053
- }
1054
- cachedRepoMapCwd = currentCwd;
1055
- lastRepoMapCheck = now;
1056
- }
1057
-
1058
- const runtimeParts = [
1059
- cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
1060
- ].filter(Boolean);
1061
- const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
1062
-
1063
826
  const basePrompt = event.systemPrompt || "";
1064
827
  const systemPrompt = piDocsEnabled(ctx)
1065
828
  ? basePrompt
@@ -1076,11 +839,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
1076
839
  ? loadKernelGuidance(toolCollisions, promptToolNames)
1077
840
  : "";
1078
841
  const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
1079
- const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
1080
- return {
1081
- systemPrompt: guidedPrompt
1082
- ? (shouldAppendRuntime ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
1083
- : runtimeContext,
1084
- };
842
+ return { systemPrompt: guidedPrompt };
1085
843
  });
1086
844
  }
@@ -121,7 +121,7 @@ export class BM25Engine {
121
121
  */
122
122
  public removeFile(filePath: string): void {
123
123
  const prefix = `${filePath}:`;
124
- for (const chunkId of Array.from(this.docTermFreqs.keys())) {
124
+ for (const chunkId of [...this.docTermFreqs.keys()]) {
125
125
  if (chunkId.startsWith(prefix)) {
126
126
  const tfMap = this.docTermFreqs.get(chunkId);
127
127
  if (tfMap) {
@@ -204,7 +204,9 @@ export class BM25Engine {
204
204
  .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
205
205
  .sort((a, b) => {
206
206
  if (b.score !== a.score) return b.score - a.score;
207
- return a.chunkId < b.chunkId ? -1 : a.chunkId > b.chunkId ? 1 : 0;
207
+ if (a.chunkId < b.chunkId) return -1;
208
+ if (a.chunkId > b.chunkId) return 1;
209
+ return 0;
208
210
  })
209
211
  .slice(0, limit);
210
212
  }
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as crypto from "node:crypto";
4
4
  import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
5
- import { extractFileTags, isTestPath, SymbolDef } from "./repomap";
5
+ import { extractFileTags, isTestPath, SymbolDef } from "./tag_extractor";
6
6
  import { TreeSitterEngine } from "./tree_sitter_engine";
7
7
 
8
8
  export interface CodeChunk {
@@ -3,11 +3,9 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import {
5
5
  getPiHomeDir,
6
- loadKernelConfig,
7
6
  saveProjectKernelConfig,
8
7
  saveGlobalKernelConfig,
9
8
  getProjectConfigPath,
10
- getGlobalConfigPath,
11
9
  getGlobalRawConfig,
12
10
  } from "../config";
13
11
  import { kernelDebug } from "../safety/kernel_debug";
@@ -66,8 +64,8 @@ export function loadPersistedProfile(
66
64
  const raw = parseToml(fs.readFileSync(projectPath, "utf-8"));
67
65
  const retrieval = raw.retrieval;
68
66
  if (retrieval && typeof retrieval === "object" && !Array.isArray(retrieval)) {
69
- const p = (retrieval as any).default_profile;
70
- if (p && ["lean", "hybrid", "full", "off", "auto"].includes(p)) {
67
+ const p = (retrieval as Record<string, unknown>).default_profile;
68
+ if (typeof p === "string" && ["lean", "hybrid", "full", "off", "auto"].includes(p)) {
71
69
  return p as SearchProfile;
72
70
  }
73
71
  }
@@ -111,10 +109,10 @@ export function savePersistedProfile(profile: SearchProfile, cwd?: string): void
111
109
  try {
112
110
  if (cwd) {
113
111
  // Workspace-local profile update: writes only to project-local config.toml
114
- saveProjectKernelConfig(cwd, { retrieval: { default_profile: profile as any } });
112
+ saveProjectKernelConfig(cwd, { retrieval: { default_profile: profile } });
115
113
  } else {
116
114
  // Global profile update: writes to global ~/.pi/agent/config.toml and legacy search_settings.json
117
- saveGlobalKernelConfig({ retrieval: { default_profile: profile as any } });
115
+ saveGlobalKernelConfig({ retrieval: { default_profile: profile } });
118
116
  const dir = path.dirname(SETTINGS_FILE);
119
117
  if (!fs.existsSync(dir)) {
120
118
  fs.mkdirSync(dir, { recursive: true });
@@ -344,8 +344,9 @@ export class LocalEmbedder {
344
344
  this.queryLruCache.clear();
345
345
 
346
346
  try {
347
- if (typeof (global as any).gc === "function") {
348
- (global as any).gc();
347
+ const globalWithGc = globalThis as typeof globalThis & { gc?: () => void };
348
+ if (typeof globalWithGc.gc === "function") {
349
+ globalWithGc.gc();
349
350
  }
350
351
  } catch (e) {
351
352
  kernelDebug(e);