@floydous/pi-agent-kernel 0.4.2 → 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 +48 -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 +117 -15
  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 +122 -32
  32. package/src/safety/output_clamper.ts +57 -35
  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
@@ -1,228 +0,0 @@
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 (capped at 10 lines to prevent context bloat)
177
- const requestedExtra = options.surroundingLines || 0;
178
- const extra = Math.min(10, Math.max(0, requestedExtra));
179
- const finalStart = Math.max(0, actualStartIdx - extra);
180
- const finalEnd = Math.min(lines.length - 1, endIdx + extra);
181
-
182
- const rawContent = lines.slice(finalStart, finalEnd + 1).join("\n");
183
-
184
- matches.push({
185
- name: def.name,
186
- kind: def.kind,
187
- signature: def.signature,
188
- startLine: finalStart + 1,
189
- endLine: finalEnd + 1,
190
- content: rawContent,
191
- filePath: resolvedPath,
192
- });
193
- }
194
-
195
- // Deduplicate strictly overlapping companion symbols (e.g. interface + companion const at the same lines)
196
- // Only merge if one range actually contains or directly overlaps the other (not distinct separate functions)
197
- const deduped: SymbolLocation[] = [];
198
- for (const m of matches) {
199
- const existingIdx = deduped.findIndex(
200
- (d) =>
201
- d.name.toLowerCase() === m.name.toLowerCase() &&
202
- // Overlap condition: ranges must strictly intersect
203
- d.startLine <= m.endLine && m.startLine <= d.endLine,
204
- );
205
- if (existingIdx !== -1) {
206
- const ex = deduped[existingIdx];
207
- // Merge the overlapping range
208
- const mergedStart = Math.min(ex.startLine, m.startLine);
209
- const mergedEnd = Math.max(ex.endLine, m.endLine);
210
- deduped[existingIdx] = {
211
- name: ex.name,
212
- kind: ex.kind === "interface" || ex.kind === "type" ? m.kind : ex.kind,
213
- signature: ex.signature || m.signature,
214
- startLine: mergedStart,
215
- endLine: mergedEnd,
216
- content: lines.slice(mergedStart - 1, mergedEnd).join("\n"),
217
- filePath: ex.filePath,
218
- };
219
- } else {
220
- deduped.push(m);
221
- }
222
- }
223
-
224
- return {
225
- found: deduped.length > 0,
226
- symbols: deduped,
227
- };
228
- }
@@ -1,161 +0,0 @@
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
- }
@@ -1,146 +0,0 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { Text, makeOutputText } from "../ui/tui_utils";
4
- import { searchAstSymbols } from "../retrieval/ast_search";
5
- import { globalEpistemicGuard } from "../safety/epistemic_guard";
6
- import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
7
- import type { SessionDeps } from "./context";
8
- import { formatAstSearchResults } from "./ast_search_formatter";
9
-
10
- /** Extracted from index.ts — registers the `ast_search` tool. */
11
- export function registerAstSearchTool(
12
- pi: ExtensionAPI,
13
- deps: SessionDeps,
14
- ): void {
15
- // 5. Tool: `ast_search` (Tree-sitter Structural Symbol Search)
16
- pi.registerTool({
17
- name: "ast_search",
18
- label: "Tree-sitter AST Search",
19
- description:
20
- "Search symbol declarations (functions, classes, methods, types) by AST structure across repository.",
21
- promptSnippet: "Search code declarations and signatures via Tree-sitter AST",
22
- renderShell: "default",
23
- parameters: Type.Object({
24
- name: Type.Optional(
25
- Type.String({ description: "Symbol name or substring to search" }),
26
- ),
27
- kind: Type.Optional(
28
- Type.String({
29
- description:
30
- "Kind: function | class | method | interface | type | struct | enum | variable | constant",
31
- }),
32
- ),
33
- filePattern: Type.Optional(
34
- Type.String({
35
- description: "Optional relative path substring filter",
36
- }),
37
- ),
38
- includeBody: Type.Optional(
39
- Type.Boolean({
40
- description: "Include preview of up to 25 lines (default: false)",
41
- }),
42
- ),
43
- }),
44
- async execute(
45
- _toolCallId: string,
46
- params: any,
47
- _signal: any,
48
- onUpdate: any,
49
- ctx: any,
50
- ): Promise<any> {
51
- onUpdate?.({
52
- content: [
53
- { type: "text", text: `Searching AST for "${params.name || "*"}"...` },
54
- ],
55
- });
56
-
57
- // If query specifies a filePattern with an extension, ensure its grammar is loaded
58
- if (params.filePattern) {
59
- const ext = (params.filePattern.match(/\.[a-zA-Z0-9]+$/) || [])[0]?.toLowerCase();
60
- if (ext && TreeSitterEngine.getInstance().isSupported(ext)) {
61
- await TreeSitterEngine.getInstance().loadLanguages([ext]);
62
- }
63
- }
64
-
65
- const results = searchAstSymbols(ctx.cwd, {
66
- name: params.name,
67
- kind: params.kind,
68
- filePattern: params.filePattern,
69
- includeBody: params.includeBody ?? false,
70
- });
71
-
72
- const sessionId = deps.getSessionId(ctx);
73
- for (const r of results) {
74
- const visibleRange = r.codeBlock && r.visibleEndLine
75
- ? { startLine: r.line, endLine: r.visibleEndLine }
76
- : null;
77
- if (visibleRange) {
78
- globalEpistemicGuard.recordFileRead(r.filePath, sessionId, ctx.cwd, undefined, {
79
- coverage: {
80
- complete: false,
81
- ranges: [visibleRange],
82
- },
83
- provenance: "ast_search",
84
- query: params.name,
85
- });
86
- } else {
87
- globalEpistemicGuard.recordFileSearched(r.filePath, sessionId, ctx.cwd, {
88
- coverage: {
89
- complete: false,
90
- ranges: [],
91
- },
92
- provenance: "ast_search",
93
- query: params.name,
94
- });
95
- }
96
- }
97
-
98
- if (results.length === 0) {
99
- return {
100
- content: [
101
- {
102
- type: "text",
103
- text: `No AST symbols found matching query. (Note: For string literals, error codes, or configs, use 'rg' in bash).`,
104
- },
105
- ],
106
- details: { count: 0 },
107
- };
108
- }
109
-
110
- const displayedResults = results.slice(0, 30);
111
- const formatted = formatAstSearchResults(
112
- displayedResults,
113
- params.includeBody ?? false,
114
- );
115
-
116
- return {
117
- content: [
118
- {
119
- type: "text",
120
- text: formatted,
121
- },
122
- ],
123
- details: { count: results.length },
124
- };
125
- },
126
- renderCall(args: any, theme: any, _context: any) {
127
- return makeOutputText(
128
- `${theme.fg("toolTitle", theme.bold("ast_search"))} ${theme.fg("accent", args?.name || "*")}${args?.kind ? ` [${args.kind}]` : ""}`,
129
- );
130
- },
131
- renderResult(result: any, options: any, theme: any, context: any) {
132
- if (context.isError) {
133
- const errMsg =
134
- result.content?.find((c: any) => c.type === "text")?.text ||
135
- "Search failed";
136
- return makeOutputText(`\n${theme.fg("error", errMsg)}`);
137
- }
138
- if (!options.expanded) {
139
- return new Text("", 0, 0);
140
- }
141
- const output =
142
- result.content?.find((c: any) => c.type === "text")?.text || "";
143
- return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
144
- },
145
- });
146
- }