@floydous/pi-agent-kernel 0.2.0 → 0.3.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.
@@ -1,254 +1,261 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import * as crypto from "node:crypto";
4
- import { extractFileTags, SymbolDef } from "./repomap";
5
-
6
- export interface CodeChunk {
7
- id: string; // e.g. "src/auth.ts:45-90#verifyToken"
8
- filePath: string; // Relative path
9
- absolutePath: string;
10
- startLine: number;
11
- endLine: number;
12
- symbolName: string;
13
- kind: string; // "function" | "class" | "method" | "interface" | "type" | "block"
14
- signature: string;
15
- breadcrumb: string; // e.g. "// [File: src/auth.ts] > [Class: AuthManager] > [Function: verifyToken]"
16
- content: string; // The full code block text
17
- textForEmbedding: string;// Search-optimized representation
18
- hash: string; // SHA-256 hash of content
19
- }
20
-
21
- const SUPPORTED_EXTENSIONS = new Set([
22
- ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql", ".md"
23
- ]);
24
-
25
- const IGNORED_DIRS = new Set([
26
- ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "coverage", ".pi", ".hermes", ".next", ".turbo", ".cache", "target", "vendor"
27
- ]);
28
-
29
- /**
30
- * Compute SHA-256 hash of a string.
31
- */
32
- export function computeHash(content: string): string {
33
- return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 16);
34
- }
35
-
36
- /**
37
- * Chunk a single source file into logical AST-bounded chunks.
38
- */
39
- export function chunkFile(rootDir: string, filePath: string, content?: string): CodeChunk[] {
40
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath);
41
- const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
42
-
43
- let fileContent = content;
44
- if (fileContent === undefined) {
45
- try {
46
- fileContent = fs.readFileSync(absPath, "utf-8");
47
- } catch {
48
- return [];
49
- }
50
- }
51
-
52
- const lines = fileContent.split("\n");
53
- if (lines.length === 0) return [];
54
-
55
- const ext = path.extname(absPath).toLowerCase();
56
- const chunks: CodeChunk[] = [];
57
-
58
- // 1. Extract AST symbols using extractFileTags
59
- const tags = extractFileTags(absPath, fileContent);
60
- const defs = tags.definitions.sort((a, b) => a.line - b.line);
61
-
62
- // If file has no AST definitions or is small (< 40 lines), chunk as single whole file
63
- if (defs.length === 0 || lines.length <= 40) {
64
- const wholeContent = lines.join("\n");
65
- const breadcrumb = `// [File: ${relPath}]`;
66
- const hash = computeHash(wholeContent);
67
- chunks.push({
68
- id: `${relPath}:1-${lines.length}`,
69
- filePath: relPath,
70
- absolutePath: absPath,
71
- startLine: 1,
72
- endLine: lines.length,
73
- symbolName: path.basename(relPath),
74
- kind: "file",
75
- signature: `File: ${relPath}`,
76
- breadcrumb,
77
- content: wholeContent,
78
- textForEmbedding: `${breadcrumb}\n${wholeContent.slice(0, 1500)}`,
79
- hash,
80
- });
81
- return chunks;
82
- }
83
-
84
- // 2. Map symbol spans using delimiter & indentation boundaries
85
- interface SymbolSpan {
86
- def: SymbolDef;
87
- startLine: number;
88
- endLine: number;
89
- parentClass?: string;
90
- }
91
-
92
- const spans: SymbolSpan[] = [];
93
- let currentClass: string | undefined = undefined;
94
- let currentClassEndLine = -1;
95
-
96
- for (let i = 0; i < defs.length; i++) {
97
- const def = defs[i];
98
- const startIdx = Math.max(0, def.line - 1);
99
- let endIdx = lines.length - 1;
100
-
101
- if (def.line > currentClassEndLine) {
102
- currentClass = undefined;
103
- }
104
-
105
- if (def.kind === "class") {
106
- currentClass = def.name;
107
- }
108
-
109
- if (def.endLine && def.endLine >= def.line) {
110
- // Exact AST node boundaries from Tree-sitter
111
- endIdx = Math.min(lines.length - 1, def.endLine - 1);
112
- } else if (ext === ".py") {
113
- // Python scope
114
- const defLine = lines[startIdx];
115
- const matchIndent = defLine.match(/^(\s*)/);
116
- const baseIndent = matchIndent ? matchIndent[1].length : 0;
117
-
118
- for (let j = startIdx + 1; j < lines.length; j++) {
119
- const line = lines[j];
120
- if (!line.trim() || line.trim().startsWith("#")) continue;
121
- const indent = line.match(/^(\s*)/)?.[1].length || 0;
122
- if (indent <= baseIndent) {
123
- endIdx = j - 1;
124
- break;
125
- }
126
- endIdx = j;
127
- }
128
- } else {
129
- // Brace based scope (fallback)
130
- let braceCount = 0;
131
- let foundOpenBrace = false;
132
-
133
- for (let j = startIdx; j < lines.length; j++) {
134
- const line = lines[j];
135
- for (const ch of line) {
136
- if (ch === "{") {
137
- braceCount++;
138
- foundOpenBrace = true;
139
- } else if (ch === "}") {
140
- braceCount--;
141
- }
142
- }
143
- if (foundOpenBrace && braceCount <= 0) {
144
- endIdx = j;
145
- break;
146
- }
147
- }
148
- }
149
-
150
- // Bound endLine to before next top-level def if necessary
151
- if (i + 1 < defs.length && endIdx >= defs[i + 1].line - 1 && def.kind !== "class") {
152
- endIdx = Math.min(endIdx, defs[i + 1].line - 2);
153
- }
154
-
155
- endIdx = Math.max(startIdx, Math.min(lines.length - 1, endIdx));
156
-
157
- if (def.kind === "class") {
158
- currentClassEndLine = endIdx + 1;
159
- }
160
-
161
- spans.push({
162
- def,
163
- startLine: startIdx + 1,
164
- endLine: endIdx + 1,
165
- parentClass: def.kind !== "class" && def.line <= currentClassEndLine ? currentClass : undefined,
166
- });
167
- }
168
-
169
- // 3. Construct CodeChunk objects from spans
170
- for (const span of spans) {
171
- const startIdx = span.startLine - 1;
172
- const endIdx = span.endLine - 1;
173
- const chunkLines = lines.slice(startIdx, endIdx + 1);
174
- const chunkContent = chunkLines.join("\n");
175
-
176
- if (!chunkContent.trim()) continue;
177
-
178
- let breadcrumb = `// [File: ${relPath}]`;
179
- if (span.parentClass) {
180
- breadcrumb += ` > [Class: ${span.parentClass}]`;
181
- }
182
- breadcrumb += ` > [${span.def.kind.toUpperCase()}: ${span.def.name}]`;
183
-
184
- const textForEmbedding = `${breadcrumb}\nSignature: ${span.def.signature}\n\n${chunkContent.slice(0, 1500)}`;
185
- const hash = computeHash(chunkContent);
186
-
187
- chunks.push({
188
- id: `${relPath}:${span.startLine}-${span.endLine}#${span.def.name}`,
189
- filePath: relPath,
190
- absolutePath: absPath,
191
- startLine: span.startLine,
192
- endLine: span.endLine,
193
- symbolName: span.def.name,
194
- kind: span.def.kind,
195
- signature: span.def.signature,
196
- breadcrumb,
197
- content: chunkContent,
198
- textForEmbedding,
199
- hash,
200
- });
201
- }
202
-
203
- return chunks;
204
- }
205
-
206
- /**
207
- * Find supported source files in a workspace using the same traversal policy as
208
- * chunkWorkspace. The search index uses this to check live file freshness
209
- * without reparsing unchanged files.
210
- */
211
- export function findChunkableFiles(rootDir: string, maxFiles = 500): string[] {
212
- const files: string[] = [];
213
-
214
- function scan(dir: string) {
215
- if (files.length >= maxFiles) return;
216
- let entries: fs.Dirent[];
217
- try {
218
- entries = fs.readdirSync(dir, { withFileTypes: true });
219
- } catch {
220
- return;
221
- }
222
-
223
- for (const entry of entries) {
224
- if (entry.name.startsWith(".") && entry.name !== ".github") continue;
225
- if (IGNORED_DIRS.has(entry.name)) continue;
226
-
227
- const fullPath = path.join(dir, entry.name);
228
- if (entry.isDirectory()) {
229
- scan(fullPath);
230
- } else if (entry.isFile()) {
231
- const ext = path.extname(entry.name).toLowerCase();
232
- if (SUPPORTED_EXTENSIONS.has(ext)) {
233
- files.push(fullPath);
234
- if (files.length >= maxFiles) return;
235
- }
236
- }
237
- }
238
- }
239
-
240
- scan(rootDir);
241
- return files;
242
- }
243
-
244
- /**
245
- * Scan workspace and chunk all supported source files.
246
- */
247
- export function chunkWorkspace(rootDir: string, maxFiles = 500): { chunks: CodeChunk[]; fileCount: number } {
248
- const files = findChunkableFiles(rootDir, maxFiles);
249
- const chunks: CodeChunk[] = [];
250
- for (const filePath of files) {
251
- chunks.push(...chunkFile(rootDir, filePath));
252
- }
253
- return { chunks, fileCount: files.length };
254
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as crypto from "node:crypto";
4
+ import { extractFileTags, SymbolDef } from "./repomap";
5
+
6
+ export interface CodeChunk {
7
+ id: string; // e.g. "src/auth.ts:45-90#verifyToken"
8
+ filePath: string; // Relative path
9
+ absolutePath: string;
10
+ startLine: number;
11
+ endLine: number;
12
+ symbolName: string;
13
+ kind: string; // "function" | "class" | "method" | "interface" | "type" | "block"
14
+ signature: string;
15
+ breadcrumb: string; // e.g. "// [File: src/auth.ts] > [Class: AuthManager] > [Function: verifyToken]"
16
+ content: string; // The full code block text
17
+ textForEmbedding: string;// Search-optimized representation
18
+ hash: string; // SHA-256 hash of content
19
+ }
20
+
21
+ const SUPPORTED_EXTENSIONS = new Set([
22
+ ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql", ".md", ".mdx", ".txt", ".rst"
23
+ ]);
24
+
25
+ const IGNORED_DIRS = new Set([
26
+ ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "coverage", ".pi", ".hermes", ".next", ".turbo", ".cache", "target", "vendor"
27
+ ]);
28
+
29
+ /** Prose extensions are excluded from the default code-search scope. */
30
+ export const PROSE_EXTENSIONS = new Set([".md", ".mdx", ".txt", ".rst"]);
31
+
32
+ export function isProseFilePath(filePath: string): boolean {
33
+ return PROSE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
34
+ }
35
+
36
+ /**
37
+ * Compute SHA-256 hash of a string.
38
+ */
39
+ export function computeHash(content: string): string {
40
+ return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 16);
41
+ }
42
+
43
+ /**
44
+ * Chunk a single source file into logical AST-bounded chunks.
45
+ */
46
+ export function chunkFile(rootDir: string, filePath: string, content?: string): CodeChunk[] {
47
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath);
48
+ const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
49
+
50
+ let fileContent = content;
51
+ if (fileContent === undefined) {
52
+ try {
53
+ fileContent = fs.readFileSync(absPath, "utf-8");
54
+ } catch {
55
+ return [];
56
+ }
57
+ }
58
+
59
+ const lines = fileContent.split("\n");
60
+ if (lines.length === 0) return [];
61
+
62
+ const ext = path.extname(absPath).toLowerCase();
63
+ const chunks: CodeChunk[] = [];
64
+
65
+ // 1. Extract AST symbols using extractFileTags
66
+ const tags = extractFileTags(absPath, fileContent);
67
+ const defs = tags.definitions.sort((a, b) => a.line - b.line);
68
+
69
+ // If file has no AST definitions or is small (< 40 lines), chunk as single whole file
70
+ if (defs.length === 0 || lines.length <= 40) {
71
+ const wholeContent = lines.join("\n");
72
+ const breadcrumb = `// [File: ${relPath}]`;
73
+ const hash = computeHash(wholeContent);
74
+ chunks.push({
75
+ id: `${relPath}:1-${lines.length}`,
76
+ filePath: relPath,
77
+ absolutePath: absPath,
78
+ startLine: 1,
79
+ endLine: lines.length,
80
+ symbolName: path.basename(relPath),
81
+ kind: "file",
82
+ signature: `File: ${relPath}`,
83
+ breadcrumb,
84
+ content: wholeContent,
85
+ textForEmbedding: `${breadcrumb}\n${wholeContent.slice(0, 1500)}`,
86
+ hash,
87
+ });
88
+ return chunks;
89
+ }
90
+
91
+ // 2. Map symbol spans using delimiter & indentation boundaries
92
+ interface SymbolSpan {
93
+ def: SymbolDef;
94
+ startLine: number;
95
+ endLine: number;
96
+ parentClass?: string;
97
+ }
98
+
99
+ const spans: SymbolSpan[] = [];
100
+ let currentClass: string | undefined = undefined;
101
+ let currentClassEndLine = -1;
102
+
103
+ for (let i = 0; i < defs.length; i++) {
104
+ const def = defs[i];
105
+ const startIdx = Math.max(0, def.line - 1);
106
+ let endIdx = lines.length - 1;
107
+
108
+ if (def.line > currentClassEndLine) {
109
+ currentClass = undefined;
110
+ }
111
+
112
+ if (def.kind === "class") {
113
+ currentClass = def.name;
114
+ }
115
+
116
+ if (def.endLine && def.endLine >= def.line) {
117
+ // Exact AST node boundaries from Tree-sitter
118
+ endIdx = Math.min(lines.length - 1, def.endLine - 1);
119
+ } else if (ext === ".py") {
120
+ // Python scope
121
+ const defLine = lines[startIdx];
122
+ const matchIndent = defLine.match(/^(\s*)/);
123
+ const baseIndent = matchIndent ? matchIndent[1].length : 0;
124
+
125
+ for (let j = startIdx + 1; j < lines.length; j++) {
126
+ const line = lines[j];
127
+ if (!line.trim() || line.trim().startsWith("#")) continue;
128
+ const indent = line.match(/^(\s*)/)?.[1].length || 0;
129
+ if (indent <= baseIndent) {
130
+ endIdx = j - 1;
131
+ break;
132
+ }
133
+ endIdx = j;
134
+ }
135
+ } else {
136
+ // Brace based scope (fallback)
137
+ let braceCount = 0;
138
+ let foundOpenBrace = false;
139
+
140
+ for (let j = startIdx; j < lines.length; j++) {
141
+ const line = lines[j];
142
+ for (const ch of line) {
143
+ if (ch === "{") {
144
+ braceCount++;
145
+ foundOpenBrace = true;
146
+ } else if (ch === "}") {
147
+ braceCount--;
148
+ }
149
+ }
150
+ if (foundOpenBrace && braceCount <= 0) {
151
+ endIdx = j;
152
+ break;
153
+ }
154
+ }
155
+ }
156
+
157
+ // Bound endLine to before next top-level def if necessary
158
+ if (i + 1 < defs.length && endIdx >= defs[i + 1].line - 1 && def.kind !== "class") {
159
+ endIdx = Math.min(endIdx, defs[i + 1].line - 2);
160
+ }
161
+
162
+ endIdx = Math.max(startIdx, Math.min(lines.length - 1, endIdx));
163
+
164
+ if (def.kind === "class") {
165
+ currentClassEndLine = endIdx + 1;
166
+ }
167
+
168
+ spans.push({
169
+ def,
170
+ startLine: startIdx + 1,
171
+ endLine: endIdx + 1,
172
+ parentClass: def.kind !== "class" && def.line <= currentClassEndLine ? currentClass : undefined,
173
+ });
174
+ }
175
+
176
+ // 3. Construct CodeChunk objects from spans
177
+ for (const span of spans) {
178
+ const startIdx = span.startLine - 1;
179
+ const endIdx = span.endLine - 1;
180
+ const chunkLines = lines.slice(startIdx, endIdx + 1);
181
+ const chunkContent = chunkLines.join("\n");
182
+
183
+ if (!chunkContent.trim()) continue;
184
+
185
+ let breadcrumb = `// [File: ${relPath}]`;
186
+ if (span.parentClass) {
187
+ breadcrumb += ` > [Class: ${span.parentClass}]`;
188
+ }
189
+ breadcrumb += ` > [${span.def.kind.toUpperCase()}: ${span.def.name}]`;
190
+
191
+ const textForEmbedding = `${breadcrumb}\nSignature: ${span.def.signature}\n\n${chunkContent.slice(0, 1500)}`;
192
+ const hash = computeHash(chunkContent);
193
+
194
+ chunks.push({
195
+ id: `${relPath}:${span.startLine}-${span.endLine}#${span.def.name}`,
196
+ filePath: relPath,
197
+ absolutePath: absPath,
198
+ startLine: span.startLine,
199
+ endLine: span.endLine,
200
+ symbolName: span.def.name,
201
+ kind: span.def.kind,
202
+ signature: span.def.signature,
203
+ breadcrumb,
204
+ content: chunkContent,
205
+ textForEmbedding,
206
+ hash,
207
+ });
208
+ }
209
+
210
+ return chunks;
211
+ }
212
+
213
+ /**
214
+ * Find supported source files in a workspace using the same traversal policy as
215
+ * chunkWorkspace. The search index uses this to check live file freshness
216
+ * without reparsing unchanged files.
217
+ */
218
+ export function findChunkableFiles(rootDir: string, maxFiles = 500): string[] {
219
+ const files: string[] = [];
220
+
221
+ function scan(dir: string) {
222
+ if (files.length >= maxFiles) return;
223
+ let entries: fs.Dirent[];
224
+ try {
225
+ entries = fs.readdirSync(dir, { withFileTypes: true });
226
+ } catch {
227
+ return;
228
+ }
229
+
230
+ for (const entry of entries) {
231
+ if (entry.name.startsWith(".") && entry.name !== ".github") continue;
232
+ if (IGNORED_DIRS.has(entry.name)) continue;
233
+
234
+ const fullPath = path.join(dir, entry.name);
235
+ if (entry.isDirectory()) {
236
+ scan(fullPath);
237
+ } else if (entry.isFile()) {
238
+ const ext = path.extname(entry.name).toLowerCase();
239
+ if (SUPPORTED_EXTENSIONS.has(ext)) {
240
+ files.push(fullPath);
241
+ if (files.length >= maxFiles) return;
242
+ }
243
+ }
244
+ }
245
+ }
246
+
247
+ scan(rootDir);
248
+ return files;
249
+ }
250
+
251
+ /**
252
+ * Scan workspace and chunk all supported source files.
253
+ */
254
+ export function chunkWorkspace(rootDir: string, maxFiles = 500): { chunks: CodeChunk[]; fileCount: number } {
255
+ const files = findChunkableFiles(rootDir, maxFiles);
256
+ const chunks: CodeChunk[] = [];
257
+ for (const filePath of files) {
258
+ chunks.push(...chunkFile(rootDir, filePath));
259
+ }
260
+ return { chunks, fileCount: files.length };
261
+ }
@@ -7,6 +7,7 @@ import {
7
7
  chunkFile,
8
8
  computeHash,
9
9
  findChunkableFiles,
10
+ isProseFilePath,
10
11
  } from "./search_chunker";
11
12
  import { BM25Engine } from "./search_bm25";
12
13
  import { LocalEmbedder } from "./search_embedder";
@@ -571,6 +572,8 @@ export class HybridSearchIndex {
571
572
  profile?: SearchProfile;
572
573
  /** Bounded RRF smoothing constant; defaults to 60. */
573
574
  rrfK?: number;
575
+ /** Search scope. Code is the default; all/prose are explicit opt-ins. */
576
+ scope?: "code" | "all" | "prose";
574
577
  } = {},
575
578
  ): Promise<SearchHit[]> {
576
579
  // Do not return the previous snapshot while a background synchronization
@@ -589,12 +592,27 @@ export class HybridSearchIndex {
589
592
 
590
593
  const limit = options.limit || 5;
591
594
  const k = Math.max(1, Math.min(Math.floor(options.rrfK ?? 60), 200));
595
+ const scope = options.scope ?? "code";
596
+ const isProsePath = isProseFilePath;
597
+ const matchesScope = (chunk: CodeChunk): boolean => {
598
+ const isProse = isProsePath(chunk.filePath);
599
+ return scope === "all" || (scope === "prose" ? isProse : !isProse);
600
+ };
601
+ const matchesFilePattern = (chunk: CodeChunk): boolean =>
602
+ !options.filePattern ||
603
+ chunk.filePath
604
+ .replace(/\\/g, "/")
605
+ .toLowerCase()
606
+ .includes(options.filePattern.replace(/\\/g, "/").toLowerCase());
592
607
  const activeConfig = options.profile
593
608
  ? getSearchConfig(options.profile)
594
609
  : this.config;
595
610
 
596
611
  // 1. BM25 Search (Instant AST-tokenized lexical retrieval)
597
- const bm25Results = this.bm25.search(query, 100);
612
+ const bm25Results = this.bm25.search(query, 100, (chunkId) => {
613
+ const chunk = this.chunks.get(chunkId);
614
+ return !!chunk && matchesScope(chunk) && matchesFilePattern(chunk);
615
+ });
598
616
  const bm25RankMap = new Map<
599
617
  string,
600
618
  { rank: number; score: number; matches: string[] }
@@ -620,6 +638,8 @@ export class HybridSearchIndex {
620
638
  if (queryVec) {
621
639
  const vecScores: { chunkId: string; score: number }[] = [];
622
640
  for (const [chunkId, vec] of this.vectors.entries()) {
641
+ const chunk = this.chunks.get(chunkId);
642
+ if (!chunk || !matchesScope(chunk) || !matchesFilePattern(chunk)) continue;
623
643
  const score = LocalEmbedder.cosineSimilarity(queryVec, vec);
624
644
  vecScores.push({ chunkId, score });
625
645
  }
@@ -649,15 +669,6 @@ export class HybridSearchIndex {
649
669
  const chunk = this.chunks.get(chunkId);
650
670
  if (!chunk) continue;
651
671
 
652
- if (
653
- options.filePattern &&
654
- !chunk.filePath
655
- .replace(/\\/g, "/")
656
- .toLowerCase()
657
- .includes(options.filePattern.replace(/\\/g, "/").toLowerCase())
658
- ) {
659
- continue;
660
- }
661
672
 
662
673
  const bmData = bm25RankMap.get(chunkId);
663
674
  const vecData = vectorRankMap.get(chunkId);