@floydous/pi-agent-kernel 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { extractFileTags } from "./repomap";
4
4
  import { kernelDebug } from "../safety/kernel_debug";
5
+ import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
5
6
 
6
7
  export interface AstQueryResult {
7
8
  filePath: string;
@@ -104,18 +105,7 @@ const SUPPORTED_EXTENSIONS = new Set([
104
105
  ".lua",
105
106
  ]);
106
107
 
107
- const IGNORED_DIRS = new Set([
108
- "node_modules",
109
- ".git",
110
- "target",
111
- "dist",
112
- "build",
113
- ".next",
114
- "__pycache__",
115
- ".pytest_cache",
116
- ".venv",
117
- "venv",
118
- ]);
108
+ const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
119
109
 
120
110
  /**
121
111
  * Extract top-level symbols from a single file using fast AST tagging
@@ -204,88 +194,73 @@ export function findSymbolReferences(
204
194
  const escaped = cleanSym.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
205
195
  const regex = new RegExp(`\\b${escaped}\\b`, "g");
206
196
 
207
- function walk(dir: string) {
208
- if (results.length >= maxResults) return;
209
- let entries: fs.Dirent[] = [];
210
- try {
211
- entries = fs.readdirSync(dir, { withFileTypes: true });
212
- } catch {
213
- return;
214
- }
215
-
216
- for (const entry of entries) {
217
- if (results.length >= maxResults) break;
218
- if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) continue;
219
-
220
- const fullPath = path.join(dir, entry.name);
221
- if (entry.isDirectory()) {
222
- walk(fullPath);
223
- } else if (entry.isFile()) {
224
- const ext = path.extname(entry.name).toLowerCase();
225
- if (!SUPPORTED_EXTENSIONS.has(ext)) continue;
226
-
227
- try {
228
- const content = fs.readFileSync(fullPath, "utf-8");
229
- const lines = content.split("\n");
230
- let inBlockComment = false;
231
-
232
- for (let i = 0; i < lines.length; i++) {
233
- if (results.length >= maxResults) break;
234
- const lineText = lines[i];
235
- const trimmed = lineText.trim();
236
-
237
- // Block comment handling (/* ... */)
238
- if (inBlockComment) {
239
- if (trimmed.includes("*/")) {
240
- inBlockComment = false;
241
- }
242
- continue;
197
+ walkWorkspaceFiles({
198
+ rootDir,
199
+ extensions: SUPPORTED_EXTENSIONS,
200
+ includeGithub: false,
201
+ onFile: (fullPath) => {
202
+ if (results.length >= maxResults) return false;
203
+ try {
204
+ const content = fs.readFileSync(fullPath, "utf-8");
205
+ const lines = content.split("\n");
206
+ let inBlockComment = false;
207
+
208
+ for (let i = 0; i < lines.length; i++) {
209
+ if (results.length >= maxResults) return false;
210
+ const lineText = lines[i];
211
+ const trimmed = lineText.trim();
212
+
213
+ // Block comment handling (/* ... */)
214
+ if (inBlockComment) {
215
+ if (trimmed.includes("*/")) {
216
+ inBlockComment = false;
243
217
  }
244
- if (trimmed.startsWith("/*")) {
245
- if (!trimmed.includes("*/")) {
246
- inBlockComment = true;
247
- }
248
- continue;
218
+ continue;
219
+ }
220
+ if (trimmed.startsWith("/*")) {
221
+ if (!trimmed.includes("*/")) {
222
+ inBlockComment = true;
249
223
  }
224
+ continue;
225
+ }
226
+
227
+ // Skip lines starting with comment markers
228
+ if (
229
+ trimmed.startsWith("//") ||
230
+ trimmed.startsWith("///") ||
231
+ trimmed.startsWith("//!") ||
232
+ trimmed.startsWith("#") ||
233
+ trimmed.startsWith("*") ||
234
+ trimmed.startsWith("--")
235
+ ) {
236
+ continue;
237
+ }
250
238
 
251
- // Skip lines starting with comment markers
252
- if (
253
- trimmed.startsWith("//") ||
254
- trimmed.startsWith("///") ||
255
- trimmed.startsWith("//!") ||
256
- trimmed.startsWith("#") ||
257
- trimmed.startsWith("*") ||
258
- trimmed.startsWith("--")
259
- ) {
239
+ let match;
240
+ regex.lastIndex = 0;
241
+ while ((match = regex.exec(lineText)) !== null) {
242
+ // Filter out matches inside inline comments or string literals
243
+ if (isInsideCommentOrString(lineText, match.index)) {
260
244
  continue;
261
245
  }
262
246
 
263
- let match;
264
- regex.lastIndex = 0;
265
- while ((match = regex.exec(lineText)) !== null) {
266
- // Filter out matches inside inline comments or string literals
267
- if (isInsideCommentOrString(lineText, match.index)) {
268
- continue;
269
- }
270
-
271
- results.push({
272
- filePath:
273
- path.relative(rootDir, fullPath).replace(/\\/g, "/") || fullPath,
274
- line: i + 1,
275
- column: match.index + 1,
276
- lineText: lineText.trim(),
277
- });
278
- if (results.length >= maxResults) break;
279
- }
247
+ results.push({
248
+ filePath:
249
+ path.relative(rootDir, fullPath).replace(/\\/g, "/") || fullPath,
250
+ line: i + 1,
251
+ column: match.index + 1,
252
+ lineText: lineText.trim(),
253
+ });
254
+ if (results.length >= maxResults) return false;
280
255
  }
281
- } catch (e) {
282
- kernelDebug(e);
283
256
  }
257
+ } catch (e) {
258
+ kernelDebug(e);
284
259
  }
285
- }
286
- }
260
+ return results.length < maxResults;
261
+ },
262
+ });
287
263
 
288
- walk(rootDir);
289
264
  return results;
290
265
  }
291
266
 
@@ -747,100 +722,86 @@ export function searchAstSymbols(
747
722
  : cleanQueryName;
748
723
  const includeBody = query.includeBody ?? false;
749
724
 
750
- function walk(dir: string) {
751
- let entries: fs.Dirent[] = [];
752
- try {
753
- entries = fs.readdirSync(dir, { withFileTypes: true });
754
- } catch {
755
- return;
756
- }
757
-
758
- for (const entry of entries) {
759
- if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) {
760
- continue;
725
+ walkWorkspaceFiles({
726
+ rootDir,
727
+ extensions: SUPPORTED_EXTENSIONS,
728
+ includeGithub: false,
729
+ onFile: (fullPath) => {
730
+ const relPath = path.relative(rootDir, fullPath).replace(/\\/g, "/");
731
+ if (
732
+ query.filePattern &&
733
+ !relPath
734
+ .toLowerCase()
735
+ .includes(query.filePattern.replace(/\\/g, "/").toLowerCase())
736
+ ) {
737
+ return;
761
738
  }
762
- const fullPath = path.join(dir, entry.name);
763
- if (entry.isDirectory()) {
764
- walk(fullPath);
765
- } else if (entry.isFile()) {
766
- const relPath = path.relative(rootDir, fullPath).replace(/\\/g, "/");
767
- if (
768
- query.filePattern &&
769
- !relPath
770
- .toLowerCase()
771
- .includes(query.filePattern.replace(/\\/g, "/").toLowerCase())
772
- ) {
773
- continue;
774
- }
775
- const ext = path.extname(entry.name).toLowerCase();
776
- if (!SUPPORTED_EXTENSIONS.has(ext)) {
777
- continue;
778
- }
779
- try {
780
- const content = fs.readFileSync(fullPath, "utf-8");
781
- const tags = extractFileTags(fullPath, content);
782
- const lines = content.split("\n");
783
- const fileDefs: AstQueryResult[] = [];
784
-
785
- for (const def of tags.definitions) {
786
- let codeBlock: string | undefined;
787
- let bodyTruncated = false;
788
- let visibleEndLine: number | undefined;
789
- if (includeBody) {
790
- const start = Math.max(0, def.line - 1);
791
- const end = Math.min(lines.length, start + 25);
792
- codeBlock = lines.slice(start, end).join("\n");
793
- visibleEndLine = end;
794
- bodyTruncated = end < lines.length;
795
- }
796
-
797
- const item: AstQueryResult = {
798
- filePath: relPath,
799
- name: def.name,
800
- kind: def.kind,
801
- signature: def.signature,
802
- line: def.line,
803
- endLine: def.endLine && def.endLine >= def.line ? def.endLine : findSymbolEndLine(lines, def.line - 1, ext),
804
- codeBlock,
805
- visibleEndLine,
806
- bodyTruncated: includeBody ? bodyTruncated : undefined,
807
- aliasedFrom: def.aliasedFrom,
808
- };
809
-
810
- fileDefs.push(item);
811
-
812
- if (query.kind) {
813
- const qKind = query.kind.toLowerCase();
814
- const dKind = def.kind.toLowerCase();
815
- const matchKind =
816
- qKind === dKind ||
817
- (qKind === "struct" && dKind === "class") ||
818
- (qKind === "trait" && dKind === "class") ||
819
- (qKind === "constant" && (dKind === "constant" || dKind === "variable")) ||
820
- (qKind === "variable" && (dKind === "variable" || dKind === "constant"));
821
- if (!matchKind) continue;
822
- }
739
+ const ext = path.extname(fullPath).toLowerCase();
740
+ if (!SUPPORTED_EXTENSIONS.has(ext)) {
741
+ return;
742
+ }
743
+ try {
744
+ const content = fs.readFileSync(fullPath, "utf-8");
745
+ const tags = extractFileTags(fullPath, content);
746
+ const lines = content.split("\n");
747
+ const fileDefs: AstQueryResult[] = [];
748
+
749
+ for (const def of tags.definitions) {
750
+ let codeBlock: string | undefined;
751
+ let bodyTruncated = false;
752
+ let visibleEndLine: number | undefined;
753
+ if (includeBody) {
754
+ const start = Math.max(0, def.line - 1);
755
+ const end = Math.min(lines.length, start + 25);
756
+ codeBlock = lines.slice(start, end).join("\n");
757
+ visibleEndLine = end;
758
+ bodyTruncated = end < lines.length;
759
+ }
823
760
 
824
- if (queryLeaf) {
825
- const qName = queryLeaf.toLowerCase();
826
- const dName = def.name.toLowerCase();
827
- if (query.exactMatch) {
828
- if (dName !== qName) continue;
829
- } else if (!dName.includes(qName)) continue;
830
- }
761
+ const item: AstQueryResult = {
762
+ filePath: relPath,
763
+ name: def.name,
764
+ kind: def.kind,
765
+ signature: def.signature,
766
+ line: def.line,
767
+ endLine: def.endLine && def.endLine >= def.line ? def.endLine : findSymbolEndLine(lines, def.line - 1, ext),
768
+ codeBlock,
769
+ visibleEndLine,
770
+ bodyTruncated: includeBody ? bodyTruncated : undefined,
771
+ aliasedFrom: def.aliasedFrom,
772
+ };
773
+
774
+ fileDefs.push(item);
775
+
776
+ if (query.kind) {
777
+ const qKind = query.kind.toLowerCase();
778
+ const dKind = def.kind.toLowerCase();
779
+ const matchKind =
780
+ qKind === dKind ||
781
+ (qKind === "struct" && dKind === "class") ||
782
+ (qKind === "trait" && dKind === "class") ||
783
+ (qKind === "constant" && (dKind === "constant" || dKind === "variable")) ||
784
+ (qKind === "variable" && (dKind === "variable" || dKind === "constant"));
785
+ if (!matchKind) continue;
786
+ }
831
787
 
832
- rawResults.push(item);
788
+ if (queryLeaf) {
789
+ const qName = queryLeaf.toLowerCase();
790
+ const dName = def.name.toLowerCase();
791
+ if (query.exactMatch) {
792
+ if (dName !== qName) continue;
793
+ } else if (!dName.includes(qName)) continue;
833
794
  }
834
795
 
835
- allDefsByFile.set(relPath, fileDefs);
836
- } catch {
837
- // skip unreadable
796
+ rawResults.push(item);
838
797
  }
839
- }
840
- }
841
- }
842
798
 
843
- walk(rootDir);
799
+ allDefsByFile.set(relPath, fileDefs);
800
+ } catch {
801
+ // skip unreadable
802
+ }
803
+ },
804
+ });
844
805
 
845
806
  // Resolve aliased re-exports (e.g. `WebSocketClient` -> `client` in `.websocket`)
846
807
  const resolvedResults: AstQueryResult[] = [...rawResults];
@@ -994,9 +955,12 @@ export function findSymbolSuggestions(
994
955
  const nameLower = h.name.toLowerCase();
995
956
  const dist = levenshteinDistance(qLower, nameLower);
996
957
  const normHitPath = h.filePath.replace(/\\/g, "/");
958
+ const isWindows = process.platform === "win32";
959
+ const r1 = path.resolve(cwd, normHitPath);
960
+ const r2 = path.resolve(cwd, targetFilePath);
997
961
  const isSameFile =
998
962
  normHitPath === relTarget ||
999
- path.resolve(cwd, normHitPath) === path.resolve(cwd, targetFilePath);
963
+ (isWindows ? r1.toLowerCase() === r2.toLowerCase() : r1 === r2);
1000
964
  const exactCaseSub = h.name.includes(qTrim);
1001
965
  return {
1002
966
  hit: h,
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { TreeSitterEngine } from "./tree_sitter_engine";
4
+ import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
4
5
 
5
6
  export interface SymbolDef {
6
7
  name: string;
@@ -31,23 +32,7 @@ export interface FileTags {
31
32
  hasSyntaxError?: boolean;
32
33
  }
33
34
 
34
- const IGNORED_DIRS = new Set([
35
- ".git",
36
- "node_modules",
37
- ".venv",
38
- "venv",
39
- "__pycache__",
40
- "dist",
41
- "build",
42
- "coverage",
43
- ".pi",
44
- ".hermes",
45
- ".next",
46
- ".turbo",
47
- ".cache",
48
- "target",
49
- "vendor",
50
- ]);
35
+ const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
51
36
 
52
37
  const SUPPORTED_EXTENSIONS = new Set([
53
38
  ".ts",
@@ -786,36 +771,12 @@ export function extractFileTags(filePath: string, content: string): FileTags {
786
771
 
787
772
  // Recursively find all supported code files in a directory
788
773
  export function findSourceFiles(rootDir: string, maxFiles = 300): string[] {
789
- const results: string[] = [];
790
-
791
- function scan(dir: string) {
792
- if (results.length >= maxFiles) return;
793
- let entries: fs.Dirent[];
794
- try {
795
- entries = fs.readdirSync(dir, { withFileTypes: true });
796
- } catch {
797
- return;
798
- }
799
-
800
- for (const entry of entries) {
801
- if (entry.name.startsWith(".") && entry.name !== ".github") continue;
802
- if (IGNORED_DIRS.has(entry.name)) continue;
803
-
804
- const fullPath = path.join(dir, entry.name);
805
- if (entry.isDirectory()) {
806
- scan(fullPath);
807
- } else if (entry.isFile()) {
808
- const ext = path.extname(entry.name).toLowerCase();
809
- if (SUPPORTED_EXTENSIONS.has(ext)) {
810
- results.push(fullPath);
811
- if (results.length >= maxFiles) return;
812
- }
813
- }
814
- }
815
- }
816
-
817
- scan(rootDir);
818
- return results;
774
+ return walkWorkspaceFiles({
775
+ rootDir,
776
+ maxFiles,
777
+ extensions: SUPPORTED_EXTENSIONS,
778
+ includeGithub: false,
779
+ });
819
780
  }
820
781
 
821
782
  // Check if a path corresponds to a test file or test directory
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as crypto from "node:crypto";
4
+ import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
4
5
  import { extractFileTags, isTestPath, SymbolDef } from "./repomap";
5
6
  import { TreeSitterEngine } from "./tree_sitter_engine";
6
7
 
@@ -19,13 +20,11 @@ export interface CodeChunk {
19
20
  hash: string; // SHA-256 hash of content
20
21
  }
21
22
 
22
- const SUPPORTED_EXTENSIONS = new Set([
23
+ export const SUPPORTED_EXTENSIONS = new Set([
23
24
  ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql", ".md", ".mdx", ".txt", ".rst"
24
25
  ]);
25
26
 
26
- const IGNORED_DIRS = new Set([
27
- ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "coverage", ".pi", ".hermes", ".next", ".turbo", ".cache", "target", "vendor"
28
- ]);
27
+ export const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
29
28
 
30
29
  /** Prose extensions are excluded from the default code-search scope. */
31
30
  export const PROSE_EXTENSIONS = new Set([".md", ".mdx", ".txt", ".rst"]);
@@ -282,36 +281,12 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
282
281
  * without reparsing unchanged files.
283
282
  */
284
283
  export function findChunkableFiles(rootDir: string, maxFiles = 500): string[] {
285
- const files: string[] = [];
286
-
287
- function scan(dir: string) {
288
- if (files.length >= maxFiles) return;
289
- let entries: fs.Dirent[];
290
- try {
291
- entries = fs.readdirSync(dir, { withFileTypes: true });
292
- } catch {
293
- return;
294
- }
295
-
296
- for (const entry of entries) {
297
- if (entry.name.startsWith(".") && entry.name !== ".github") continue;
298
- if (IGNORED_DIRS.has(entry.name)) continue;
299
-
300
- const fullPath = path.join(dir, entry.name);
301
- if (entry.isDirectory()) {
302
- scan(fullPath);
303
- } else if (entry.isFile()) {
304
- const ext = path.extname(entry.name).toLowerCase();
305
- if (SUPPORTED_EXTENSIONS.has(ext)) {
306
- files.push(fullPath);
307
- if (files.length >= maxFiles) return;
308
- }
309
- }
310
- }
311
- }
312
-
313
- scan(rootDir);
314
- return files;
284
+ return walkWorkspaceFiles({
285
+ rootDir,
286
+ maxFiles,
287
+ extensions: SUPPORTED_EXTENSIONS,
288
+ includeGithub: true,
289
+ });
315
290
  }
316
291
 
317
292
  /**
@@ -1,9 +1,18 @@
1
1
  import * as os from "node:os";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
- import { getPiHomeDir, loadKernelConfig } from "../config";
4
+ import {
5
+ getPiHomeDir,
6
+ loadKernelConfig,
7
+ saveProjectKernelConfig,
8
+ saveGlobalKernelConfig,
9
+ getProjectConfigPath,
10
+ getGlobalConfigPath,
11
+ getGlobalRawConfig,
12
+ } from "../config";
5
13
  import { kernelDebug } from "../safety/kernel_debug";
6
14
  import { writeFileSyncAtomic } from "../safety/atomic_write";
15
+ import { parseToml } from "../config/toml";
7
16
 
8
17
  export type SearchProfile = "lean" | "hybrid" | "full" | "off" | "auto";
9
18
 
@@ -42,7 +51,34 @@ export function detectBestProfile(): "lean" | "hybrid" | "full" {
42
51
  /**
43
52
  * Load persisted search settings or default to config.toml setting.
44
53
  */
45
- export function loadPersistedProfile(): SearchProfile {
54
+ export function loadPersistedProfile(cwd?: string): SearchProfile {
55
+ // 1. Explicit project-local config (.pi/config.toml or config.toml)
56
+ const projectPath = cwd ? getProjectConfigPath(cwd) : null;
57
+ if (projectPath && fs.existsSync(projectPath)) {
58
+ try {
59
+ const raw = parseToml(fs.readFileSync(projectPath, "utf-8"));
60
+ const retrieval = raw.retrieval;
61
+ if (retrieval && typeof retrieval === "object" && !Array.isArray(retrieval)) {
62
+ const p = (retrieval as any).default_profile;
63
+ if (p && ["lean", "hybrid", "full", "off", "auto"].includes(p)) {
64
+ return p as SearchProfile;
65
+ }
66
+ }
67
+ } catch (e) {
68
+ kernelDebug(e);
69
+ }
70
+ }
71
+
72
+ // 2. Explicit global configuration (~/.pi/agent/config.toml)
73
+ const globalRaw = getGlobalRawConfig();
74
+ if (
75
+ globalRaw.retrieval?.default_profile &&
76
+ ["lean", "hybrid", "full", "off", "auto"].includes(globalRaw.retrieval.default_profile as string)
77
+ ) {
78
+ return globalRaw.retrieval.default_profile as SearchProfile;
79
+ }
80
+
81
+ // 3. Legacy search_settings.json fallback
46
82
  try {
47
83
  if (fs.existsSync(SETTINGS_FILE)) {
48
84
  const data = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf-8"));
@@ -56,23 +92,31 @@ export function loadPersistedProfile(): SearchProfile {
56
92
  } catch (e) {
57
93
  kernelDebug(e);
58
94
  }
59
- const kernelCfg = loadKernelConfig();
60
- return (kernelCfg.retrieval.default_profile as SearchProfile) || "lean";
95
+
96
+ // 4. Canonical hardcoded default fallback
97
+ return "lean";
61
98
  }
62
99
 
63
100
  /**
64
- * Persist search settings to disk.
101
+ * Persist search settings to disk and config.toml.
65
102
  */
66
- export function savePersistedProfile(profile: SearchProfile): void {
103
+ export function savePersistedProfile(profile: SearchProfile, cwd?: string): void {
67
104
  try {
68
- const dir = path.dirname(SETTINGS_FILE);
69
- if (!fs.existsSync(dir)) {
70
- fs.mkdirSync(dir, { recursive: true });
105
+ if (cwd) {
106
+ // Workspace-local profile update: writes only to project-local config.toml
107
+ saveProjectKernelConfig(cwd, { retrieval: { default_profile: profile as any } });
108
+ } else {
109
+ // Global profile update: writes to global ~/.pi/agent/config.toml and legacy search_settings.json
110
+ saveGlobalKernelConfig({ retrieval: { default_profile: profile as any } });
111
+ const dir = path.dirname(SETTINGS_FILE);
112
+ if (!fs.existsSync(dir)) {
113
+ fs.mkdirSync(dir, { recursive: true });
114
+ }
115
+ writeFileSyncAtomic(
116
+ SETTINGS_FILE,
117
+ JSON.stringify({ profile, updatedAt: new Date().toISOString() }, null, 2),
118
+ );
71
119
  }
72
- writeFileSyncAtomic(
73
- SETTINGS_FILE,
74
- JSON.stringify({ profile, updatedAt: new Date().toISOString() }, null, 2),
75
- );
76
120
  } catch (e) {
77
121
  kernelDebug(e);
78
122
  }
@@ -84,8 +128,9 @@ export function savePersistedProfile(profile: SearchProfile): void {
84
128
  */
85
129
  export function getSearchConfig(
86
130
  requestedProfile?: SearchProfile,
131
+ cwd?: string,
87
132
  ): SearchConfig {
88
- const profile = requestedProfile || loadPersistedProfile();
133
+ const profile = requestedProfile || loadPersistedProfile(cwd);
89
134
  const effectiveProfile: "lean" | "hybrid" | "full" | "off" =
90
135
  profile === "auto" ? detectBestProfile() : profile || "lean";
91
136