@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.
Files changed (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,813 @@
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 * as path from "node:path";
5
+ import * as fs from "node:fs";
6
+ import {
7
+ LspManager,
8
+ formatDiagnostics,
9
+ formatDefinitions,
10
+ formatReferences,
11
+ formatHover,
12
+ formatDocumentSymbols,
13
+ uriToPath,
14
+ windowAround,
15
+ } from "../lsp";
16
+ import {
17
+ extractDocumentSymbols,
18
+ findSymbolReferences,
19
+ extractLocalSymbolHover,
20
+ searchAstSymbols,
21
+ } from "../retrieval/ast_search";
22
+ import { checkSyntax } from "../editing/syntax-verify";
23
+ import { kernelDebug } from "../safety/kernel_debug";
24
+ import type { SessionDeps } from "./context";
25
+
26
+ /** Extracted from index.ts — registers the `lsp` tool. */
27
+ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
28
+ // 8. Tool: `lsp` (Language Server Protocol Symbol Resolution, Definitions, References, & Diagnostics)
29
+ pi.registerTool({
30
+ name: "lsp",
31
+ label: "Language Server Protocol (LSP)",
32
+ description:
33
+ "Query language server for definitions, references (supports exclude_tests and exclude_declaration), hover docstrings, document symbols, or diagnostics with instant Tree-sitter fallback.",
34
+ promptSnippet:
35
+ "Query LSP for definitions, references (with test filtering), hover type signatures, and workspace diagnostics",
36
+ renderShell: "default",
37
+ parameters: Type.Object({
38
+ action: Type.String({
39
+ enum: [
40
+ "definition",
41
+ "references",
42
+ "hover",
43
+ "document_symbols",
44
+ "diagnostics",
45
+ ],
46
+ description:
47
+ "LSP operation: 'definition' | 'references' | 'hover' | 'document_symbols' | 'diagnostics'",
48
+ }),
49
+ path: Type.String({ description: "File path (absolute or relative)" }),
50
+ line: Type.Optional(
51
+ Type.Number({
52
+ description:
53
+ "1-based line number (required for definition, references, hover)",
54
+ }),
55
+ ),
56
+ character: Type.Optional(
57
+ Type.Number({
58
+ description: "1-based character/column number (default: 1)",
59
+ }),
60
+ ),
61
+ symbol: Type.Optional(
62
+ Type.String({
63
+ description: "Optional symbol name for definition, references, or hover; avoids manual line/character coordinates",
64
+ }),
65
+ ),
66
+ exclude_tests: Type.Optional(
67
+ Type.Boolean({
68
+ description: "Exclude references located in test files or test modules (default: false)",
69
+ }),
70
+ ),
71
+ exclude_declaration: Type.Optional(
72
+ Type.Boolean({
73
+ description: "Exclude the symbol's own declaration site from references (default: false)",
74
+ }),
75
+ ),
76
+ }),
77
+ async execute(
78
+ _toolCallId: string,
79
+ params: any,
80
+ _signal: any,
81
+ onUpdate: any,
82
+ ctx: any,
83
+ ): Promise<any> {
84
+ if (
85
+ !params ||
86
+ typeof params !== "object" ||
87
+ typeof params.path !== "string" ||
88
+ !params.path.trim() ||
89
+ !["definition", "references", "hover", "document_symbols", "diagnostics"].includes(params.action)
90
+ ) {
91
+ return {
92
+ content: [{ type: "text", text: "[LSP ERROR] Invalid action or file path." }],
93
+ isError: true,
94
+ };
95
+ }
96
+ const action = params.action;
97
+ const targetPath = params.path;
98
+ if (
99
+ typeof targetPath !== "string" ||
100
+ !targetPath.trim() ||
101
+ !["definition", "references", "hover", "document_symbols", "diagnostics"].includes(action)
102
+ ) {
103
+ return {
104
+ content: [{ type: "text", text: "[LSP ERROR] Invalid action or file path." }],
105
+ isError: true,
106
+ };
107
+ }
108
+ const absPath = path.isAbsolute(targetPath)
109
+ ? targetPath
110
+ : path.resolve(ctx.cwd, targetPath);
111
+
112
+ if (!fs.existsSync(absPath)) {
113
+ return {
114
+ content: [
115
+ { type: "text", text: `[LSP ERROR] File not found: ${targetPath}` },
116
+ ],
117
+ isError: true,
118
+ };
119
+ }
120
+
121
+ // Read the source only for local cursor/symbol resolution. An LSP query
122
+ // returns metadata, not model-visible source coverage, so it must not
123
+ // authorize a later mutation.
124
+ let observedContent: Buffer;
125
+ try {
126
+ observedContent = fs.readFileSync(absPath);
127
+ } catch (error: any) {
128
+ return {
129
+ content: [
130
+ { type: "text", text: `[LSP ERROR] Unable to read ${targetPath}: ${error.message}` },
131
+ ],
132
+ isError: true,
133
+ };
134
+ }
135
+ // Intentionally no epistemic read record: the source buffer is an
136
+ // implementation input, not content returned by the LSP operation.
137
+
138
+ const requestedSymbol = typeof params.symbol === "string" ? params.symbol.trim() : "";
139
+ let line0 = Math.max(0, (params.line || 1) - 1);
140
+ let col0 = Math.max(0, (params.character || 1) - 1);
141
+
142
+ // If a symbol is requested or column coordinate is defaulted to 1 (col0 = 0),
143
+ // check if line0 points to leading whitespace or reserved keywords (e.g. `pub fn`, `export async`).
144
+ // Advance col0 to the actual declared identifier so LSP and AST queries resolve cleanly.
145
+ const fileLines = observedContent.toString("utf8").split("\n");
146
+ if (requestedSymbol && (params.line === undefined || params.character === undefined)) {
147
+ const lineIdx = fileLines.findIndex((l) => {
148
+ const escaped = requestedSymbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
149
+ return new RegExp(`\\b${escaped}\\b`).test(l);
150
+ });
151
+ if (lineIdx !== -1) {
152
+ line0 = lineIdx;
153
+ const charIdx = fileLines[lineIdx].indexOf(requestedSymbol);
154
+ if (charIdx !== -1) col0 = charIdx;
155
+ }
156
+ } else if (params.character === undefined || params.character === 1) {
157
+ const lineText = fileLines[line0] || "";
158
+ const declMatch = lineText.match(/(?:pub(?:\([^)]*\))?\s+|async\s+|fn\s+|function\s+|def\s+|class\s+|interface\s+|type\s+|struct\s+|enum\s+|export\s+|let\s+|const\s+|var\s+)+([a-zA-Z_][a-zA-Z0-9_]*)/);
159
+ if (declMatch && declMatch.index !== undefined && declMatch[1]) {
160
+ const symName = declMatch[1];
161
+ const symOffset = lineText.indexOf(symName, declMatch.index);
162
+ if (symOffset !== -1) {
163
+ col0 = symOffset;
164
+ }
165
+ }
166
+ }
167
+
168
+ // Helper: extract identifier / qualified symbol under cursor (supports `foo.bar`, `crate::state::KeyUsage`)
169
+ const getSymbolUnderCursor = (): {
170
+ full: string;
171
+ leaf: string;
172
+ isModule: boolean;
173
+ } => {
174
+ try {
175
+ const fileContent = observedContent.toString("utf8");
176
+ const lines = fileContent.split("\n");
177
+ const lineText = lines[line0] || "";
178
+ const qualifiedWords = Array.from(
179
+ lineText.matchAll(
180
+ /[a-zA-Z_][a-zA-Z0-9_]*(?:(?:::|\.)[a-zA-Z_][a-zA-Z0-9_]*)*/g,
181
+ ),
182
+ );
183
+
184
+ for (const w of qualifiedWords) {
185
+ if (
186
+ w.index !== undefined &&
187
+ col0 >= w.index &&
188
+ col0 <= w.index + w[0].length
189
+ ) {
190
+ const fullExpr = w[0];
191
+ const separator = fullExpr.includes("::") ? "::" : ".";
192
+ const parts = fullExpr.split(separator);
193
+
194
+ let currentOffset = w.index;
195
+ for (let idx = 0; idx < parts.length; idx++) {
196
+ const part = parts[idx];
197
+ const partEnd = currentOffset + part.length;
198
+ if (col0 >= currentOffset && col0 <= partEnd) {
199
+ const isModule =
200
+ idx < parts.length - 1 ||
201
+ part === "crate" ||
202
+ part === "super" ||
203
+ part === "self";
204
+ return { full: fullExpr, leaf: part, isModule };
205
+ }
206
+ currentOffset = partEnd + separator.length;
207
+ }
208
+ return {
209
+ full: fullExpr,
210
+ leaf: parts[parts.length - 1],
211
+ isModule: false,
212
+ };
213
+ }
214
+ }
215
+ } catch (e) {
216
+ kernelDebug(e);
217
+ }
218
+ return { full: "", leaf: "", isModule: false };
219
+ };
220
+
221
+ onUpdate?.({
222
+ content: [{ type: "text", text: `Querying LSP (${action})...` }],
223
+ });
224
+
225
+ const lspMgr = LspManager.getInstance();
226
+ const client = await lspMgr.getClientForFile(absPath, ctx.cwd);
227
+ // LSP results are metadata, not source visibility. Keep the native buffer
228
+ // local for cursor resolution and never treat it as read evidence.
229
+
230
+ // If no client available, fall back cleanly to AST intelligence
231
+ if (!client) {
232
+ if (action === "document_symbols") {
233
+ const docSyms = extractDocumentSymbols(absPath);
234
+ if (docSyms.length > 0) {
235
+ const formatted = docSyms
236
+ .map((s) => `${s.line}: [${s.kind}] ${s.name} - ${s.signature}`)
237
+ .join("\n");
238
+ return {
239
+ content: [
240
+ {
241
+ type: "text",
242
+ text: formatted,
243
+ },
244
+ ],
245
+ };
246
+ }
247
+ return {
248
+ content: [
249
+ {
250
+ type: "text",
251
+ text: `No symbols found in ${path.basename(absPath)}.`,
252
+ },
253
+ ],
254
+ };
255
+ }
256
+
257
+ if (action === "references") {
258
+ const sym = getSymbolUnderCursor();
259
+ const targetSym = requestedSymbol || sym.leaf || sym.full;
260
+ if (targetSym) {
261
+ const refs = findSymbolReferences(ctx.cwd, targetSym);
262
+ if (refs.length > 0) {
263
+ const formatted = refs
264
+ .map((r) => `${r.filePath}:${r.line}:${r.column}`)
265
+ .join("\n");
266
+ return {
267
+ content: [
268
+ {
269
+ type: "text",
270
+ text: formatted,
271
+ },
272
+ ],
273
+ };
274
+ }
275
+ }
276
+ return {
277
+ content: [{ type: "text", text: "No references found in workspace." }],
278
+ };
279
+ }
280
+
281
+ if (action === "hover") {
282
+ const sym = getSymbolUnderCursor();
283
+ const targetSym = sym.leaf || sym.full;
284
+ if (targetSym) {
285
+ const localHover = extractLocalSymbolHover(
286
+ absPath,
287
+ line0,
288
+ col0,
289
+ targetSym,
290
+ );
291
+ if (localHover) {
292
+ return { content: [{ type: "text", text: localHover }] };
293
+ }
294
+ const astHits = searchAstSymbols(ctx.cwd, {
295
+ name: targetSym,
296
+ exactMatch: true,
297
+ currentFilePath: absPath,
298
+ });
299
+ if (astHits.length > 0) {
300
+ const hit = astHits[0];
301
+ return {
302
+ content: [
303
+ {
304
+ type: "text",
305
+ text: `[Tree-sitter AST Hover - ${hit.kind} ${hit.name}]\n${hit.signature}\nDeclared in ${hit.filePath}:${hit.line}`,
306
+ },
307
+ ],
308
+ };
309
+ }
310
+ }
311
+ return {
312
+ content: [
313
+ {
314
+ type: "text",
315
+ text: "No hover information available at this position.",
316
+ },
317
+ ],
318
+ };
319
+ }
320
+
321
+ if (action === "definition") {
322
+ const sym = getSymbolUnderCursor();
323
+ const targetSym = requestedSymbol || sym.leaf || sym.full;
324
+ if (targetSym) {
325
+ // 1. Check if targetSym is a module/file in the workspace (e.g. `state` -> `src/state.rs` or `state/mod.rs`)
326
+ const candidates = [
327
+ path.join(ctx.cwd, "src", `${targetSym}.rs`),
328
+ path.join(ctx.cwd, "src", targetSym, "mod.rs"),
329
+ path.join(ctx.cwd, `${targetSym}.rs`),
330
+ path.join(ctx.cwd, "src", `${targetSym}.ts`),
331
+ path.join(ctx.cwd, `${targetSym}.ts`),
332
+ path.join(ctx.cwd, `${targetSym}.py`),
333
+ path.join(path.dirname(absPath), `${targetSym}.rs`),
334
+ path.join(path.dirname(absPath), targetSym, "mod.rs"),
335
+ ];
336
+ for (const cand of candidates) {
337
+ if (fs.existsSync(cand) && cand !== absPath) {
338
+ const rel = path.relative(ctx.cwd, cand).replace(/\\/g, "/");
339
+ return {
340
+ content: [
341
+ {
342
+ type: "text",
343
+ text: `[Tree-sitter AST Definition - module '${targetSym}']\n → [module] ${targetSym} (${rel}:1)\n Module file in workspace`,
344
+ },
345
+ ],
346
+ };
347
+ }
348
+ }
349
+
350
+ // 2. Search AST symbol declarations across workspace
351
+ let astHits = searchAstSymbols(ctx.cwd, {
352
+ name: targetSym,
353
+ exactMatch: true,
354
+ currentFilePath: absPath,
355
+ });
356
+ if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
357
+ astHits = searchAstSymbols(ctx.cwd, {
358
+ name: sym.full,
359
+ exactMatch: true,
360
+ currentFilePath: absPath,
361
+ });
362
+ }
363
+ if (astHits.length === 0) {
364
+ astHits = searchAstSymbols(ctx.cwd, {
365
+ name: targetSym,
366
+ exactMatch: false,
367
+ currentFilePath: absPath,
368
+ });
369
+ }
370
+ if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
371
+ astHits = searchAstSymbols(ctx.cwd, {
372
+ name: sym.full,
373
+ exactMatch: false,
374
+ currentFilePath: absPath,
375
+ });
376
+ }
377
+ if (astHits.length > 0) {
378
+ const formatted = astHits
379
+ .slice(0, 5)
380
+ .map((h) => {
381
+ const aliasInfo = h.aliasedFrom
382
+ ? `\n (aliased from '${h.aliasedFrom.originalName}' in ${h.aliasedFrom.module || "workspace"})`
383
+ : "";
384
+ return ` → [${h.kind}] ${h.name} (${h.filePath}:${h.line})\n Signature: ${h.signature}${aliasInfo}`;
385
+ })
386
+ .join("\n");
387
+ return {
388
+ content: [
389
+ {
390
+ type: "text",
391
+ text: `[Tree-sitter AST Definition - ${astHits.length} match(es) for '${targetSym}']\n${formatted}`,
392
+ },
393
+ ],
394
+ };
395
+ }
396
+ }
397
+ return {
398
+ content: [{ type: "text", text: "Definition not found." }],
399
+ };
400
+ }
401
+
402
+ if (action === "diagnostics") {
403
+ const syn = checkSyntax(absPath);
404
+ if (!syn.valid) {
405
+ const status = syn.status || "failed";
406
+ return {
407
+ content: [
408
+ {
409
+ type: "text",
410
+ text: `- [1:1] [${status.toUpperCase()}] Syntax validation: ${syn.error}`,
411
+ },
412
+ ],
413
+ };
414
+ }
415
+ return {
416
+ content: [],
417
+ };
418
+ }
419
+
420
+ return {
421
+ content: [
422
+ {
423
+ type: "text",
424
+ text: `[LSP Notice] No installed LSP server found for ${path.basename(absPath)}. Use 'ast_search' or run '/lsp install' to configure an LSP server.`,
425
+ },
426
+ ],
427
+ };
428
+ }
429
+
430
+ try {
431
+ if (action === "definition") {
432
+ const defs = await client.gotoDefinition(absPath, line0, col0);
433
+ if (defs.length > 0) {
434
+ return {
435
+ content: [{ type: "text", text: formatDefinitions(defs, ctx.cwd) }],
436
+ };
437
+ }
438
+ // Only fallback to Tree-sitter AST for programming languages when LSP is unavailable or errored
439
+ const ext = path.extname(absPath).toLowerCase();
440
+ const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
441
+ if (nonCodeExts.includes(ext)) {
442
+ return {
443
+ content: [{ type: "text", text: formatDefinitions(defs, ctx.cwd) }],
444
+ };
445
+ }
446
+
447
+ // Tree-sitter fallback with exact symbol ranking
448
+ const sym = getSymbolUnderCursor();
449
+ const targetSym = requestedSymbol || sym.leaf || sym.full;
450
+ if (targetSym) {
451
+ let astHits = searchAstSymbols(ctx.cwd, {
452
+ name: targetSym,
453
+ exactMatch: true,
454
+ });
455
+ if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
456
+ astHits = searchAstSymbols(ctx.cwd, {
457
+ name: sym.full,
458
+ exactMatch: true,
459
+ });
460
+ }
461
+ if (astHits.length === 0) {
462
+ astHits = searchAstSymbols(ctx.cwd, {
463
+ name: targetSym,
464
+ exactMatch: false,
465
+ });
466
+ }
467
+ if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
468
+ astHits = searchAstSymbols(ctx.cwd, {
469
+ name: sym.full,
470
+ exactMatch: false,
471
+ });
472
+ }
473
+ if (astHits.length > 0) {
474
+ const formatted = astHits
475
+ .slice(0, 5)
476
+ .map((h) => {
477
+ const aliasInfo = h.aliasedFrom
478
+ ? `\n (aliased from '${h.aliasedFrom.originalName}' in ${h.aliasedFrom.module || "workspace"})`
479
+ : "";
480
+ return ` → [${h.kind}] ${h.name} (${h.filePath}:${h.line})\n Signature: ${h.signature}${aliasInfo}`;
481
+ })
482
+ .join("\n");
483
+ return {
484
+ content: [
485
+ {
486
+ type: "text",
487
+ text: `[Tree-sitter AST Fallback - ${astHits.length} declaration match(es) for '${targetSym}']\n${formatted}`,
488
+ },
489
+ ],
490
+ };
491
+ }
492
+ }
493
+
494
+ return {
495
+ content: [{ type: "text", text: formatDefinitions(defs, ctx.cwd) }],
496
+ };
497
+ }
498
+
499
+ if (action === "references") {
500
+ const filterRefs = (locations: any[]) => {
501
+ let res = locations;
502
+ if (params.exclude_declaration) {
503
+ res = res.filter((loc) => {
504
+ const locPath = uriToPath(loc.uri);
505
+ const sameFile = locPath === absPath || path.resolve(locPath) === path.resolve(absPath);
506
+ const sameLine = loc.range?.start?.line === line0;
507
+ return !(sameFile && sameLine);
508
+ });
509
+ }
510
+ if (params.exclude_tests) {
511
+ res = res.filter((loc) => {
512
+ const locPath = uriToPath(loc.uri).replace(/\\/g, "/").toLowerCase();
513
+ const fileName = path.basename(locPath);
514
+ const isTestPath =
515
+ locPath.includes("/test/") ||
516
+ locPath.includes("/tests/") ||
517
+ locPath.startsWith("tests/") ||
518
+ locPath.startsWith("test/") ||
519
+ locPath.includes("__tests__") ||
520
+ fileName.startsWith("test_") ||
521
+ fileName.endsWith("_test.rs") ||
522
+ fileName.endsWith("_test.go") ||
523
+ fileName.endsWith("_test.py") ||
524
+ fileName.endsWith(".test.ts") ||
525
+ fileName.endsWith(".spec.ts") ||
526
+ fileName.endsWith(".test.js");
527
+ return !isTestPath;
528
+ });
529
+ }
530
+ return res;
531
+ };
532
+
533
+ let refs = await client.findReferences(absPath, line0, col0);
534
+ if (refs.length > 0) {
535
+ refs = filterRefs(refs);
536
+ return {
537
+ content: [{ type: "text", text: formatReferences(refs, ctx.cwd) }],
538
+ };
539
+ }
540
+ const ext = path.extname(absPath).toLowerCase();
541
+ const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
542
+ if (nonCodeExts.includes(ext)) {
543
+ return {
544
+ content: [{ type: "text", text: formatReferences(refs, ctx.cwd) }],
545
+ };
546
+ }
547
+
548
+ // Workspace-wide symbol reference search fallback
549
+ const sym = getSymbolUnderCursor();
550
+ const targetSym = requestedSymbol || sym.leaf || sym.full;
551
+ if (targetSym) {
552
+ let astRefs = findSymbolReferences(ctx.cwd, targetSym);
553
+ if (params.exclude_declaration) {
554
+ astRefs = astRefs.filter((r) => {
555
+ const sameFile = path.resolve(ctx.cwd, r.filePath) === path.resolve(absPath);
556
+ return !(sameFile && r.line === (line0 + 1));
557
+ });
558
+ }
559
+ if (params.exclude_tests) {
560
+ astRefs = astRefs.filter((r) => {
561
+ const norm = r.filePath.replace(/\\/g, "/").toLowerCase();
562
+ const fileName = path.basename(norm);
563
+ return !(
564
+ norm.includes("/test/") ||
565
+ norm.includes("/tests/") ||
566
+ norm.startsWith("tests/") ||
567
+ norm.startsWith("test/") ||
568
+ norm.includes("__tests__") ||
569
+ fileName.startsWith("test_") ||
570
+ fileName.endsWith("_test.rs") ||
571
+ fileName.endsWith("_test.go") ||
572
+ fileName.endsWith("_test.py") ||
573
+ fileName.endsWith(".test.ts") ||
574
+ fileName.endsWith(".spec.ts") ||
575
+ fileName.endsWith(".test.js")
576
+ );
577
+ });
578
+ }
579
+ if (astRefs.length > 0) {
580
+ const formatted = astRefs
581
+ .map((r) => {
582
+ const col0 = Math.max(0, r.column - 1);
583
+ const endCol0 = col0 + targetSym.length;
584
+ const snippet = windowAround(r.lineText, col0, endCol0, 50);
585
+ return `${r.filePath}:${r.line}:${r.column}: ${snippet}`;
586
+ })
587
+ .join("\n");
588
+ return {
589
+ content: [
590
+ {
591
+ type: "text",
592
+ text: formatted,
593
+ },
594
+ ],
595
+ };
596
+ }
597
+ }
598
+ return {
599
+ content: [{ type: "text", text: formatReferences(refs, ctx.cwd) }],
600
+ };
601
+ }
602
+
603
+ if (action === "hover") {
604
+ if (requestedSymbol) {
605
+ const candidates = searchAstSymbols(ctx.cwd, {
606
+ name: requestedSymbol,
607
+ exactMatch: true,
608
+ currentFilePath: absPath,
609
+ });
610
+ if (candidates.length === 1) {
611
+ const candidate = candidates[0];
612
+ const candidatePath = path.isAbsolute(candidate.filePath)
613
+ ? candidate.filePath
614
+ : path.resolve(ctx.cwd, candidate.filePath);
615
+ const candidateLine = Math.max(0, candidate.line - 1);
616
+ const candidateContent = candidatePath === absPath
617
+ ? observedContent.toString("utf8")
618
+ : fs.readFileSync(candidatePath, "utf8");
619
+ const candidateLineText = candidateContent.split("\n")[candidateLine] || "";
620
+ const candidateColumn = Math.max(0, candidateLineText.indexOf(candidate.name));
621
+ const candidateClient = candidatePath === absPath
622
+ ? client
623
+ : await lspMgr.getClientForFile(candidatePath, ctx.cwd);
624
+ if (candidateClient) {
625
+ const candidateHover = await candidateClient.hover(candidatePath, candidateLine, candidateColumn);
626
+ const candidateHoverText = formatHover(candidateHover);
627
+ if (candidateHover && !candidateHoverText.startsWith("No hover information")) {
628
+ return { content: [{ type: "text", text: candidateHoverText }] };
629
+ }
630
+ }
631
+ return {
632
+ content: [{ type: "text", text: `[AST Hover] ${candidate.kind} ${candidate.name}\n${candidate.signature}\nDeclared in ${candidate.filePath}:${candidate.line}` }],
633
+ };
634
+ }
635
+ if (candidates.length > 1) {
636
+ return {
637
+ content: [{ type: "text", text: `Multiple declarations found for '${requestedSymbol}':\n${candidates.slice(0, 10).map((candidate) => `- ${candidate.filePath}:${candidate.line} [${candidate.kind}] ${candidate.signature}`).join("\n")}` }],
638
+ };
639
+ }
640
+ }
641
+ const h = await client.hover(absPath, line0, col0);
642
+ const hoverText = formatHover(h);
643
+ if (h && !hoverText.startsWith("No hover information")) {
644
+ return {
645
+ content: [{ type: "text", text: hoverText }],
646
+ };
647
+ }
648
+ const ext = path.extname(absPath).toLowerCase();
649
+ const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
650
+ if (nonCodeExts.includes(ext)) {
651
+ return {
652
+ content: [{ type: "text", text: hoverText }],
653
+ };
654
+ }
655
+
656
+ // Tree-sitter local variable / parameter / symbol hover fallback
657
+ const sym = getSymbolUnderCursor();
658
+ const targetSym = sym.leaf || sym.full;
659
+ if (targetSym) {
660
+ const localHover = extractLocalSymbolHover(
661
+ absPath,
662
+ line0,
663
+ col0,
664
+ targetSym,
665
+ );
666
+ if (localHover) {
667
+ return { content: [{ type: "text", text: localHover }] };
668
+ }
669
+ const astHits = searchAstSymbols(ctx.cwd, {
670
+ name: targetSym,
671
+ exactMatch: true,
672
+ });
673
+ if (astHits.length > 0) {
674
+ const hit = astHits[0];
675
+ return {
676
+ content: [
677
+ {
678
+ type: "text",
679
+ text: `[Tree-sitter AST Hover - ${hit.kind} ${hit.name}]\n${hit.signature}\nDeclared in ${hit.filePath}:${hit.line}`,
680
+ },
681
+ ],
682
+ };
683
+ }
684
+ }
685
+
686
+ return {
687
+ content: [{ type: "text", text: hoverText }],
688
+ };
689
+ }
690
+
691
+ if (action === "document_symbols") {
692
+ const syms = await client.documentSymbol(absPath);
693
+ if (syms.length > 0) {
694
+ return {
695
+ content: [{ type: "text", text: formatDocumentSymbols(syms) }],
696
+ };
697
+ }
698
+ const ext = path.extname(absPath).toLowerCase();
699
+ const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
700
+ if (nonCodeExts.includes(ext)) {
701
+ return {
702
+ content: [{ type: "text", text: formatDocumentSymbols(syms) }],
703
+ };
704
+ }
705
+ const docSyms = extractDocumentSymbols(absPath);
706
+ if (docSyms.length > 0) {
707
+ const formatted = docSyms
708
+ .map((s) => `• [${s.kind}] ${s.name} (line ${s.line}) - ${s.signature}`)
709
+ .join("\n");
710
+ return {
711
+ content: [
712
+ {
713
+ type: "text",
714
+ text: `[Tree-sitter AST Document Symbols - ${docSyms.length} symbol(s)]\n${formatted}`,
715
+ },
716
+ ],
717
+ };
718
+ }
719
+ return {
720
+ content: [
721
+ {
722
+ type: "text",
723
+ text: `[Tree-sitter AST] No symbols found in ${path.basename(absPath)}.`,
724
+ },
725
+ ],
726
+ };
727
+ }
728
+
729
+ if (action === "diagnostics") {
730
+ const diagnosticResult = await client.getDiagnosticsResult(absPath);
731
+ if (diagnosticResult.diagnostics.length > 0) {
732
+ return {
733
+ content: [
734
+ { type: "text", text: formatDiagnostics(diagnosticResult.diagnostics, absPath, ctx.cwd) },
735
+ ],
736
+ };
737
+ }
738
+
739
+ const syn = checkSyntax(absPath);
740
+ if (!syn.valid) {
741
+ const status = syn.status || "failed";
742
+ return {
743
+ content: [
744
+ {
745
+ type: "text",
746
+ text: `- [1:1] [${status.toUpperCase()}] Syntax validation: ${syn.error}`,
747
+ },
748
+ ],
749
+ };
750
+ }
751
+
752
+ if (diagnosticResult.status !== "clean") {
753
+ return {
754
+ content: [
755
+ {
756
+ type: "text",
757
+ text: `[LSP ${diagnosticResult.status.toUpperCase()}] No definitive diagnostics result for ${path.relative(ctx.cwd, absPath)} (syntax validation passed).`,
758
+ },
759
+ ],
760
+ };
761
+ }
762
+
763
+ const relPath = path.relative(ctx.cwd, absPath).replace(/\\/g, "/") || absPath;
764
+ return {
765
+ content: [
766
+ {
767
+ type: "text",
768
+ text: `${relPath} clean`,
769
+ },
770
+ ],
771
+ };
772
+ }
773
+
774
+ return {
775
+ content: [
776
+ { type: "text", text: `[LSP ERROR] Unsupported action: ${action}` },
777
+ ],
778
+ isError: true,
779
+ };
780
+ } catch (err: any) {
781
+ return {
782
+ content: [{ type: "text", text: `[LSP ERROR] ${err.message}` }],
783
+ isError: true,
784
+ };
785
+ }
786
+ },
787
+ renderCall(args: any, theme: any, context: any) {
788
+ const action = args?.action || "query";
789
+ const rawPath = args?.path || "";
790
+ const relPath = rawPath
791
+ ? path.relative(context.cwd, rawPath) || rawPath
792
+ : "";
793
+ const pos = args?.line ? `:${args.line}:${args.character || 1}` : "";
794
+ return makeOutputText(
795
+ `${theme.fg("toolTitle", theme.bold("lsp"))} ${theme.fg("accent", `${action} ${relPath}${pos}`)}`,
796
+ );
797
+ },
798
+ renderResult(result: any, options: any, theme: any, context: any) {
799
+ if (context.isError) {
800
+ const errMsg =
801
+ result.content?.find((c: any) => c.type === "text")?.text ||
802
+ "LSP request failed";
803
+ return makeOutputText(`\n${theme.fg("error", errMsg)}`);
804
+ }
805
+ if (!options.expanded) {
806
+ return new Text("", 0, 0);
807
+ }
808
+ const output =
809
+ result.content?.find((c: any) => c.type === "text")?.text || "";
810
+ return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
811
+ },
812
+ });
813
+ }