@floydous/pi-agent-kernel 0.1.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/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type Focusable, matchesKey, truncateToWidth, visibleWidth } from "../ui/tui_utils";
|
|
3
|
+
import { HybridSearchIndex } from "./search_index";
|
|
4
|
+
import { SearchProfile } from "./search_config";
|
|
5
|
+
|
|
6
|
+
export interface ModalResult {
|
|
7
|
+
action: string;
|
|
8
|
+
profile?: SearchProfile;
|
|
9
|
+
reindexed?: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class SearchControlModal implements Focusable {
|
|
13
|
+
focused = false;
|
|
14
|
+
|
|
15
|
+
private tui: any;
|
|
16
|
+
private index: HybridSearchIndex;
|
|
17
|
+
private theme: Theme;
|
|
18
|
+
private done: (result: ModalResult | undefined) => void;
|
|
19
|
+
private selectedIndex = 0;
|
|
20
|
+
private initialProfile: SearchProfile;
|
|
21
|
+
|
|
22
|
+
// Menu items categorized
|
|
23
|
+
private items: Array<{
|
|
24
|
+
id: string;
|
|
25
|
+
category: "profile" | "action";
|
|
26
|
+
label: string;
|
|
27
|
+
desc: string;
|
|
28
|
+
profile?: SearchProfile;
|
|
29
|
+
}> = [
|
|
30
|
+
// Category: Profiles
|
|
31
|
+
{
|
|
32
|
+
id: "auto",
|
|
33
|
+
category: "profile",
|
|
34
|
+
profile: "auto",
|
|
35
|
+
label: "Auto Detect",
|
|
36
|
+
desc: "Auto-detect Lean (VPS), Hybrid (Laptop), or Full (Desktop)",
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
id: "lean",
|
|
40
|
+
category: "profile",
|
|
41
|
+
profile: "lean",
|
|
42
|
+
label: "Lean Mode",
|
|
43
|
+
desc: "AST BM25 (0% CPU, 0 MB extra RAM)",
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
id: "hybrid",
|
|
47
|
+
category: "profile",
|
|
48
|
+
profile: "hybrid",
|
|
49
|
+
label: "Hybrid Mode",
|
|
50
|
+
desc: "Throttled 256-dim Matryoshka embeddings",
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
id: "full",
|
|
54
|
+
category: "profile",
|
|
55
|
+
profile: "full",
|
|
56
|
+
label: "Full Mode",
|
|
57
|
+
desc: "Multi-core 768-dim embeddings",
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: "off",
|
|
61
|
+
category: "profile",
|
|
62
|
+
profile: "off",
|
|
63
|
+
label: "Disable Engine",
|
|
64
|
+
desc: "Turn off search & free memory",
|
|
65
|
+
},
|
|
66
|
+
// Category: Workspace Actions
|
|
67
|
+
{
|
|
68
|
+
id: "reindex",
|
|
69
|
+
category: "action",
|
|
70
|
+
label: "Re-index Workspace",
|
|
71
|
+
desc: "Scan all source files and rebuild index",
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
id: "close",
|
|
75
|
+
category: "action",
|
|
76
|
+
label: "Close Panel",
|
|
77
|
+
desc: "Dismiss this dialog",
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
constructor(
|
|
82
|
+
tui: any,
|
|
83
|
+
index: HybridSearchIndex,
|
|
84
|
+
theme: Theme,
|
|
85
|
+
done: (result: ModalResult | undefined) => void
|
|
86
|
+
) {
|
|
87
|
+
this.tui = tui;
|
|
88
|
+
this.index = index;
|
|
89
|
+
this.theme = theme;
|
|
90
|
+
this.done = done;
|
|
91
|
+
this.initialProfile = index.getProfile();
|
|
92
|
+
|
|
93
|
+
// Set initial cursor to current active profile
|
|
94
|
+
const currentProfile = this.initialProfile;
|
|
95
|
+
const idx = this.items.findIndex((item) => item.profile === currentProfile);
|
|
96
|
+
if (idx >= 0) this.selectedIndex = idx;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async handleInput(data: string): Promise<void> {
|
|
100
|
+
if (matchesKey(data, "escape") || matchesKey(data, "q") || matchesKey(data, "ctrl+c")) {
|
|
101
|
+
const currentProfile = this.index.getProfile();
|
|
102
|
+
const changed = currentProfile !== this.initialProfile;
|
|
103
|
+
this.done({ action: "close", profile: currentProfile, reindexed: changed });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
108
|
+
this.selectedIndex = (this.selectedIndex - 1 + this.items.length) % this.items.length;
|
|
109
|
+
this.tui?.requestRender?.();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
114
|
+
this.selectedIndex = (this.selectedIndex + 1) % this.items.length;
|
|
115
|
+
this.tui?.requestRender?.();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (matchesKey(data, "return") || matchesKey(data, "space")) {
|
|
120
|
+
const item = this.items[this.selectedIndex];
|
|
121
|
+
if (!item) return;
|
|
122
|
+
|
|
123
|
+
if (item.category === "profile" && item.profile) {
|
|
124
|
+
this.index.setProfile(item.profile);
|
|
125
|
+
const changed = item.profile !== this.initialProfile;
|
|
126
|
+
this.done({ action: "select", profile: item.profile, reindexed: changed });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (item.id === "reindex") {
|
|
131
|
+
const currentProfile = this.index.getProfile();
|
|
132
|
+
this.done({ action: "reindex", profile: currentProfile, reindexed: true });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (item.id === "close") {
|
|
137
|
+
const currentProfile = this.index.getProfile();
|
|
138
|
+
const changed = currentProfile !== this.initialProfile;
|
|
139
|
+
this.done({ action: "close", profile: currentProfile, reindexed: changed });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
render(width: number): string[] {
|
|
146
|
+
const cardWidth = Math.min(108, Math.max(20, width - 4));
|
|
147
|
+
const innerW = Math.max(1, cardWidth - 2);
|
|
148
|
+
|
|
149
|
+
const pad = (s: string, len: number) => {
|
|
150
|
+
const vis = visibleWidth(s);
|
|
151
|
+
if (vis > len) {
|
|
152
|
+
return truncateToWidth(s, len, "...");
|
|
153
|
+
}
|
|
154
|
+
return s + " ".repeat(Math.max(0, len - vis));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// Signature Dark Slate / Charcoal Minimalist Theme Palette
|
|
158
|
+
const reset = "\x1b[0m";
|
|
159
|
+
const bgCard = "\x1b[48;5;234m"; // Dark charcoal matte card background
|
|
160
|
+
|
|
161
|
+
// Clean Monochrome & Dark Slate Foreground Colors (TrueColor with fallback-safe ANSI escapes)
|
|
162
|
+
const fgBorder = "\x1b[38;5;240m"; // Refined dark slate/gray border (#585858)
|
|
163
|
+
const fgTitle = "\x1b[1;38;5;255m"; // Pure crisp white bold title
|
|
164
|
+
const fgSubHeader = "\x1b[1;38;5;250m"; // Light silver bold for section headers (#bcbcbc)
|
|
165
|
+
const fgActive = "\x1b[1;38;5;255m"; // Pure white highlight for active/selected item
|
|
166
|
+
const fgSelected = "\x1b[38;5;252m"; // Crisp light gray for selected radios (#d0d0d0)
|
|
167
|
+
const fgStatusReady = "\x1b[38;5;250m"; // Light slate for ready status
|
|
168
|
+
const fgValue = "\x1b[38;5;252m"; // Crisp silver-gray for metrics and values
|
|
169
|
+
const fgNotice = "\x1b[38;5;215m"; // Soft muted amber for download/sync alerts
|
|
170
|
+
const fgMuted = "\x1b[38;5;245m"; // Mid slate gray (#8a8a8a) for labels
|
|
171
|
+
const fgDim = "\x1b[38;5;239m"; // Dimmed charcoal gray (#4e4e4e) for secondary text and bullets
|
|
172
|
+
|
|
173
|
+
const row = (content: string) =>
|
|
174
|
+
bgCard + fgBorder + "│" + reset + bgCard + pad(content, innerW) + fgBorder + "│" + reset;
|
|
175
|
+
|
|
176
|
+
const status = this.index.getStatus();
|
|
177
|
+
const currentProfile = this.index.getProfile();
|
|
178
|
+
|
|
179
|
+
// Determine semantic color for model status
|
|
180
|
+
let modelColor = fgMuted;
|
|
181
|
+
if (status.modelStatus.includes("Active in RAM")) {
|
|
182
|
+
modelColor = fgActive;
|
|
183
|
+
} else if (status.modelStatus.includes("Active (BM25")) {
|
|
184
|
+
modelColor = fgStatusReady;
|
|
185
|
+
} else if (status.modelStatus.includes("Cached on disk")) {
|
|
186
|
+
modelColor = fgValue;
|
|
187
|
+
} else if (status.modelStatus.includes("Not downloaded")) {
|
|
188
|
+
modelColor = fgNotice;
|
|
189
|
+
} else if (status.modelStatus === "Disabled") {
|
|
190
|
+
modelColor = fgDim;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const cardLines: string[] = [];
|
|
194
|
+
|
|
195
|
+
// Header
|
|
196
|
+
cardLines.push(bgCard + fgBorder + `╭${"─".repeat(innerW)}╮` + reset);
|
|
197
|
+
cardLines.push(row(` ${fgTitle}Codebase Retrieval Engine${reset}${bgCard} ${fgDim}(Hybrid AST & Vector)`));
|
|
198
|
+
cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
|
|
199
|
+
|
|
200
|
+
// Status section
|
|
201
|
+
cardLines.push(row(` ${fgSubHeader}Status:`));
|
|
202
|
+
cardLines.push(
|
|
203
|
+
row(
|
|
204
|
+
` ${fgMuted}Engine : ${fgActive}${status.engineState}${fgMuted} (${fgValue}${status.pipelineDesc}${fgMuted})`
|
|
205
|
+
)
|
|
206
|
+
);
|
|
207
|
+
cardLines.push(
|
|
208
|
+
row(
|
|
209
|
+
` ${fgMuted}Default : ${fgTitle}${currentProfile.toUpperCase()}${fgMuted} ${fgDim}(~/.pi/agent/search_settings.json)`
|
|
210
|
+
)
|
|
211
|
+
);
|
|
212
|
+
cardLines.push(
|
|
213
|
+
row(
|
|
214
|
+
` ${fgMuted}Active : ${fgValue}${status.effectiveProfile.toUpperCase()}${fgMuted} (${fgDim}${status.hardwareInfo}${fgMuted})`
|
|
215
|
+
)
|
|
216
|
+
);
|
|
217
|
+
cardLines.push(
|
|
218
|
+
row(
|
|
219
|
+
` ${fgMuted}Index : ${fgValue}${status.chunkCount}${fgMuted} chunks in ${fgValue}${status.fileCount}${fgMuted} files | ${status.vectorCount > 0 ? fgValue : fgDim}${status.vectorCount} vectors`
|
|
220
|
+
)
|
|
221
|
+
);
|
|
222
|
+
cardLines.push(
|
|
223
|
+
row(
|
|
224
|
+
` ${fgMuted}Model : ${modelColor}${status.modelStatus}`
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
cardLines.push(
|
|
228
|
+
row(
|
|
229
|
+
` ${fgMuted}Memory : ${fgMuted}RSS ${fgValue}${status.rssMemoryMB} MB`
|
|
230
|
+
)
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
|
|
234
|
+
cardLines.push(row(` ${fgSubHeader}Engine Profiles:`));
|
|
235
|
+
|
|
236
|
+
// Render profile items
|
|
237
|
+
for (let i = 0; i < this.items.length; i++) {
|
|
238
|
+
const item = this.items[i];
|
|
239
|
+
if (item.category === "profile") {
|
|
240
|
+
const isSelected = i === this.selectedIndex;
|
|
241
|
+
const isCurrentProfile = item.profile === currentProfile;
|
|
242
|
+
|
|
243
|
+
const cursor = isSelected ? `${fgTitle} > ` : " ";
|
|
244
|
+
const radio = isCurrentProfile ? `${fgSelected}[x]` : `${fgDim}[ ]`;
|
|
245
|
+
|
|
246
|
+
const labelText = isSelected
|
|
247
|
+
? `${fgActive}${item.label}`
|
|
248
|
+
: isCurrentProfile
|
|
249
|
+
? `${fgSelected}${item.label}`
|
|
250
|
+
: `${fgMuted}${item.label}`;
|
|
251
|
+
|
|
252
|
+
let descExtra = "";
|
|
253
|
+
if (item.profile === "hybrid" || item.profile === "full") {
|
|
254
|
+
if (!status.isModelCached) {
|
|
255
|
+
descExtra = ` ${fgNotice}(Not downloaded, ~135 MB)`;
|
|
256
|
+
} else {
|
|
257
|
+
descExtra = ` ${fgStatusReady}(ready)`;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const descText = `${fgDim}- ${item.desc}${descExtra}`;
|
|
262
|
+
const lineStr = `${cursor}${radio} ${labelText} ${descText}`;
|
|
263
|
+
|
|
264
|
+
cardLines.push(row(lineStr));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
|
|
269
|
+
cardLines.push(row(` ${fgSubHeader}Workspace Actions:`));
|
|
270
|
+
|
|
271
|
+
// Render action items
|
|
272
|
+
for (let i = 0; i < this.items.length; i++) {
|
|
273
|
+
const item = this.items[i];
|
|
274
|
+
if (item.category === "action") {
|
|
275
|
+
const isSelected = i === this.selectedIndex;
|
|
276
|
+
const cursor = isSelected ? `${fgTitle} > ` : " ";
|
|
277
|
+
const bullet = `${fgDim}[-]`;
|
|
278
|
+
|
|
279
|
+
const labelText = isSelected
|
|
280
|
+
? `${fgActive}${item.label}`
|
|
281
|
+
: `${fgMuted}${item.label}`;
|
|
282
|
+
|
|
283
|
+
const descText = `${fgDim}- ${item.desc}`;
|
|
284
|
+
const lineStr = `${cursor}${bullet} ${labelText} ${descText}`;
|
|
285
|
+
|
|
286
|
+
cardLines.push(row(lineStr));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
|
|
291
|
+
cardLines.push(
|
|
292
|
+
row(
|
|
293
|
+
` ${fgDim}Up/Down: Navigate | Enter: Select/Toggle | Esc: Close`
|
|
294
|
+
)
|
|
295
|
+
);
|
|
296
|
+
cardLines.push(bgCard + fgBorder + `╰${"─".repeat(innerW)}╯` + reset);
|
|
297
|
+
|
|
298
|
+
// Terminal height resolution for full-viewport coverage
|
|
299
|
+
const termHeight =
|
|
300
|
+
this.tui?.terminal?.rows ||
|
|
301
|
+
(process.stdout && process.stdout.rows ? process.stdout.rows : 24);
|
|
302
|
+
|
|
303
|
+
// Layout calculations for full-screen backdrop framing
|
|
304
|
+
const leftPad = Math.max(0, Math.floor((width - cardWidth) / 2));
|
|
305
|
+
const rightPad = Math.max(0, width - cardWidth - leftPad);
|
|
306
|
+
|
|
307
|
+
// Dark monochrome backdrop: deep black background with dark gray stippling
|
|
308
|
+
const scrim = (len: number) =>
|
|
309
|
+
len <= 0 ? "" : "\x1b[48;5;232m\x1b[38;5;234m" + "░".repeat(len) + reset;
|
|
310
|
+
|
|
311
|
+
// Deep dark right drop shadow
|
|
312
|
+
const shadowRight = (len: number) => {
|
|
313
|
+
if (len <= 0) return "";
|
|
314
|
+
return "\x1b[48;5;232m\x1b[38;5;233m▌" + reset + scrim(len - 1);
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
// Deep dark bottom drop shadow
|
|
318
|
+
const shadowBottom = (left: number, card: number, right: number) => {
|
|
319
|
+
return (
|
|
320
|
+
scrim(left) +
|
|
321
|
+
"\x1b[48;5;232m\x1b[38;5;233m" +
|
|
322
|
+
"▀".repeat(card) +
|
|
323
|
+
reset +
|
|
324
|
+
scrim(right)
|
|
325
|
+
);
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const totalCardRows = cardLines.length + 1; // Card lines + bottom shadow row
|
|
329
|
+
const topPad = Math.max(0, Math.floor((termHeight - totalCardRows) / 2));
|
|
330
|
+
const bottomPad = Math.max(0, termHeight - totalCardRows - topPad);
|
|
331
|
+
|
|
332
|
+
const fullLines: string[] = [];
|
|
333
|
+
|
|
334
|
+
// Top backdrop scrim rows to fill viewport from top down to modal
|
|
335
|
+
for (let i = 0; i < topPad; i++) {
|
|
336
|
+
fullLines.push(scrim(width));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Centered card rows with left/right scrim and right shadow
|
|
340
|
+
for (let i = 0; i < cardLines.length; i++) {
|
|
341
|
+
const line = scrim(leftPad) + cardLines[i] + shadowRight(rightPad);
|
|
342
|
+
fullLines.push(line);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Bottom shadow row
|
|
346
|
+
fullLines.push(shadowBottom(leftPad, cardWidth, rightPad));
|
|
347
|
+
|
|
348
|
+
// Bottom backdrop scrim rows to fill viewport down to bottom edge
|
|
349
|
+
for (let i = 0; i < bottomPad; i++) {
|
|
350
|
+
fullLines.push(scrim(width));
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return fullLines;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
invalidate(): void {}
|
|
357
|
+
dispose(): void {}
|
|
358
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
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 (ext === ".py") {
|
|
84
|
+
// Python indentation based boundary detection
|
|
85
|
+
const defLine = lines[startIdx];
|
|
86
|
+
const matchIndent = defLine.match(/^(\s*)/);
|
|
87
|
+
const baseIndent = matchIndent ? matchIndent[1].length : 0;
|
|
88
|
+
|
|
89
|
+
// Handle multi-line Python signatures (e.g. def foo(\n arg: int\n) -> bool:)
|
|
90
|
+
let headerEndIdx = startIdx;
|
|
91
|
+
let parenCount = 0;
|
|
92
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
93
|
+
const line = lines[i];
|
|
94
|
+
for (const ch of line) {
|
|
95
|
+
if (ch === "(") parenCount++;
|
|
96
|
+
else if (ch === ")") parenCount--;
|
|
97
|
+
}
|
|
98
|
+
if (parenCount <= 0 && line.trim().endsWith(":")) {
|
|
99
|
+
headerEndIdx = i;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let inDocstring = false;
|
|
105
|
+
let docstringQuote = "";
|
|
106
|
+
|
|
107
|
+
for (let i = headerEndIdx + 1; i < lines.length; i++) {
|
|
108
|
+
const currentLine = lines[i];
|
|
109
|
+
const trimmed = currentLine.trim();
|
|
110
|
+
|
|
111
|
+
if (!trimmed) {
|
|
112
|
+
endIdx = i;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Check docstrings
|
|
117
|
+
if (!inDocstring) {
|
|
118
|
+
if (trimmed.startsWith('"""') || trimmed.startsWith("'''")) {
|
|
119
|
+
docstringQuote = trimmed.slice(0, 3);
|
|
120
|
+
if (trimmed.length === 3 || !trimmed.slice(3).includes(docstringQuote)) {
|
|
121
|
+
inDocstring = true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} else {
|
|
125
|
+
if (trimmed.includes(docstringQuote)) {
|
|
126
|
+
inDocstring = false;
|
|
127
|
+
}
|
|
128
|
+
endIdx = i;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (inDocstring) {
|
|
133
|
+
endIdx = i;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (trimmed.startsWith("#")) {
|
|
138
|
+
endIdx = i;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const currIndent = currentLine.match(/^(\s*)/)?.[1].length || 0;
|
|
143
|
+
if (currIndent <= baseIndent) {
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
endIdx = i;
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
// Brace-based languages (TS, JS, Go, Rust, C++, Java, C#)
|
|
150
|
+
let braceCount = 0;
|
|
151
|
+
let foundOpenBrace = false;
|
|
152
|
+
|
|
153
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
154
|
+
const currentLine = lines[i];
|
|
155
|
+
|
|
156
|
+
for (let charIdx = 0; charIdx < currentLine.length; charIdx++) {
|
|
157
|
+
const char = currentLine[charIdx];
|
|
158
|
+
if (char === "{") {
|
|
159
|
+
braceCount++;
|
|
160
|
+
foundOpenBrace = true;
|
|
161
|
+
} else if (char === "}") {
|
|
162
|
+
braceCount--;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
endIdx = i;
|
|
167
|
+
if (foundOpenBrace && braceCount <= 0) {
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Apply surrounding context if requested
|
|
174
|
+
const extra = options.surroundingLines || 0;
|
|
175
|
+
const finalStart = Math.max(0, actualStartIdx - extra);
|
|
176
|
+
const finalEnd = Math.min(lines.length - 1, endIdx + extra);
|
|
177
|
+
|
|
178
|
+
// Format with line numbers (e.g. " 1420 | def handle(...):")
|
|
179
|
+
const formattedLines = [];
|
|
180
|
+
for (let i = finalStart; i <= finalEnd; i++) {
|
|
181
|
+
const lineNumStr = String(i + 1).padStart(5, " ");
|
|
182
|
+
formattedLines.push(`${lineNumStr} | ${lines[i]}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
matches.push({
|
|
186
|
+
name: def.name,
|
|
187
|
+
kind: def.kind,
|
|
188
|
+
signature: def.signature,
|
|
189
|
+
startLine: finalStart + 1,
|
|
190
|
+
endLine: finalEnd + 1,
|
|
191
|
+
content: formattedLines.join("\n"),
|
|
192
|
+
filePath: resolvedPath,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
found: matches.length > 0,
|
|
198
|
+
symbols: matches,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { kernelDebug } from "./kernel_debug";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Write a file atomically: write to a sibling temp file, then rename over the
|
|
6
|
+
* destination. A plain writeFileSync can leave a truncated/corrupt JSON store
|
|
7
|
+
* behind if the process dies mid-write; with tmp+rename the destination either
|
|
8
|
+
* holds the old complete file or the new complete file, never a partial one.
|
|
9
|
+
*/
|
|
10
|
+
export function writeFileSyncAtomic(
|
|
11
|
+
filePath: string,
|
|
12
|
+
data: string | Buffer,
|
|
13
|
+
): void {
|
|
14
|
+
const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
15
|
+
try {
|
|
16
|
+
fs.writeFileSync(tmp, data);
|
|
17
|
+
fs.renameSync(tmp, filePath);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
try {
|
|
20
|
+
fs.unlinkSync(tmp);
|
|
21
|
+
} catch (cleanupErr) {
|
|
22
|
+
kernelDebug(cleanupErr);
|
|
23
|
+
}
|
|
24
|
+
throw err;
|
|
25
|
+
}
|
|
26
|
+
}
|