@floydous/pi-agent-kernel 0.2.0 → 0.3.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.
- package/CHANGELOG.md +25 -0
- package/README.md +73 -86
- package/docs/testing.md +10 -9
- package/package.json +5 -4
- package/src/dedup/content_store.ts +365 -365
- package/src/index.ts +918 -918
- package/src/retrieval/ast_search.ts +930 -930
- package/src/retrieval/repomap.ts +192 -7
- package/src/retrieval/search_bm25.ts +190 -190
- package/src/retrieval/search_chunker.ts +254 -254
- package/src/retrieval/symbol_reader.ts +198 -203
- package/src/retrieval/tree_sitter_engine.ts +1 -1
- package/src/safety/epistemic_guard.ts +8 -1
- package/src/tools/ast_search_formatter.ts +161 -0
- package/src/tools/ast_search_tool.ts +17 -10
- package/src/tools/context.ts +20 -20
- package/src/tools/lsp_tool.ts +13 -2
- package/src/ui/tui_utils.ts +278 -278
- package/static/with-agent-kernel.png +0 -0
- package/static/without-agent-kernel-1.png +0 -0
- package/static/without-agent-kernel-2.png +0 -0
- package/static/without-agent-kernel-3.png +0 -0
|
@@ -1,203 +1,198 @@
|
|
|
1
|
-
import * as fs from "fs";
|
|
2
|
-
import * as path from "path";
|
|
3
|
-
import { extractFileTags, SymbolDef } from "./repomap";
|
|
4
|
-
|
|
5
|
-
export interface SymbolLocation {
|
|
6
|
-
name: string;
|
|
7
|
-
kind: string;
|
|
8
|
-
signature: string;
|
|
9
|
-
startLine: number;
|
|
10
|
-
endLine: number;
|
|
11
|
-
content: string;
|
|
12
|
-
filePath: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Extract exact start and end line range for a symbol in a file.
|
|
17
|
-
*/
|
|
18
|
-
export function extractSymbolContent(
|
|
19
|
-
filePath: string,
|
|
20
|
-
targetSymbol: string,
|
|
21
|
-
options: { surroundingLines?: number } = {},
|
|
22
|
-
fileContentOverride?: string,
|
|
23
|
-
): { found: boolean; symbols: SymbolLocation[]; error?: string } {
|
|
24
|
-
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
25
|
-
|
|
26
|
-
if (!fs.existsSync(resolvedPath)) {
|
|
27
|
-
return { found: false, symbols: [], error: `File not found: ${resolvedPath}` };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
let fileContent: string;
|
|
31
|
-
if (fileContentOverride !== undefined) {
|
|
32
|
-
fileContent = fileContentOverride;
|
|
33
|
-
} else {
|
|
34
|
-
try {
|
|
35
|
-
fileContent = fs.readFileSync(resolvedPath, "utf-8");
|
|
36
|
-
} catch (e: any) {
|
|
37
|
-
return { found: false, symbols: [], error: `Unable to read file: ${e.message}` };
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const lines = fileContent.split("\n");
|
|
42
|
-
const tags = extractFileTags(resolvedPath, fileContent);
|
|
43
|
-
const ext = path.extname(resolvedPath).toLowerCase();
|
|
44
|
-
|
|
45
|
-
const matches: SymbolLocation[] = [];
|
|
46
|
-
|
|
47
|
-
// Search matching definitions in tags
|
|
48
|
-
const matchingDefs = tags.definitions.filter(
|
|
49
|
-
(d) => d.name === targetSymbol || d.name.toLowerCase() === targetSymbol.toLowerCase()
|
|
50
|
-
);
|
|
51
|
-
|
|
52
|
-
if (matchingDefs.length === 0) {
|
|
53
|
-
// Fallback: search for symbol with regex across all occurrences if tags missed it
|
|
54
|
-
const escaped = targetSymbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
55
|
-
const regex = new RegExp(`(?:def|class|function|async function|const|let|var|type|interface)\\s+${escaped}\\b`, "i");
|
|
56
|
-
for (let i = 0; i < lines.length; i++) {
|
|
57
|
-
if (regex.test(lines[i])) {
|
|
58
|
-
matchingDefs.push({
|
|
59
|
-
name: targetSymbol,
|
|
60
|
-
kind: lines[i].includes("class") ? "class" : "function",
|
|
61
|
-
signature: lines[i].trim(),
|
|
62
|
-
line: i + 1,
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
for (const def of matchingDefs) {
|
|
69
|
-
const startIdx = def.line - 1;
|
|
70
|
-
let endIdx = startIdx;
|
|
71
|
-
|
|
72
|
-
// Include preceding docstrings/comments/decorators if present
|
|
73
|
-
let actualStartIdx = startIdx;
|
|
74
|
-
while (actualStartIdx > 0) {
|
|
75
|
-
const prevLine = lines[actualStartIdx - 1].trim();
|
|
76
|
-
if (prevLine.startsWith("#") || prevLine.startsWith("//") || prevLine.startsWith("*") || prevLine.startsWith("/*") || prevLine.startsWith("@")) {
|
|
77
|
-
actualStartIdx--;
|
|
78
|
-
} else {
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
if (def.endLine && def.endLine >= def.line) {
|
|
84
|
-
// Ground-truth AST range provided directly by Tree-sitter
|
|
85
|
-
endIdx = Math.min(lines.length - 1, def.endLine - 1);
|
|
86
|
-
} else if (ext === ".py") {
|
|
87
|
-
// Python indentation based boundary detection
|
|
88
|
-
const defLine = lines[startIdx];
|
|
89
|
-
const matchIndent = defLine.match(/^(\s*)/);
|
|
90
|
-
const baseIndent = matchIndent ? matchIndent[1].length : 0;
|
|
91
|
-
|
|
92
|
-
// Handle multi-line Python signatures (e.g. def foo(\n arg: int\n) -> bool:)
|
|
93
|
-
let headerEndIdx = startIdx;
|
|
94
|
-
let parenCount = 0;
|
|
95
|
-
for (let i = startIdx; i < lines.length; i++) {
|
|
96
|
-
const line = lines[i];
|
|
97
|
-
for (const ch of line) {
|
|
98
|
-
if (ch === "(") parenCount++;
|
|
99
|
-
else if (ch === ")") parenCount--;
|
|
100
|
-
}
|
|
101
|
-
if (parenCount <= 0 && line.trim().endsWith(":")) {
|
|
102
|
-
headerEndIdx = i;
|
|
103
|
-
break;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
let inDocstring = false;
|
|
108
|
-
let docstringQuote = "";
|
|
109
|
-
|
|
110
|
-
for (let i = headerEndIdx + 1; i < lines.length; i++) {
|
|
111
|
-
const currentLine = lines[i];
|
|
112
|
-
const trimmed = currentLine.trim();
|
|
113
|
-
|
|
114
|
-
if (!trimmed) {
|
|
115
|
-
endIdx = i;
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Check docstrings
|
|
120
|
-
if (!inDocstring) {
|
|
121
|
-
if (trimmed.startsWith('"""') || trimmed.startsWith("'''")) {
|
|
122
|
-
docstringQuote = trimmed.slice(0, 3);
|
|
123
|
-
if (trimmed.length === 3 || !trimmed.slice(3).includes(docstringQuote)) {
|
|
124
|
-
inDocstring = true;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
} else {
|
|
128
|
-
if (trimmed.includes(docstringQuote)) {
|
|
129
|
-
inDocstring = false;
|
|
130
|
-
}
|
|
131
|
-
endIdx = i;
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
if (inDocstring) {
|
|
136
|
-
endIdx = i;
|
|
137
|
-
continue;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
if (trimmed.startsWith("#")) {
|
|
141
|
-
endIdx = i;
|
|
142
|
-
continue;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
const currIndent = currentLine.match(/^(\s*)/)?.[1].length || 0;
|
|
146
|
-
if (currIndent <= baseIndent) {
|
|
147
|
-
break;
|
|
148
|
-
}
|
|
149
|
-
endIdx = i;
|
|
150
|
-
}
|
|
151
|
-
} else {
|
|
152
|
-
// Brace-based languages (fallback if AST endLine is unavailable)
|
|
153
|
-
let braceCount = 0;
|
|
154
|
-
let foundOpenBrace = false;
|
|
155
|
-
|
|
156
|
-
for (let i = startIdx; i < lines.length; i++) {
|
|
157
|
-
const currentLine = lines[i];
|
|
158
|
-
|
|
159
|
-
for (let charIdx = 0; charIdx < currentLine.length; charIdx++) {
|
|
160
|
-
const char = currentLine[charIdx];
|
|
161
|
-
if (char === "{") {
|
|
162
|
-
braceCount++;
|
|
163
|
-
foundOpenBrace = true;
|
|
164
|
-
} else if (char === "}") {
|
|
165
|
-
braceCount--;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
endIdx = i;
|
|
170
|
-
if (foundOpenBrace && braceCount <= 0) {
|
|
171
|
-
break;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Apply surrounding context if requested
|
|
177
|
-
const extra = options.surroundingLines || 0;
|
|
178
|
-
const finalStart = Math.max(0, actualStartIdx - extra);
|
|
179
|
-
const finalEnd = Math.min(lines.length - 1, endIdx + extra);
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
return {
|
|
200
|
-
found: matches.length > 0,
|
|
201
|
-
symbols: matches,
|
|
202
|
-
};
|
|
203
|
-
}
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { extractFileTags, SymbolDef } from "./repomap";
|
|
4
|
+
|
|
5
|
+
export interface SymbolLocation {
|
|
6
|
+
name: string;
|
|
7
|
+
kind: string;
|
|
8
|
+
signature: string;
|
|
9
|
+
startLine: number;
|
|
10
|
+
endLine: number;
|
|
11
|
+
content: string;
|
|
12
|
+
filePath: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Extract exact start and end line range for a symbol in a file.
|
|
17
|
+
*/
|
|
18
|
+
export function extractSymbolContent(
|
|
19
|
+
filePath: string,
|
|
20
|
+
targetSymbol: string,
|
|
21
|
+
options: { surroundingLines?: number } = {},
|
|
22
|
+
fileContentOverride?: string,
|
|
23
|
+
): { found: boolean; symbols: SymbolLocation[]; error?: string } {
|
|
24
|
+
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
|
|
25
|
+
|
|
26
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
27
|
+
return { found: false, symbols: [], error: `File not found: ${resolvedPath}` };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let fileContent: string;
|
|
31
|
+
if (fileContentOverride !== undefined) {
|
|
32
|
+
fileContent = fileContentOverride;
|
|
33
|
+
} else {
|
|
34
|
+
try {
|
|
35
|
+
fileContent = fs.readFileSync(resolvedPath, "utf-8");
|
|
36
|
+
} catch (e: any) {
|
|
37
|
+
return { found: false, symbols: [], error: `Unable to read file: ${e.message}` };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const lines = fileContent.split("\n");
|
|
42
|
+
const tags = extractFileTags(resolvedPath, fileContent);
|
|
43
|
+
const ext = path.extname(resolvedPath).toLowerCase();
|
|
44
|
+
|
|
45
|
+
const matches: SymbolLocation[] = [];
|
|
46
|
+
|
|
47
|
+
// Search matching definitions in tags
|
|
48
|
+
const matchingDefs = tags.definitions.filter(
|
|
49
|
+
(d) => d.name === targetSymbol || d.name.toLowerCase() === targetSymbol.toLowerCase()
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
if (matchingDefs.length === 0) {
|
|
53
|
+
// Fallback: search for symbol with regex across all occurrences if tags missed it
|
|
54
|
+
const escaped = targetSymbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
55
|
+
const regex = new RegExp(`(?:def|class|function|async function|const|let|var|type|interface)\\s+${escaped}\\b`, "i");
|
|
56
|
+
for (let i = 0; i < lines.length; i++) {
|
|
57
|
+
if (regex.test(lines[i])) {
|
|
58
|
+
matchingDefs.push({
|
|
59
|
+
name: targetSymbol,
|
|
60
|
+
kind: lines[i].includes("class") ? "class" : "function",
|
|
61
|
+
signature: lines[i].trim(),
|
|
62
|
+
line: i + 1,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
for (const def of matchingDefs) {
|
|
69
|
+
const startIdx = def.line - 1;
|
|
70
|
+
let endIdx = startIdx;
|
|
71
|
+
|
|
72
|
+
// Include preceding docstrings/comments/decorators if present
|
|
73
|
+
let actualStartIdx = startIdx;
|
|
74
|
+
while (actualStartIdx > 0) {
|
|
75
|
+
const prevLine = lines[actualStartIdx - 1].trim();
|
|
76
|
+
if (prevLine.startsWith("#") || prevLine.startsWith("//") || prevLine.startsWith("*") || prevLine.startsWith("/*") || prevLine.startsWith("@")) {
|
|
77
|
+
actualStartIdx--;
|
|
78
|
+
} else {
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (def.endLine && def.endLine >= def.line) {
|
|
84
|
+
// Ground-truth AST range provided directly by Tree-sitter
|
|
85
|
+
endIdx = Math.min(lines.length - 1, def.endLine - 1);
|
|
86
|
+
} else if (ext === ".py") {
|
|
87
|
+
// Python indentation based boundary detection
|
|
88
|
+
const defLine = lines[startIdx];
|
|
89
|
+
const matchIndent = defLine.match(/^(\s*)/);
|
|
90
|
+
const baseIndent = matchIndent ? matchIndent[1].length : 0;
|
|
91
|
+
|
|
92
|
+
// Handle multi-line Python signatures (e.g. def foo(\n arg: int\n) -> bool:)
|
|
93
|
+
let headerEndIdx = startIdx;
|
|
94
|
+
let parenCount = 0;
|
|
95
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
96
|
+
const line = lines[i];
|
|
97
|
+
for (const ch of line) {
|
|
98
|
+
if (ch === "(") parenCount++;
|
|
99
|
+
else if (ch === ")") parenCount--;
|
|
100
|
+
}
|
|
101
|
+
if (parenCount <= 0 && line.trim().endsWith(":")) {
|
|
102
|
+
headerEndIdx = i;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let inDocstring = false;
|
|
108
|
+
let docstringQuote = "";
|
|
109
|
+
|
|
110
|
+
for (let i = headerEndIdx + 1; i < lines.length; i++) {
|
|
111
|
+
const currentLine = lines[i];
|
|
112
|
+
const trimmed = currentLine.trim();
|
|
113
|
+
|
|
114
|
+
if (!trimmed) {
|
|
115
|
+
endIdx = i;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Check docstrings
|
|
120
|
+
if (!inDocstring) {
|
|
121
|
+
if (trimmed.startsWith('"""') || trimmed.startsWith("'''")) {
|
|
122
|
+
docstringQuote = trimmed.slice(0, 3);
|
|
123
|
+
if (trimmed.length === 3 || !trimmed.slice(3).includes(docstringQuote)) {
|
|
124
|
+
inDocstring = true;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
if (trimmed.includes(docstringQuote)) {
|
|
129
|
+
inDocstring = false;
|
|
130
|
+
}
|
|
131
|
+
endIdx = i;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (inDocstring) {
|
|
136
|
+
endIdx = i;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (trimmed.startsWith("#")) {
|
|
141
|
+
endIdx = i;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const currIndent = currentLine.match(/^(\s*)/)?.[1].length || 0;
|
|
146
|
+
if (currIndent <= baseIndent) {
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
endIdx = i;
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
// Brace-based languages (fallback if AST endLine is unavailable)
|
|
153
|
+
let braceCount = 0;
|
|
154
|
+
let foundOpenBrace = false;
|
|
155
|
+
|
|
156
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
157
|
+
const currentLine = lines[i];
|
|
158
|
+
|
|
159
|
+
for (let charIdx = 0; charIdx < currentLine.length; charIdx++) {
|
|
160
|
+
const char = currentLine[charIdx];
|
|
161
|
+
if (char === "{") {
|
|
162
|
+
braceCount++;
|
|
163
|
+
foundOpenBrace = true;
|
|
164
|
+
} else if (char === "}") {
|
|
165
|
+
braceCount--;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
endIdx = i;
|
|
170
|
+
if (foundOpenBrace && braceCount <= 0) {
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Apply surrounding context if requested
|
|
177
|
+
const extra = options.surroundingLines || 0;
|
|
178
|
+
const finalStart = Math.max(0, actualStartIdx - extra);
|
|
179
|
+
const finalEnd = Math.min(lines.length - 1, endIdx + extra);
|
|
180
|
+
|
|
181
|
+
const rawContent = lines.slice(finalStart, finalEnd + 1).join("\n");
|
|
182
|
+
|
|
183
|
+
matches.push({
|
|
184
|
+
name: def.name,
|
|
185
|
+
kind: def.kind,
|
|
186
|
+
signature: def.signature,
|
|
187
|
+
startLine: finalStart + 1,
|
|
188
|
+
endLine: finalEnd + 1,
|
|
189
|
+
content: rawContent,
|
|
190
|
+
filePath: resolvedPath,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
found: matches.length > 0,
|
|
196
|
+
symbols: matches,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
@@ -502,7 +502,7 @@ export class TreeSitterEngine {
|
|
|
502
502
|
}
|
|
503
503
|
return;
|
|
504
504
|
} else if (type === "const_item" || type === "static_item") {
|
|
505
|
-
const isTopLevel = node.parent?.type === "source_file";
|
|
505
|
+
const isTopLevel = node.parent?.type === "source_file" || node.parent?.type === "declaration_list";
|
|
506
506
|
if (isTopLevel) {
|
|
507
507
|
const nameNode = node.childForFieldName("name");
|
|
508
508
|
if (nameNode) {
|
|
@@ -651,7 +651,14 @@ export class EpistemicGuard {
|
|
|
651
651
|
};
|
|
652
652
|
}
|
|
653
653
|
|
|
654
|
-
|
|
654
|
+
if (!exists && operation === "edit") {
|
|
655
|
+
return {
|
|
656
|
+
allowed: false,
|
|
657
|
+
reason: `[EPISTEMIC GUARD]: Target '${filePath}' does not exist.`,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// A new file has no prior contents to inspect. Containment still applies for write.
|
|
655
662
|
if (!enforceInspection || !exists) return { allowed: true };
|
|
656
663
|
|
|
657
664
|
const normalized = this.normalize(resolvedPath, workspace);
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { AstQueryResult } from "../retrieval/ast_search";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Clean signature string by removing redundant declaration keywords and access modifiers,
|
|
5
|
+
* while preserving semantic modifiers (async, static, readonly, unsafe, const, mut)
|
|
6
|
+
* and full parameter/return types.
|
|
7
|
+
*/
|
|
8
|
+
export function cleanSignature(rawSignature: string | undefined, symbolName: string | undefined): string {
|
|
9
|
+
const trimmedName = symbolName?.trim();
|
|
10
|
+
if (!rawSignature || !rawSignature.trim()) {
|
|
11
|
+
return trimmedName || "unknown";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Normalize multiline signatures to a single line
|
|
15
|
+
let sig = rawSignature.replace(/\r?\n/g, " ").replace(/\s+/g, " ").trim();
|
|
16
|
+
|
|
17
|
+
// Iteratively peel redundant leading prefixes from the start of the signature
|
|
18
|
+
let changed = true;
|
|
19
|
+
while (changed) {
|
|
20
|
+
const before = sig;
|
|
21
|
+
|
|
22
|
+
// 1. Module / declaration wrappers
|
|
23
|
+
sig = sig.replace(/^(export\s+|default\s+|declare\s+)/, "");
|
|
24
|
+
|
|
25
|
+
// 2. Visibility modifiers (TypeScript, Java, PHP, C++, Rust)
|
|
26
|
+
sig = sig.replace(/^(public\s+|private\s+|protected\s+)/, "");
|
|
27
|
+
sig = sig.replace(/^pub(\s*\([^)]*\))?\s+/, "");
|
|
28
|
+
|
|
29
|
+
// 3. Redundant kind keywords (when not preceded by async/static/unsafe)
|
|
30
|
+
// e.g. "function foo()", "def foo()", "fn foo()", "func foo()", "class Foo"
|
|
31
|
+
sig = sig.replace(/^(function\s*\*?|def\s+|fn\s+|func\s+|class\s+|interface\s+|type\s+|enum\s+|struct\s+|trait\s+)/, "");
|
|
32
|
+
|
|
33
|
+
// 4. Strip redundant kind keywords that follow preserved semantic modifiers (async, static, unsafe)
|
|
34
|
+
sig = sig.replace(/^((?:async|static|unsafe)\s+)(?:function\s*\*?|fn|def|func)\s+/, "$1");
|
|
35
|
+
|
|
36
|
+
// 5. TypeScript/ES accessors (get/set)
|
|
37
|
+
sig = sig.replace(/^(get\s+|set\s+)/, "");
|
|
38
|
+
|
|
39
|
+
// 6. Abstract modifier
|
|
40
|
+
sig = sig.replace(/^abstract\s+/, "");
|
|
41
|
+
|
|
42
|
+
sig = sig.trim();
|
|
43
|
+
changed = sig !== before;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return sig.trim() || trimmedName || "unknown";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Format raw AST search results into a compact hierarchical layout:
|
|
51
|
+
* - Each normalized file path appears once.
|
|
52
|
+
* - Symbols are grouped by kind preserving incoming rank order.
|
|
53
|
+
* - Singletons of a kind render inline: `[kind] range signature`
|
|
54
|
+
* - Multiple items of a kind render with a header and `- range signature`
|
|
55
|
+
* - Optional body preview indented with 4 spaces and truncation notice
|
|
56
|
+
*/
|
|
57
|
+
export function formatAstSearchResults(
|
|
58
|
+
results: AstQueryResult[],
|
|
59
|
+
includeBody = false,
|
|
60
|
+
): string {
|
|
61
|
+
if (!results || results.length === 0) {
|
|
62
|
+
return "";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 1. Group by normalized relative filePath preserving first-seen file order
|
|
66
|
+
const fileOrder: string[] = [];
|
|
67
|
+
const byFile = new Map<string, Map<string, AstQueryResult[]>>();
|
|
68
|
+
|
|
69
|
+
for (const r of results) {
|
|
70
|
+
const normPath = r.filePath.replace(/\\/g, "/");
|
|
71
|
+
let byKind = byFile.get(normPath);
|
|
72
|
+
if (!byKind) {
|
|
73
|
+
byKind = new Map<string, AstQueryResult[]>();
|
|
74
|
+
byFile.set(normPath, byKind);
|
|
75
|
+
fileOrder.push(normPath);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const kind = r.kind || "symbol";
|
|
79
|
+
let items = byKind.get(kind);
|
|
80
|
+
if (!items) {
|
|
81
|
+
items = [];
|
|
82
|
+
byKind.set(kind, items);
|
|
83
|
+
}
|
|
84
|
+
items.push(r);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 2. Build sections
|
|
88
|
+
const sections: string[] = [];
|
|
89
|
+
|
|
90
|
+
for (const filePath of fileOrder) {
|
|
91
|
+
const byKind = byFile.get(filePath)!;
|
|
92
|
+
const fileLines: string[] = [filePath];
|
|
93
|
+
|
|
94
|
+
for (const [kind, items] of byKind) {
|
|
95
|
+
if (items.length === 1) {
|
|
96
|
+
const r = items[0];
|
|
97
|
+
const span = formatRange(r.line, r.endLine);
|
|
98
|
+
const sig = formatSymbolSignature(r);
|
|
99
|
+
fileLines.push(`[${kind}] ${span} ${sig}`);
|
|
100
|
+
if (includeBody && (r.codeBlock !== undefined || r.bodyTruncated)) {
|
|
101
|
+
fileLines.push(indentBody(r.codeBlock, r.bodyTruncated, r.visibleEndLine));
|
|
102
|
+
}
|
|
103
|
+
} else {
|
|
104
|
+
fileLines.push(`[${kind}]`);
|
|
105
|
+
for (const r of items) {
|
|
106
|
+
const span = formatRange(r.line, r.endLine);
|
|
107
|
+
const sig = formatSymbolSignature(r);
|
|
108
|
+
fileLines.push(`- ${span} ${sig}`);
|
|
109
|
+
if (includeBody && (r.codeBlock !== undefined || r.bodyTruncated)) {
|
|
110
|
+
fileLines.push(indentBody(r.codeBlock, r.bodyTruncated, r.visibleEndLine));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
sections.push(fileLines.join("\n"));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return sections.join("\n\n");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function formatRange(startLine: number, endLine?: number): string {
|
|
123
|
+
if (endLine !== undefined && endLine !== null && endLine > startLine) {
|
|
124
|
+
return `${startLine}-${endLine}`;
|
|
125
|
+
}
|
|
126
|
+
return `${startLine}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function formatSymbolSignature(r: AstQueryResult): string {
|
|
130
|
+
const name = r.name?.trim() || "unknown";
|
|
131
|
+
let sig = cleanSignature(r.signature, r.name);
|
|
132
|
+
|
|
133
|
+
if (r.aliasedFrom && r.aliasedFrom.originalName && r.aliasedFrom.originalName !== name) {
|
|
134
|
+
const orig = r.aliasedFrom.originalName;
|
|
135
|
+
if (sig === orig) {
|
|
136
|
+
sig = name;
|
|
137
|
+
} else if (sig.startsWith(orig + "(") || sig.startsWith(orig + "<") || sig.startsWith(orig + " ")) {
|
|
138
|
+
sig = name + sig.slice(orig.length);
|
|
139
|
+
}
|
|
140
|
+
sig = `${sig} [alias of ${orig}]`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return sig;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function indentBody(codeBlock?: string, bodyTruncated?: boolean, visibleEndLine?: number): string {
|
|
147
|
+
const indentedLines: string[] = [];
|
|
148
|
+
if (codeBlock && codeBlock.trim()) {
|
|
149
|
+
for (const line of codeBlock.split("\n")) {
|
|
150
|
+
indentedLines.push(` ${line}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (bodyTruncated) {
|
|
154
|
+
if (visibleEndLine !== undefined && visibleEndLine !== null) {
|
|
155
|
+
indentedLines.push(` [... body preview truncated at line ${visibleEndLine}]`);
|
|
156
|
+
} else {
|
|
157
|
+
indentedLines.push(` [... body preview truncated]`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return indentedLines.join("\n");
|
|
161
|
+
}
|
|
@@ -3,7 +3,9 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
4
|
import { searchAstSymbols } from "../retrieval/ast_search";
|
|
5
5
|
import { globalEpistemicGuard } from "../safety/epistemic_guard";
|
|
6
|
+
import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
|
|
6
7
|
import type { SessionDeps } from "./context";
|
|
8
|
+
import { formatAstSearchResults } from "./ast_search_formatter";
|
|
7
9
|
|
|
8
10
|
/** Extracted from index.ts — registers the `ast_search` tool. */
|
|
9
11
|
export function registerAstSearchTool(
|
|
@@ -54,6 +56,15 @@ export function registerAstSearchTool(
|
|
|
54
56
|
{ type: "text", text: `Searching AST for "${params.name || "*"}"...` },
|
|
55
57
|
],
|
|
56
58
|
});
|
|
59
|
+
|
|
60
|
+
// If query specifies a filePattern with an extension, ensure its grammar is loaded
|
|
61
|
+
if (params.filePattern) {
|
|
62
|
+
const ext = (params.filePattern.match(/\.[a-zA-Z0-9]+$/) || [])[0]?.toLowerCase();
|
|
63
|
+
if (ext && TreeSitterEngine.getInstance().isSupported(ext)) {
|
|
64
|
+
await TreeSitterEngine.getInstance().loadLanguages([ext]);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
57
68
|
const results = searchAstSymbols(ctx.cwd, {
|
|
58
69
|
name: params.name,
|
|
59
70
|
kind: params.kind,
|
|
@@ -88,21 +99,17 @@ export function registerAstSearchTool(
|
|
|
88
99
|
};
|
|
89
100
|
}
|
|
90
101
|
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
str += `\n${r.codeBlock}`;
|
|
97
|
-
}
|
|
98
|
-
return str;
|
|
99
|
-
});
|
|
102
|
+
const displayedResults = results.slice(0, 30);
|
|
103
|
+
const formatted = formatAstSearchResults(
|
|
104
|
+
displayedResults,
|
|
105
|
+
params.includeBody ?? false,
|
|
106
|
+
);
|
|
100
107
|
|
|
101
108
|
return {
|
|
102
109
|
content: [
|
|
103
110
|
{
|
|
104
111
|
type: "text",
|
|
105
|
-
text: formatted
|
|
112
|
+
text: formatted,
|
|
106
113
|
},
|
|
107
114
|
],
|
|
108
115
|
details: { count: results.length },
|