@aria-cli/tools 1.0.2 → 1.0.3

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 (157) hide show
  1. package/dist/.aria-build-stamp.json +1 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/definitions/code-intelligence.d.ts +9 -0
  4. package/dist/definitions/code-intelligence.d.ts.map +1 -0
  5. package/dist/definitions/code-intelligence.js +471 -0
  6. package/dist/definitions/code-intelligence.js.map +1 -0
  7. package/dist/definitions/core.d.ts +3 -0
  8. package/dist/definitions/core.d.ts.map +1 -1
  9. package/dist/definitions/core.js +13 -1
  10. package/dist/definitions/core.js.map +1 -1
  11. package/dist/definitions/filesystem.d.ts +3 -2
  12. package/dist/definitions/filesystem.d.ts.map +1 -1
  13. package/dist/definitions/filesystem.js +4 -38
  14. package/dist/definitions/filesystem.js.map +1 -1
  15. package/dist/definitions/frg.d.ts +4 -0
  16. package/dist/definitions/frg.d.ts.map +1 -0
  17. package/dist/definitions/frg.js +64 -0
  18. package/dist/definitions/frg.js.map +1 -0
  19. package/dist/definitions/index.d.ts +3 -0
  20. package/dist/definitions/index.d.ts.map +1 -1
  21. package/dist/definitions/index.js +3 -0
  22. package/dist/definitions/index.js.map +1 -1
  23. package/dist/definitions/search.d.ts +10 -0
  24. package/dist/definitions/search.d.ts.map +1 -0
  25. package/dist/definitions/search.js +61 -0
  26. package/dist/definitions/search.js.map +1 -0
  27. package/dist/executors/apply-patch.d.ts.map +1 -1
  28. package/dist/executors/apply-patch.js +18 -0
  29. package/dist/executors/apply-patch.js.map +1 -1
  30. package/dist/executors/code-intelligence.d.ts +139 -0
  31. package/dist/executors/code-intelligence.d.ts.map +1 -0
  32. package/dist/executors/code-intelligence.js +883 -0
  33. package/dist/executors/code-intelligence.js.map +1 -0
  34. package/dist/executors/filesystem.d.ts.map +1 -1
  35. package/dist/executors/filesystem.js +14 -8
  36. package/dist/executors/filesystem.js.map +1 -1
  37. package/dist/executors/frg-freshness.d.ts +94 -0
  38. package/dist/executors/frg-freshness.d.ts.map +1 -0
  39. package/dist/executors/frg-freshness.js +577 -0
  40. package/dist/executors/frg-freshness.js.map +1 -0
  41. package/dist/executors/frg.d.ts +28 -0
  42. package/dist/executors/frg.d.ts.map +1 -0
  43. package/dist/executors/frg.js +299 -0
  44. package/dist/executors/frg.js.map +1 -0
  45. package/dist/executors/index.d.ts +6 -0
  46. package/dist/executors/index.d.ts.map +1 -1
  47. package/dist/executors/index.js +5 -0
  48. package/dist/executors/index.js.map +1 -1
  49. package/dist/executors/lsp-client.d.ts +39 -0
  50. package/dist/executors/lsp-client.d.ts.map +1 -0
  51. package/dist/executors/lsp-client.js +297 -0
  52. package/dist/executors/lsp-client.js.map +1 -0
  53. package/dist/executors/restart.d.ts +4 -9
  54. package/dist/executors/restart.d.ts.map +1 -1
  55. package/dist/executors/restart.js +20 -51
  56. package/dist/executors/restart.js.map +1 -1
  57. package/dist/executors/search-freshness.d.ts +51 -0
  58. package/dist/executors/search-freshness.d.ts.map +1 -0
  59. package/dist/executors/search-freshness.js +196 -0
  60. package/dist/executors/search-freshness.js.map +1 -0
  61. package/dist/executors/search.d.ts +12 -0
  62. package/dist/executors/search.d.ts.map +1 -0
  63. package/dist/executors/search.js +67 -0
  64. package/dist/executors/search.js.map +1 -0
  65. package/dist/headless-control-contract.d.ts +4 -0
  66. package/dist/headless-control-contract.d.ts.map +1 -1
  67. package/dist/index.d.ts +2 -2
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +1 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/network-runtime/local-control-contract.d.ts +2 -0
  72. package/dist/network-runtime/local-control-contract.d.ts.map +1 -1
  73. package/dist/network-runtime/local-control-contract.js +2 -0
  74. package/dist/network-runtime/local-control-contract.js.map +1 -1
  75. package/dist-cjs/.tsbuildinfo +1 -1
  76. package/dist-cjs/definitions/code-intelligence.d.ts +8 -0
  77. package/dist-cjs/definitions/code-intelligence.js +474 -0
  78. package/dist-cjs/definitions/code-intelligence.js.map +1 -0
  79. package/dist-cjs/definitions/core.d.ts +3 -0
  80. package/dist-cjs/definitions/core.js +17 -2
  81. package/dist-cjs/definitions/core.js.map +1 -1
  82. package/dist-cjs/definitions/filesystem.d.ts +3 -2
  83. package/dist-cjs/definitions/filesystem.js +3 -37
  84. package/dist-cjs/definitions/filesystem.js.map +1 -1
  85. package/dist-cjs/definitions/frg.d.ts +3 -0
  86. package/dist-cjs/definitions/frg.js +67 -0
  87. package/dist-cjs/definitions/frg.js.map +1 -0
  88. package/dist-cjs/definitions/index.d.ts +3 -0
  89. package/dist-cjs/definitions/index.js +7 -1
  90. package/dist-cjs/definitions/index.js.map +1 -1
  91. package/dist-cjs/definitions/search.d.ts +9 -0
  92. package/dist-cjs/definitions/search.js +64 -0
  93. package/dist-cjs/definitions/search.js.map +1 -0
  94. package/dist-cjs/executors/apply-patch.js +18 -0
  95. package/dist-cjs/executors/apply-patch.js.map +1 -1
  96. package/dist-cjs/executors/code-intelligence.d.ts +138 -0
  97. package/dist-cjs/executors/code-intelligence.js +926 -0
  98. package/dist-cjs/executors/code-intelligence.js.map +1 -0
  99. package/dist-cjs/executors/filesystem.js +17 -8
  100. package/dist-cjs/executors/filesystem.js.map +1 -1
  101. package/dist-cjs/executors/frg-freshness.d.ts +93 -0
  102. package/dist-cjs/executors/frg-freshness.js +628 -0
  103. package/dist-cjs/executors/frg-freshness.js.map +1 -0
  104. package/dist-cjs/executors/frg.d.ts +27 -0
  105. package/dist-cjs/executors/frg.js +335 -0
  106. package/dist-cjs/executors/frg.js.map +1 -0
  107. package/dist-cjs/executors/index.d.ts +6 -0
  108. package/dist-cjs/executors/index.js +34 -2
  109. package/dist-cjs/executors/index.js.map +1 -1
  110. package/dist-cjs/executors/lsp-client.d.ts +38 -0
  111. package/dist-cjs/executors/lsp-client.js +311 -0
  112. package/dist-cjs/executors/lsp-client.js.map +1 -0
  113. package/dist-cjs/executors/restart.d.ts +4 -9
  114. package/dist-cjs/executors/restart.js +19 -50
  115. package/dist-cjs/executors/restart.js.map +1 -1
  116. package/dist-cjs/executors/search-freshness.d.ts +50 -0
  117. package/dist-cjs/executors/search-freshness.js +235 -0
  118. package/dist-cjs/executors/search-freshness.js.map +1 -0
  119. package/dist-cjs/executors/search.d.ts +11 -0
  120. package/dist-cjs/executors/search.js +103 -0
  121. package/dist-cjs/executors/search.js.map +1 -0
  122. package/dist-cjs/headless-control-contract.d.ts +15 -11
  123. package/dist-cjs/index.d.ts +2 -2
  124. package/dist-cjs/index.js +22 -2
  125. package/dist-cjs/index.js.map +1 -1
  126. package/dist-cjs/network-runtime/local-control-contract.d.ts +2 -0
  127. package/dist-cjs/network-runtime/local-control-contract.js +2 -0
  128. package/dist-cjs/network-runtime/local-control-contract.js.map +1 -1
  129. package/package.json +9 -5
  130. package/src/definitions/code-intelligence.ts +526 -0
  131. package/src/definitions/core.ts +13 -1
  132. package/src/definitions/filesystem.ts +3 -39
  133. package/src/definitions/frg.ts +67 -0
  134. package/src/definitions/index.ts +3 -0
  135. package/src/definitions/search.ts +67 -0
  136. package/src/executors/apply-patch.ts +20 -0
  137. package/src/executors/code-intelligence.ts +1179 -0
  138. package/src/executors/filesystem.ts +15 -8
  139. package/src/executors/frg-freshness.ts +743 -0
  140. package/src/executors/frg.ts +394 -0
  141. package/src/executors/index.ts +58 -0
  142. package/src/executors/lsp-client.ts +355 -0
  143. package/src/executors/restart.ts +21 -56
  144. package/src/executors/search-freshness.ts +249 -0
  145. package/src/executors/search.ts +89 -0
  146. package/src/index.ts +25 -0
  147. package/src/network-runtime/local-control-contract.ts +2 -0
  148. package/tests/definitions/tool-inventory.test.ts +17 -6
  149. package/tests/executors/frg-freshness.test.ts +136 -0
  150. package/tests/executors/frg-merge.test.ts +70 -0
  151. package/tests/executors/frg-session-content.test.ts +40 -0
  152. package/tests/executors/frg.test.ts +56 -0
  153. package/tests/integration/headless-control-contract.integration.test.ts +2 -0
  154. package/tests/loading-tier.test.ts +6 -6
  155. package/tests/test-lane-manifest.ts +4 -0
  156. package/tsconfig.cjs.json +9 -1
  157. package/tsconfig.json +1 -1
@@ -0,0 +1,1179 @@
1
+ /**
2
+ * @aria/tools - Code intelligence executors
3
+ *
4
+ * 7 native tools wrapping external CLI binaries:
5
+ * rg (ripgrep), ug (ugrep), probe, sg (ast-grep),
6
+ * cbm (codebase-memory-mcp), serena, fff
7
+ */
8
+
9
+ import { execFile, spawn as cpSpawn } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+ import { existsSync, readdirSync, statSync } from "node:fs";
12
+ import { resolve as pathResolve, dirname, join as pathJoin } from "node:path";
13
+ import { createConnection } from "node:net";
14
+ import type { ToolContext, ToolResult } from "../types.js";
15
+ import { success, fail } from "./utils.js";
16
+
17
+ const execFileAsync = promisify(execFile);
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Shared helpers
21
+ // ---------------------------------------------------------------------------
22
+
23
+ const binaryCache = new Map<string, boolean>();
24
+
25
+ async function hasBinary(name: string): Promise<boolean> {
26
+ if (binaryCache.has(name)) return binaryCache.get(name)!;
27
+ try {
28
+ await execFileAsync("which", [name]);
29
+ binaryCache.set(name, true);
30
+ } catch {
31
+ binaryCache.set(name, false);
32
+ }
33
+ return binaryCache.get(name)!;
34
+ }
35
+
36
+ async function shellExec(
37
+ cmd: string,
38
+ args: string[],
39
+ opts: { cwd?: string; timeout?: number; signal?: AbortSignal },
40
+ ): Promise<{ stdout: string; stderr: string }> {
41
+ return execFileAsync(cmd, args, {
42
+ cwd: opts.cwd,
43
+ timeout: opts.timeout ?? 30_000,
44
+ signal: opts.signal,
45
+ maxBuffer: 10 * 1024 * 1024, // 10MB
46
+ });
47
+ }
48
+
49
+ function pushIf(args: string[], condition: unknown, ...flags: string[]): void {
50
+ if (condition) args.push(...flags);
51
+ }
52
+
53
+ function mergeExtraArgs(args: string[], extra?: string[]): void {
54
+ if (extra?.length) args.push(...extra);
55
+ }
56
+
57
+ function escapeRegex(str: string): string {
58
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
+ }
60
+
61
+ interface ExecError {
62
+ code?: number;
63
+ stderr?: string;
64
+ message?: string;
65
+ }
66
+
67
+ function asExecError(err: unknown): ExecError {
68
+ if (err && typeof err === "object") return err as ExecError;
69
+ return { message: String(err) };
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Input types
74
+ // ---------------------------------------------------------------------------
75
+
76
+ export interface RgInput {
77
+ pattern: string;
78
+ path?: string;
79
+ ignore_case?: boolean;
80
+ smart_case?: boolean;
81
+ fixed_strings?: boolean;
82
+ word_regexp?: boolean;
83
+ file_type?: string;
84
+ glob?: string;
85
+ context?: number;
86
+ max_count?: number;
87
+ invert?: boolean;
88
+ files_only?: boolean;
89
+ count?: boolean;
90
+ extra_args?: string[];
91
+ }
92
+
93
+ export interface UgInput {
94
+ pattern: string;
95
+ path?: string;
96
+ ignore_case?: boolean;
97
+ smart_case?: boolean;
98
+ fixed_strings?: boolean;
99
+ word_regexp?: boolean;
100
+ file_type?: string;
101
+ glob?: string;
102
+ context?: number;
103
+ max_count?: number;
104
+ fuzzy?: boolean | number;
105
+ bool?: boolean;
106
+ neg_pattern?: string;
107
+ files_only?: boolean;
108
+ count?: boolean;
109
+ decompress?: boolean;
110
+ extra_args?: string[];
111
+ }
112
+
113
+ export interface ProbeInput {
114
+ command?: "search" | "extract" | "symbols" | "query";
115
+ query?: string;
116
+ path?: string;
117
+ exact?: boolean;
118
+ max_tokens?: number;
119
+ max_results?: number;
120
+ session?: string;
121
+ language?: string;
122
+ reranker?: string;
123
+ allow_tests?: boolean;
124
+ files?: string[];
125
+ extra_args?: string[];
126
+ }
127
+
128
+ export interface SgInput {
129
+ command?: "run" | "scan";
130
+ pattern?: string;
131
+ language?: string;
132
+ rewrite?: string;
133
+ strictness?: "cst" | "smart" | "ast" | "relaxed" | "signature";
134
+ globs?: string;
135
+ rule?: string;
136
+ inline_rules?: string;
137
+ path?: string;
138
+ update_all?: boolean;
139
+ context?: number;
140
+ extra_args?: string[];
141
+ }
142
+
143
+ export interface CbmInput {
144
+ action:
145
+ | "index"
146
+ | "search"
147
+ | "trace"
148
+ | "impact"
149
+ | "context"
150
+ | "snippet"
151
+ | "code_search"
152
+ | "architecture"
153
+ | "schema"
154
+ | "cypher"
155
+ | "list_projects"
156
+ | "delete_project"
157
+ | "status";
158
+ path?: string;
159
+ mode?: "full" | "fast";
160
+ name?: string;
161
+ label?: string;
162
+ file?: string;
163
+ direction?: "inbound" | "outbound" | "both";
164
+ depth?: number;
165
+ edge_types?: string[];
166
+ scope?: string;
167
+ base_branch?: string;
168
+ qualified_name?: string;
169
+ include_neighbors?: boolean;
170
+ code_pattern?: string;
171
+ regex?: boolean;
172
+ code_mode?: "compact" | "full" | "files";
173
+ query?: string;
174
+ max_rows?: number;
175
+ project?: string;
176
+ limit?: number;
177
+ context?: number;
178
+ }
179
+
180
+ export interface LspInput {
181
+ action: "definition" | "references" | "hover" | "symbols" | "rename";
182
+ file: string;
183
+ line?: number;
184
+ character?: number;
185
+ new_name?: string;
186
+ }
187
+
188
+ export interface SerenaInput {
189
+ action:
190
+ | "find_symbol"
191
+ | "find_references"
192
+ | "overview"
193
+ | "replace_body"
194
+ | "insert_after"
195
+ | "insert_before"
196
+ | "rename"
197
+ | "search";
198
+ name_path?: string;
199
+ relative_path?: string;
200
+ include_body?: boolean;
201
+ include_info?: boolean;
202
+ depth?: number;
203
+ body?: string;
204
+ new_name?: string;
205
+ pattern?: string;
206
+ context_before?: number;
207
+ context_after?: number;
208
+ paths_include?: string;
209
+ paths_exclude?: string;
210
+ extra_args?: Record<string, unknown>;
211
+ }
212
+
213
+ export interface FffInput {
214
+ action: "grep" | "find_files" | "multi_grep";
215
+ query?: string;
216
+ patterns?: string[];
217
+ constraints?: string;
218
+ path?: string;
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Output types
223
+ // ---------------------------------------------------------------------------
224
+
225
+ export interface RgMatch {
226
+ file: string;
227
+ line: number;
228
+ text: string;
229
+ submatches: string[];
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // 1. rg — ripgrep
234
+ // ---------------------------------------------------------------------------
235
+
236
+ export async function executeRg(input: RgInput, ctx: ToolContext): Promise<ToolResult> {
237
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
238
+ if (!(await hasBinary("rg")))
239
+ return fail("ripgrep (rg) not installed. Install: brew install ripgrep");
240
+
241
+ // When count mode is active, rg -c outputs plain text (file:count) even with --json.
242
+ // We omit --json and parse the plain-text output instead.
243
+ const rgCountMode = !!input.count;
244
+ const args = rgCountMode
245
+ ? ["--line-number", "--color", "never"]
246
+ : ["--json", "--line-number", "--color", "never"];
247
+
248
+ pushIf(args, input.ignore_case, "-i");
249
+ pushIf(args, input.smart_case, "-S");
250
+ pushIf(args, input.fixed_strings, "-F");
251
+ pushIf(args, input.word_regexp, "-w");
252
+ pushIf(args, input.invert, "-v");
253
+ pushIf(args, input.files_only, "-l");
254
+ pushIf(args, input.count, "-c");
255
+ if (input.file_type) args.push("-t", input.file_type);
256
+ if (input.glob) args.push("-g", input.glob);
257
+ if (input.context != null) args.push("-C", String(input.context));
258
+ if (input.max_count != null) args.push("-m", String(input.max_count));
259
+
260
+ mergeExtraArgs(args, input.extra_args);
261
+ args.push("--", input.pattern);
262
+ args.push(input.path ?? ctx.workingDir);
263
+
264
+ try {
265
+ const { stdout } = await shellExec("rg", args, {
266
+ cwd: ctx.workingDir,
267
+ signal: ctx.abortSignal,
268
+ });
269
+ if (rgCountMode) {
270
+ const counts = parseRipgrepCount(stdout);
271
+ const total = counts.reduce((s, c) => s + c.count, 0);
272
+ return success(
273
+ `Found ${total} matches across ${counts.length} files for "${input.pattern}"`,
274
+ { counts, total },
275
+ );
276
+ }
277
+ const matches = parseRipgrepJson(stdout);
278
+ return success(`Found ${matches.length} matches for "${input.pattern}"`, { matches });
279
+ } catch (err: unknown) {
280
+ const e = asExecError(err);
281
+ if (e.code === 1) return success("No matches found", { matches: [] });
282
+ return fail(`rg failed: ${e.stderr || e.message}`);
283
+ }
284
+ }
285
+
286
+ function parseRipgrepJson(stdout: string): RgMatch[] {
287
+ const matches: RgMatch[] = [];
288
+ for (const line of stdout.split("\n")) {
289
+ if (!line.trim()) continue;
290
+ try {
291
+ const obj = JSON.parse(line);
292
+ if (obj.type === "match") {
293
+ matches.push({
294
+ file: obj.data.path.text,
295
+ line: obj.data.line_number,
296
+ text: obj.data.lines.text.trimEnd(),
297
+ submatches:
298
+ obj.data.submatches?.map(
299
+ (s: Record<string, unknown>) => (s.match as Record<string, unknown>)?.text,
300
+ ) ?? [],
301
+ });
302
+ }
303
+ } catch {
304
+ // Skip malformed lines
305
+ }
306
+ }
307
+ return matches;
308
+ }
309
+
310
+ /** Parse rg/ug plain-text count output: `file:count` per line.
311
+ * Filters out files with 0 matches (ug -c outputs 0-count lines, rg doesn't). */
312
+ function parseRipgrepCount(stdout: string): Array<{ file: string; count: number }> {
313
+ const counts: Array<{ file: string; count: number }> = [];
314
+ for (const line of stdout.split("\n")) {
315
+ if (!line.trim()) continue;
316
+ const lastColon = line.lastIndexOf(":");
317
+ if (lastColon === -1) continue;
318
+ const file = line.slice(0, lastColon);
319
+ const count = parseInt(line.slice(lastColon + 1), 10);
320
+ if (!isNaN(count) && count > 0) counts.push({ file, count });
321
+ }
322
+ return counts;
323
+ }
324
+
325
+ // ---------------------------------------------------------------------------
326
+ // 2. ug — ugrep
327
+ // ---------------------------------------------------------------------------
328
+
329
+ export async function executeUg(input: UgInput, ctx: ToolContext): Promise<ToolResult> {
330
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
331
+ if (!(await hasBinary("ug")))
332
+ return fail("ugrep (ug) not installed. Install: brew install ugrep");
333
+
334
+ // --ignore-files: respect .gitignore / .ignore (parity with rg default behaviour).
335
+ // --ignore-binary: skip binary files (tar, images, etc.) — rg skips them by default.
336
+ // Without these flags ug searches dist/, node_modules/, .tar archives, etc.
337
+ const ugCountMode = !!input.count;
338
+ const args = ugCountMode
339
+ ? ["--line-number", "--color=never", "-r", "--ignore-files", "--ignore-binary"]
340
+ : ["--json", "--line-number", "--color=never", "-r", "--ignore-files", "--ignore-binary"];
341
+
342
+ pushIf(args, input.ignore_case, "-i");
343
+ pushIf(args, input.smart_case, "-j");
344
+ pushIf(args, input.fixed_strings, "-F");
345
+ pushIf(args, input.word_regexp, "-w");
346
+ pushIf(args, input.files_only, "-l");
347
+ pushIf(args, input.count, "-c");
348
+ pushIf(args, input.decompress, "-z");
349
+ if (input.file_type) args.push("-t", input.file_type);
350
+ if (input.glob) args.push("-g", input.glob);
351
+ if (input.context != null) args.push("-C", String(input.context));
352
+ if (input.max_count != null) args.push("-m", String(input.max_count));
353
+ if (input.neg_pattern) args.push("-N", input.neg_pattern);
354
+
355
+ // Fuzzy matching
356
+ if (input.fuzzy === true) {
357
+ args.push("-Z");
358
+ } else if (typeof input.fuzzy === "number") {
359
+ args.push(`-Z${input.fuzzy}`);
360
+ }
361
+
362
+ // Boolean query mode
363
+ if (input.bool) args.push("-%%");
364
+
365
+ mergeExtraArgs(args, input.extra_args);
366
+ args.push("--", input.pattern);
367
+ args.push(input.path ?? ctx.workingDir);
368
+
369
+ try {
370
+ const { stdout } = await shellExec("ug", args, {
371
+ cwd: ctx.workingDir,
372
+ signal: ctx.abortSignal,
373
+ });
374
+ if (ugCountMode) {
375
+ const counts = parseRipgrepCount(stdout); // same file:count format
376
+ const total = counts.reduce((s, c) => s + c.count, 0);
377
+ return success(
378
+ `Found ${total} matches across ${counts.length} files for "${input.pattern}"`,
379
+ { counts, total },
380
+ );
381
+ }
382
+ const matches = parseUgrepJson(stdout);
383
+ return success(`Found ${matches.length} matches for "${input.pattern}"`, { matches });
384
+ } catch (err: unknown) {
385
+ const e = asExecError(err);
386
+ if (e.code === 1) return success("No matches found", { matches: [] });
387
+ return fail(`ug failed: ${e.stderr || e.message}`);
388
+ }
389
+ }
390
+
391
+ function parseUgrepJson(stdout: string): RgMatch[] {
392
+ // ugrep --json outputs: [{ file, matches: [{ line, match }] }]
393
+ // This is a JSON array, NOT NDJSON like ripgrep
394
+ const results: RgMatch[] = [];
395
+ try {
396
+ const parsed = JSON.parse(stdout) as Array<{
397
+ file: string;
398
+ matches: Array<{ line: number; match: string }>;
399
+ }>;
400
+ for (const fileGroup of parsed) {
401
+ for (const m of fileGroup.matches) {
402
+ results.push({
403
+ file: fileGroup.file,
404
+ line: m.line,
405
+ text: m.match.trimEnd(),
406
+ submatches: [],
407
+ });
408
+ }
409
+ }
410
+ } catch {
411
+ // Fallback: try NDJSON parsing in case format varies
412
+ for (const line of stdout.split("\n")) {
413
+ if (!line.trim()) continue;
414
+ try {
415
+ const obj = JSON.parse(line);
416
+ if (obj.file && obj.matches) {
417
+ for (const m of obj.matches) {
418
+ results.push({
419
+ file: obj.file,
420
+ line: m.line,
421
+ text: m.match?.trimEnd() ?? "",
422
+ submatches: [],
423
+ });
424
+ }
425
+ }
426
+ } catch {
427
+ // Skip
428
+ }
429
+ }
430
+ }
431
+ return results;
432
+ }
433
+
434
+ // ---------------------------------------------------------------------------
435
+ // 3. probe
436
+ // ---------------------------------------------------------------------------
437
+
438
+ export async function executeProbe(input: ProbeInput, ctx: ToolContext): Promise<ToolResult> {
439
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
440
+ if (!(await hasBinary("probe")))
441
+ return fail("probe not installed. Install: npm install -g @probelabs/probe");
442
+
443
+ const cmd = input.command ?? "search";
444
+ const args: string[] = [cmd];
445
+
446
+ switch (cmd) {
447
+ case "search": {
448
+ if (!input.query) return fail("query required for search");
449
+ pushIf(args, input.exact, "--exact");
450
+ pushIf(args, input.allow_tests, "--allow-tests");
451
+ if (input.max_tokens != null) args.push("--max-tokens", String(input.max_tokens));
452
+ if (input.max_results != null) args.push("--max-results", String(input.max_results));
453
+ if (input.session) args.push("--session", input.session);
454
+ if (input.language) args.push("--language", input.language);
455
+ if (input.reranker) args.push("--reranker", input.reranker);
456
+ args.push("--format", "json");
457
+ mergeExtraArgs(args, input.extra_args);
458
+ args.push("--", input.query);
459
+ if (input.path) args.push(input.path);
460
+ break;
461
+ }
462
+ case "extract": {
463
+ if (!input.files?.length) return fail("files required for extract");
464
+ args.push("--format", "json");
465
+ mergeExtraArgs(args, input.extra_args);
466
+ args.push(...input.files);
467
+ break;
468
+ }
469
+ case "symbols": {
470
+ // Accept files via `files` array or fall back to `query` as a file path
471
+ const symbolFiles = input.files?.length ? input.files : input.query ? [input.query] : [];
472
+ if (!symbolFiles.length)
473
+ return fail("files required for symbols (pass via 'files' or 'query')");
474
+ args.push("--format", "json");
475
+ mergeExtraArgs(args, input.extra_args);
476
+ args.push(...symbolFiles);
477
+ break;
478
+ }
479
+ case "query": {
480
+ if (!input.query) return fail("query (AST pattern) required for query command");
481
+ if (input.language) args.push("--language", input.language);
482
+ if (input.max_results != null) args.push("--max-results", String(input.max_results));
483
+ pushIf(args, input.allow_tests, "--allow-tests");
484
+ args.push("--format", "json");
485
+ mergeExtraArgs(args, input.extra_args);
486
+ args.push("--", input.query);
487
+ if (input.path) args.push(input.path);
488
+ break;
489
+ }
490
+ }
491
+
492
+ try {
493
+ const { stdout } = await shellExec("probe", args, {
494
+ cwd: ctx.workingDir,
495
+ signal: ctx.abortSignal,
496
+ timeout: 60_000,
497
+ });
498
+ try {
499
+ const data = JSON.parse(stdout);
500
+ return success(`probe ${cmd} completed`, data);
501
+ } catch {
502
+ // If not valid JSON, return raw output
503
+ return success(`probe ${cmd} completed`, { raw: stdout });
504
+ }
505
+ } catch (err: unknown) {
506
+ const e = asExecError(err);
507
+ return fail(`probe ${cmd} failed: ${e.stderr || e.message}`);
508
+ }
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // 4. sg — ast-grep
513
+ // ---------------------------------------------------------------------------
514
+
515
+ export async function executeSg(input: SgInput, ctx: ToolContext): Promise<ToolResult> {
516
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
517
+ if (!(await hasBinary("sg")))
518
+ return fail("ast-grep (sg) not installed. Install: cargo install ast-grep --locked");
519
+
520
+ const cmd = input.command ?? "run";
521
+ const isMutation = !!(input.rewrite || input.update_all);
522
+
523
+ // Require confirmation for mutations
524
+ if (isMutation && !input.update_all && ctx.confirm) {
525
+ const approved = await ctx.confirm(
526
+ `Rewrite code matching \`${input.pattern}\` to \`${input.rewrite}\` in ${input.language || "auto-detected"} files?`,
527
+ );
528
+ if (!approved) return fail("Rewrite cancelled by user");
529
+ }
530
+
531
+ const args: string[] = [cmd];
532
+
533
+ if (cmd === "run") {
534
+ if (!input.pattern) return fail("pattern required for sg run");
535
+ args.push("--pattern", input.pattern);
536
+ if (input.language) args.push("--lang", input.language);
537
+ if (input.rewrite) args.push("--rewrite", input.rewrite);
538
+ if (input.strictness) args.push("--strictness", input.strictness);
539
+ pushIf(args, input.update_all, "-U");
540
+ } else if (cmd === "scan") {
541
+ if (input.rule) args.push("--rule", input.rule);
542
+ if (input.inline_rules) args.push("--inline-rules", input.inline_rules);
543
+ }
544
+
545
+ // Shared flags
546
+ if (input.globs) args.push("--globs", input.globs);
547
+ if (input.context != null) args.push("-C", String(input.context));
548
+
549
+ // Always JSON for machine parsing, skip color
550
+ if (!isMutation) {
551
+ args.push("--json=compact");
552
+ }
553
+ args.push("--color", "never");
554
+
555
+ mergeExtraArgs(args, input.extra_args);
556
+ args.push(input.path ?? ctx.workingDir);
557
+
558
+ try {
559
+ const { stdout } = await shellExec("sg", args, {
560
+ cwd: ctx.workingDir,
561
+ signal: ctx.abortSignal,
562
+ });
563
+ if (isMutation) {
564
+ return success(`sg ${cmd}: rewrites applied`, { raw: stdout });
565
+ }
566
+ try {
567
+ const data = JSON.parse(stdout);
568
+ const count = Array.isArray(data) ? data.length : 0;
569
+ return success(`Found ${count} matches`, { matches: data });
570
+ } catch {
571
+ return success(`sg ${cmd} completed`, { raw: stdout });
572
+ }
573
+ } catch (err: unknown) {
574
+ // Exit code 1 = no matches for run
575
+ const e = asExecError(err);
576
+ if (e.code === 1 && cmd === "run") return success("No matches found", { matches: [] });
577
+ return fail(`sg ${cmd} failed: ${e.stderr || e.message}`);
578
+ }
579
+ }
580
+
581
+ // ---------------------------------------------------------------------------
582
+ // 5. cbm — codebase-memory-mcp
583
+ // ---------------------------------------------------------------------------
584
+
585
+ // Internal helper to call cbm CLI
586
+ async function cbmCall(
587
+ tool: string,
588
+ params: Record<string, unknown>,
589
+ ctx: ToolContext,
590
+ timeout?: number,
591
+ ): Promise<unknown> {
592
+ // Remove undefined/null values from params
593
+ const clean: Record<string, unknown> = {};
594
+ for (const [k, v] of Object.entries(params)) {
595
+ if (v !== undefined && v !== null) clean[k] = v;
596
+ }
597
+ const { stdout } = await shellExec("codebase-memory-mcp", ["cli", tool, JSON.stringify(clean)], {
598
+ cwd: ctx.workingDir,
599
+ signal: ctx.abortSignal,
600
+ timeout: timeout ?? 30_000,
601
+ });
602
+ // cbm cli returns MCP content format: { content: [{ type: "text", text: "..." }] }
603
+ // Filter log lines (level=info ...) and parse
604
+ const jsonLines = stdout.split("\n").filter((l) => l.trim() && !l.startsWith("level="));
605
+ const parsed = JSON.parse(jsonLines.join("\n")) as Record<string, unknown>;
606
+ if (Array.isArray(parsed.content)) {
607
+ const textBlocks = (parsed.content as Array<{ type: string; text: string }>)
608
+ .filter((c) => c.type === "text")
609
+ .map((c) => c.text);
610
+ const combined = textBlocks.join("\n");
611
+ try {
612
+ return JSON.parse(combined);
613
+ } catch {
614
+ return { text: combined };
615
+ }
616
+ }
617
+ return parsed;
618
+ }
619
+
620
+ export async function executeCbm(input: CbmInput, ctx: ToolContext): Promise<ToolResult> {
621
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
622
+ if (!(await hasBinary("codebase-memory-mcp")))
623
+ return fail(
624
+ "codebase-memory-mcp not installed. Install:\ncurl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/scripts/setup.sh | bash",
625
+ );
626
+
627
+ // Auto-detect project name: cbm slugifies repo_path by replacing / with -
628
+ // and stripping the leading separator: /Users/hole/aria → Users-hole-aria
629
+ const p = input.project ?? (input.path ?? ctx.workingDir).replace(/^\//, "").replace(/\//g, "-");
630
+
631
+ // Auto-index: if the action requires an indexed project and no project exists,
632
+ // transparently run a fast index first so queries don't silently return empty.
633
+ const queryActions = new Set([
634
+ "search",
635
+ "trace",
636
+ "impact",
637
+ "context",
638
+ "snippet",
639
+ "code_search",
640
+ "architecture",
641
+ "schema",
642
+ "cypher",
643
+ ]);
644
+ if (queryActions.has(input.action)) {
645
+ let needsIndex = false;
646
+ try {
647
+ const statusResult = (await cbmCall("index_status", { project: p }, ctx)) as Record<
648
+ string,
649
+ unknown
650
+ >;
651
+ // If status indicates no project or empty graph, auto-index
652
+ if (
653
+ statusResult?.status === "no_project" ||
654
+ statusResult?.node_count === 0 ||
655
+ statusResult?.error
656
+ ) {
657
+ needsIndex = true;
658
+ }
659
+ } catch {
660
+ // index_status failed — likely no project
661
+ needsIndex = true;
662
+ }
663
+ if (needsIndex) {
664
+ try {
665
+ await cbmCall(
666
+ "index_repository",
667
+ { repo_path: input.path ?? ctx.workingDir, mode: "full" },
668
+ ctx,
669
+ 300_000,
670
+ );
671
+ } catch {
672
+ // If auto-index fails, continue — let the actual action produce the error
673
+ }
674
+ }
675
+ }
676
+
677
+ switch (input.action) {
678
+ case "index":
679
+ return success(
680
+ "Indexed",
681
+ await cbmCall(
682
+ "index_repository",
683
+ { repo_path: input.path ?? ctx.workingDir, mode: input.mode ?? "full" },
684
+ ctx,
685
+ 300_000, // 5 min timeout for indexing
686
+ ),
687
+ );
688
+
689
+ case "search":
690
+ return success(
691
+ "Search results",
692
+ await cbmCall(
693
+ "search_graph",
694
+ {
695
+ project: p,
696
+ name_pattern: input.name,
697
+ label: input.label,
698
+ file_pattern: input.file,
699
+ limit: input.limit ?? 20,
700
+ },
701
+ ctx,
702
+ ),
703
+ );
704
+
705
+ case "trace": {
706
+ if (!input.name) return fail("name required for trace");
707
+ return success(
708
+ `Call chain: ${input.name}`,
709
+ await cbmCall(
710
+ "trace_call_path",
711
+ {
712
+ project: p,
713
+ function_name: input.name,
714
+ direction: input.direction ?? "both",
715
+ depth: input.depth ?? 3,
716
+ edge_types: input.edge_types,
717
+ },
718
+ ctx,
719
+ ),
720
+ );
721
+ }
722
+
723
+ case "impact":
724
+ return success(
725
+ "Impact analysis",
726
+ await cbmCall(
727
+ "detect_changes",
728
+ {
729
+ project: p,
730
+ scope: input.scope,
731
+ depth: input.depth ?? 2,
732
+ base_branch: input.base_branch ?? "main",
733
+ },
734
+ ctx,
735
+ ),
736
+ );
737
+
738
+ case "context": {
739
+ if (!input.name) return fail("name required for context");
740
+ const [sym, callers, callees] = await Promise.all([
741
+ cbmCall(
742
+ "search_graph",
743
+ { project: p, name_pattern: `^${escapeRegex(input.name)}$`, limit: 1 },
744
+ ctx,
745
+ ),
746
+ cbmCall(
747
+ "trace_call_path",
748
+ { project: p, function_name: input.name, direction: "inbound", depth: 2 },
749
+ ctx,
750
+ ),
751
+ cbmCall(
752
+ "trace_call_path",
753
+ { project: p, function_name: input.name, direction: "outbound", depth: 2 },
754
+ ctx,
755
+ ),
756
+ ]);
757
+ return success(`360° context: ${input.name}`, {
758
+ definition: (sym as Record<string, unknown[]>).results?.[0],
759
+ callers,
760
+ callees,
761
+ });
762
+ }
763
+
764
+ case "snippet": {
765
+ if (!input.qualified_name) return fail("qualified_name required for snippet");
766
+ return success(
767
+ "Code snippet",
768
+ await cbmCall(
769
+ "get_code_snippet",
770
+ {
771
+ project: p,
772
+ qualified_name: input.qualified_name,
773
+ include_neighbors: input.include_neighbors,
774
+ },
775
+ ctx,
776
+ ),
777
+ );
778
+ }
779
+
780
+ case "code_search":
781
+ return success(
782
+ "Code search",
783
+ await cbmCall(
784
+ "search_code",
785
+ {
786
+ project: p,
787
+ pattern: input.code_pattern,
788
+ mode: input.code_mode ?? "compact",
789
+ regex: input.regex,
790
+ limit: input.limit ?? 10,
791
+ file_pattern: input.file,
792
+ context: input.context,
793
+ },
794
+ ctx,
795
+ ),
796
+ );
797
+
798
+ case "architecture":
799
+ return success("Architecture", await cbmCall("get_architecture", { project: p }, ctx));
800
+
801
+ case "schema":
802
+ return success("Schema", await cbmCall("get_graph_schema", { project: p }, ctx));
803
+
804
+ case "cypher": {
805
+ if (!input.query) return fail("query required for cypher");
806
+ return success(
807
+ "Cypher result",
808
+ await cbmCall(
809
+ "query_graph",
810
+ { project: p, query: input.query, max_rows: input.max_rows },
811
+ ctx,
812
+ ),
813
+ );
814
+ }
815
+
816
+ case "list_projects":
817
+ return success("Projects", await cbmCall("list_projects", {}, ctx));
818
+
819
+ case "delete_project": {
820
+ if (!input.project) return fail("project required for delete_project");
821
+ if (ctx.confirm) {
822
+ const ok = await ctx.confirm(`Delete project "${input.project}" from cbm index?`);
823
+ if (!ok) return fail("Cancelled");
824
+ }
825
+ return success("Deleted", await cbmCall("delete_project", { project: p }, ctx));
826
+ }
827
+
828
+ case "status":
829
+ return success("Status", await cbmCall("index_status", { project: p }, ctx));
830
+
831
+ default:
832
+ return fail(`Unknown cbm action: ${input.action}`);
833
+ }
834
+ }
835
+
836
+ // ---------------------------------------------------------------------------
837
+ // 6. lsp — native LSP client (direct JSON-RPC to language servers, no Serena, no MCP, no HTTP)
838
+ // ---------------------------------------------------------------------------
839
+
840
+ // Dynamic import for ESM-only lsp-client (allows CJS build to succeed)
841
+ // Type is loose to avoid pulling lsp-client.ts into CJS build graph
842
+ interface LspClientModule {
843
+ getServerForFile: (file: string) => string | undefined;
844
+ getOrCreateServer: (
845
+ serverName: string,
846
+ rootPath: string,
847
+ ) => {
848
+ start: () => Promise<void>;
849
+ definition: (file: string, line: number, char: number) => Promise<unknown>;
850
+ references: (file: string, line: number, char: number) => Promise<unknown>;
851
+ hover: (file: string, line: number, char: number) => Promise<unknown>;
852
+ documentSymbols: (file: string) => Promise<unknown>;
853
+ rename: (file: string, line: number, char: number, newName: string) => Promise<unknown>;
854
+ };
855
+ LSP_SERVERS: Record<string, { extensionToLanguage: Record<string, string> }>;
856
+ }
857
+ let _lspClient: LspClientModule | undefined;
858
+ async function getLspClient(): Promise<LspClientModule> {
859
+ if (!_lspClient) {
860
+ // Use variable to prevent TypeScript from following the import in CJS build
861
+ const modulePath = "./lsp-client.js";
862
+ _lspClient = (await import(/* webpackIgnore: true */ modulePath)) as LspClientModule;
863
+ }
864
+ return _lspClient;
865
+ }
866
+
867
+ export async function executeLsp(input: LspInput, ctx: ToolContext): Promise<ToolResult> {
868
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
869
+
870
+ if (!input.file) return fail("file required");
871
+
872
+ const { getServerForFile, getOrCreateServer, LSP_SERVERS } = await getLspClient();
873
+
874
+ const serverName = getServerForFile(input.file);
875
+ if (!serverName) {
876
+ const ext = input.file.slice(input.file.lastIndexOf("."));
877
+ const supported = Object.entries(LSP_SERVERS)
878
+ .map(([name, cfg]) => `${name}: ${Object.keys(cfg.extensionToLanguage).join(", ")}`)
879
+ .join("\n ");
880
+ return fail(`No language server for extension "${ext}". Supported:\n ${supported}`);
881
+ }
882
+
883
+ // Rename requires confirmation
884
+ if (input.action === "rename" && ctx.confirm) {
885
+ const ok = await ctx.confirm(
886
+ `Rename symbol at ${input.file}:${input.line}:${input.character} to "${input.new_name}"?`,
887
+ );
888
+ if (!ok) return fail("Cancelled by user");
889
+ }
890
+
891
+ const server = getOrCreateServer(serverName, ctx.workingDir);
892
+
893
+ try {
894
+ await server.start();
895
+
896
+ switch (input.action) {
897
+ case "definition": {
898
+ if (input.line == null || input.character == null)
899
+ return fail("line and character required for definition");
900
+ const result = await server.definition(input.file, input.line, input.character);
901
+ return success(`lsp definition`, result);
902
+ }
903
+
904
+ case "references": {
905
+ if (input.line == null || input.character == null)
906
+ return fail("line and character required for references");
907
+ const result = await server.references(input.file, input.line, input.character);
908
+ return success(`lsp references`, result);
909
+ }
910
+
911
+ case "hover": {
912
+ if (input.line == null || input.character == null)
913
+ return fail("line and character required for hover");
914
+ const result = await server.hover(input.file, input.line, input.character);
915
+ return success(`lsp hover`, result);
916
+ }
917
+
918
+ case "symbols": {
919
+ const result = await server.documentSymbols(input.file);
920
+ return success(`lsp symbols`, result);
921
+ }
922
+
923
+ case "rename": {
924
+ if (input.line == null || input.character == null || !input.new_name)
925
+ return fail("line, character, and new_name required for rename");
926
+ const result = await server.rename(input.file, input.line, input.character, input.new_name);
927
+ return success(`lsp rename`, result);
928
+ }
929
+
930
+ default:
931
+ return fail(
932
+ `Unknown lsp action: ${input.action}. Use: definition, references, hover, symbols, rename`,
933
+ );
934
+ }
935
+ } catch (err: unknown) {
936
+ const e = asExecError(err);
937
+ return fail(`lsp ${input.action} failed: ${e.message}`);
938
+ }
939
+ }
940
+
941
+ // ---------------------------------------------------------------------------
942
+ // 7. serena — HTTP project server (kept alongside native LSP for full Serena API)
943
+ // ---------------------------------------------------------------------------
944
+
945
+ const SERENA_PORT = 9750;
946
+ const SERENA_BASE = `http://127.0.0.1:${SERENA_PORT}`;
947
+ const SERENA_PROJECT = "aria";
948
+
949
+ const SERENA_TOOL_MAP: Record<string, string> = {
950
+ find_symbol: "find_symbol",
951
+ find_references: "find_referencing_symbols",
952
+ overview: "get_symbols_overview",
953
+ replace_body: "replace_symbol_body",
954
+ insert_after: "insert_after_symbol",
955
+ insert_before: "insert_before_symbol",
956
+ rename: "rename_symbol",
957
+ search: "search_for_pattern",
958
+ };
959
+
960
+ // ---------------------------------------------------------------------------
961
+ // Serena auto-start: spawn the HTTP project server on demand
962
+ // ---------------------------------------------------------------------------
963
+
964
+ let serenaStarting: Promise<boolean> | null = null;
965
+
966
+ async function isSerenaAlive(): Promise<boolean> {
967
+ // Lightweight TCP probe — just check if something is listening on the port.
968
+ // A full HTTP request is too heavy during startup (Serena takes seconds to load projects).
969
+ return new Promise<boolean>((resolve) => {
970
+ const sock = createConnection({ host: "127.0.0.1", port: SERENA_PORT }, () => {
971
+ sock.destroy();
972
+ resolve(true);
973
+ });
974
+ sock.setTimeout(2_000);
975
+ sock.on("error", () => resolve(false));
976
+ sock.on("timeout", () => {
977
+ sock.destroy();
978
+ resolve(false);
979
+ });
980
+ });
981
+ }
982
+
983
+ function findSerenaProjectRoot(): string {
984
+ // Walk up from cwd looking for .serena/project.yml
985
+ let dir = pathResolve(process.cwd());
986
+ while (dir !== dirname(dir)) {
987
+ if (existsSync(pathJoin(dir, ".serena", "project.yml"))) return dir;
988
+ dir = dirname(dir);
989
+ }
990
+ // Fallback: walk up from this file's directory
991
+ // (compiled JS lives in packages/tools/dist/executors/)
992
+ // __dirname is available since the build target is CJS
993
+ dir = typeof __dirname === "string" ? pathResolve(__dirname) : pathResolve(".");
994
+ while (dir !== dirname(dir)) {
995
+ if (existsSync(pathJoin(dir, ".serena", "project.yml"))) return dir;
996
+ dir = dirname(dir);
997
+ }
998
+ return process.cwd();
999
+ }
1000
+
1001
+ let cachedSerenaBin: string | null | undefined;
1002
+
1003
+ function resolveSerenaBin(): string | null {
1004
+ if (cachedSerenaBin !== undefined) return cachedSerenaBin as string | null;
1005
+
1006
+ // Find the serena binary from uv's cache directory.
1007
+ // We avoid `uvx --from git+... which serena` because it triggers a blocking
1008
+ // git fetch that hangs inside a detached spawn context.
1009
+ const cacheBase = pathJoin(process.env.HOME ?? "/tmp", ".cache", "uv", "archive-v0");
1010
+ try {
1011
+ const entries = readdirSync(cacheBase)
1012
+ .map((d: string) => pathJoin(cacheBase, d, "bin", "serena"))
1013
+ .filter((p: string) => existsSync(p))
1014
+ .sort((a: string, b: string) => statSync(b).mtimeMs - statSync(a).mtimeMs);
1015
+ cachedSerenaBin = entries.length > 0 ? entries[0] : null;
1016
+ } catch {
1017
+ cachedSerenaBin = null;
1018
+ }
1019
+
1020
+ return cachedSerenaBin ?? null;
1021
+ }
1022
+
1023
+ function spawnSerenaServer(): void {
1024
+ const projectRoot = findSerenaProjectRoot();
1025
+ const serenaBin = resolveSerenaBin();
1026
+ if (!serenaBin) return;
1027
+
1028
+ // Spawn the cached Python binary directly with stdio:'ignore' + detached.
1029
+ // Using 'uvx --from git+...' does NOT work because uvx triggers a blocking
1030
+ // git fetch that hangs/dies with closed file descriptors.
1031
+ const child = cpSpawn(serenaBin, ["start-project-server", "--port", String(SERENA_PORT)], {
1032
+ cwd: projectRoot,
1033
+ detached: true,
1034
+ stdio: "ignore",
1035
+ env: { ...process.env },
1036
+ });
1037
+ child.unref();
1038
+ }
1039
+
1040
+ async function ensureSerenaServer(): Promise<boolean> {
1041
+ if (await isSerenaAlive()) return true;
1042
+
1043
+ // Deduplicate concurrent start attempts
1044
+ if (serenaStarting) return serenaStarting;
1045
+
1046
+ serenaStarting = (async () => {
1047
+ spawnSerenaServer();
1048
+
1049
+ // Poll for readiness (serena can take a few seconds to initialize)
1050
+ const deadline = Date.now() + 30_000;
1051
+ const interval = 500;
1052
+ while (Date.now() < deadline) {
1053
+ await new Promise((r) => setTimeout(r, interval));
1054
+ if (await isSerenaAlive()) {
1055
+ serenaStarting = null;
1056
+ return true;
1057
+ }
1058
+ }
1059
+ serenaStarting = null;
1060
+ return false;
1061
+ })();
1062
+
1063
+ return serenaStarting;
1064
+ }
1065
+
1066
+ export async function executeSerena(input: SerenaInput, ctx: ToolContext): Promise<ToolResult> {
1067
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
1068
+
1069
+ const toolName = SERENA_TOOL_MAP[input.action];
1070
+ if (!toolName) return fail(`Unknown serena action: ${input.action}`);
1071
+
1072
+ const isMutation = ["replace_body", "insert_after", "insert_before", "rename"].includes(
1073
+ input.action,
1074
+ );
1075
+ if (isMutation && ctx.confirm) {
1076
+ const desc =
1077
+ input.action === "rename"
1078
+ ? `Rename "${input.name_path}" to "${input.new_name}"?`
1079
+ : `${input.action} on "${input.name_path}"?`;
1080
+ const ok = await ctx.confirm(desc);
1081
+ if (!ok) return fail("Cancelled by user");
1082
+ }
1083
+
1084
+ // Auto-start the Serena project server if not running
1085
+ const alive = await ensureSerenaServer();
1086
+ if (!alive) {
1087
+ return fail(
1088
+ "Failed to auto-start Serena project server after 30s. " +
1089
+ "Check logs or start manually:\n" +
1090
+ `uvx --from "git+https://github.com/oraios/serena" serena start-project-server --port ${SERENA_PORT}`,
1091
+ );
1092
+ }
1093
+
1094
+ const params: Record<string, unknown> = { ...input.extra_args };
1095
+ if (input.name_path) {
1096
+ if (input.action === "find_symbol") {
1097
+ params.name_path_pattern = input.name_path;
1098
+ } else {
1099
+ params.name_path = input.name_path;
1100
+ }
1101
+ }
1102
+ if (input.relative_path) params.relative_path = input.relative_path;
1103
+ if (input.include_body != null) params.include_body = input.include_body;
1104
+ if (input.include_info != null) params.include_info = input.include_info;
1105
+ if (input.depth != null) params.depth = input.depth;
1106
+ if (input.body) params.body = input.body;
1107
+ if (input.new_name) params.new_name = input.new_name;
1108
+ if (input.pattern) params.substring_pattern = input.pattern;
1109
+ if (input.context_before != null) params.context_lines_before = input.context_before;
1110
+ if (input.context_after != null) params.context_lines_after = input.context_after;
1111
+ if (input.paths_include) params.paths_include_glob = input.paths_include;
1112
+ if (input.paths_exclude) params.paths_exclude_glob = input.paths_exclude;
1113
+
1114
+ try {
1115
+ const body = JSON.stringify({
1116
+ project_name: SERENA_PROJECT,
1117
+ tool_name: toolName,
1118
+ tool_params_json: JSON.stringify(params),
1119
+ });
1120
+ const response = await fetch(`${SERENA_BASE}/query_project`, {
1121
+ method: "POST",
1122
+ headers: { "Content-Type": "application/json" },
1123
+ body,
1124
+ signal: ctx.abortSignal,
1125
+ });
1126
+ if (!response.ok) {
1127
+ const text = await response.text();
1128
+ return fail(`serena ${input.action}: HTTP ${response.status} — ${text.slice(0, 200)}`);
1129
+ }
1130
+ const text = await response.text();
1131
+ try {
1132
+ return success(`serena ${input.action} completed`, JSON.parse(text));
1133
+ } catch {
1134
+ return success(`serena ${input.action} completed`, { raw: text });
1135
+ }
1136
+ } catch (err: unknown) {
1137
+ const e = asExecError(err);
1138
+ return fail(`serena ${input.action} failed: ${e.message}`);
1139
+ }
1140
+ }
1141
+
1142
+ // ---------------------------------------------------------------------------
1143
+ // 8. fff — native CLI (fff-cli binary, zero MCP)
1144
+ // ---------------------------------------------------------------------------
1145
+
1146
+ export async function executeFff(input: FffInput, ctx: ToolContext): Promise<ToolResult> {
1147
+ if (ctx.abortSignal?.aborted) return fail("Operation cancelled");
1148
+ if (!(await hasBinary("fff-cli")))
1149
+ return fail(
1150
+ "fff-cli not installed. Build: cd vendor/fff-cli && cargo build --release && cp target/release/fff-cli ~/.local/bin/",
1151
+ );
1152
+
1153
+ const args: string[] = [input.action];
1154
+
1155
+ // Query or patterns. Native fff-cli supports positional query terms; constraints are
1156
+ // appended as additional terms for grep/find_files and patterns for multi_grep.
1157
+ if (input.action === "multi_grep" && input.patterns?.length) {
1158
+ args.push(...input.patterns);
1159
+ if (input.constraints) args.push(input.constraints);
1160
+ } else {
1161
+ if (input.query) args.push(input.query);
1162
+ if (input.constraints) args.push(input.constraints);
1163
+ }
1164
+
1165
+ // Path
1166
+ args.push("--path", input.path ?? ctx.workingDir);
1167
+
1168
+ try {
1169
+ const { stdout } = await shellExec("fff-cli", args, {
1170
+ cwd: ctx.workingDir,
1171
+ signal: ctx.abortSignal,
1172
+ timeout: 30_000,
1173
+ });
1174
+ return success(`fff ${input.action} completed`, JSON.parse(stdout));
1175
+ } catch (err: unknown) {
1176
+ const e = asExecError(err);
1177
+ return fail(`fff ${input.action} failed: ${e.stderr || e.message}`);
1178
+ }
1179
+ }