@causyne/agent 1.20.91 → 1.20.94

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 (46) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +116 -26
  3. package/src/agentLoop.ts +121 -26
  4. package/src/contextManager.js +2 -0
  5. package/src/decideTools.js +9 -0
  6. package/src/decideTools.ts +9 -0
  7. package/src/decisionPolicy.js +119 -1
  8. package/src/decisionPolicy.ts +129 -1
  9. package/src/historyPruner.js +16 -1
  10. package/src/historyPruner.ts +13 -1
  11. package/src/sandbox.js +33 -7
  12. package/src/skills/skillResourceSafety.js +70 -0
  13. package/src/skills/skillResourceSafety.ts +77 -0
  14. package/src/smartToolsUse.js +28 -11
  15. package/src/smartToolsUse.ts +34 -11
  16. package/src/taskShape.js +28 -13
  17. package/src/taskShape.ts +31 -12
  18. package/src/tools/codeSearcher.js +349 -210
  19. package/src/tools/codeSearcher.ts +408 -0
  20. package/src/tools/codebaseSearch.js +182 -68
  21. package/src/tools/codebaseSearch.ts +221 -0
  22. package/src/tools/deferredMcpSearch.js +94 -40
  23. package/src/tools/deferredMcpSearch.ts +89 -30
  24. package/src/tools/fsFind.js +180 -115
  25. package/src/tools/fsFind.ts +228 -0
  26. package/src/tools/fsList.js +149 -69
  27. package/src/tools/fsList.ts +224 -0
  28. package/src/tools/fsSearch.js +192 -189
  29. package/src/tools/fsSearch.ts +241 -0
  30. package/src/tools/readNativeSkill.js +34 -42
  31. package/src/tools/readNativeSkill.ts +38 -36
  32. package/src/tools/searchRelevance.js +70 -0
  33. package/src/tools/searchRelevance.ts +72 -0
  34. package/src/tools/toolSelfRepair.js +56 -20
  35. package/src/tools/toolSelfRepair.ts +58 -19
  36. package/src/tools/walkerSafety.js +445 -0
  37. package/src/tools/walkerSafety.ts +516 -0
  38. package/src/tui/composerGeometry.js +45 -0
  39. package/src/tui/composerGeometry.ts +80 -0
  40. package/src/tui/homeView.js +10 -6
  41. package/src/tui/homeView.ts +10 -6
  42. package/src/tui/lineEditor.js +8 -0
  43. package/src/tui/prompt.js +9 -4
  44. package/src/userSkills.js +183 -203
  45. package/src/userSkills.ts +301 -0
  46. package/src/userSkills.d.ts +0 -26
@@ -1,230 +1,369 @@
1
- import fs from 'fs/promises';
2
- import fsSync from 'fs';
3
- import path from 'path';
4
- import os from 'os';
5
- import { execFile } from 'child_process';
6
- import { promisify } from 'util';
7
- import { causyneHome } from '../utils/paths.js';
8
-
1
+ import { execFile } from 'node:child_process';
2
+ import fsSync from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { DEFAULT_TIMEOUT_MS, MAX_FILE_BYTES, buildHomeGlobExcludes, buildTopLevelHomeExcludes, checkSearchScope, compileSafeSearchRegex, createTraversalGuard, isSafeSymlinkTarget, looksBinaryFile, resolveSearchRoot, shouldExcludeChild, validateRegexSafety } from './walkerSafety.js';
9
7
  const execFileAsync = promisify(execFile);
10
-
11
- // Helper: Check system ripgrep binary availability
8
+ const MAX_MATCHES = 100;
9
+ const RG_MAX_PER_FILE = 50;
12
10
  function getRipgrepBinary() {
13
- const isWin = process.platform === 'win32';
14
- const candidates = isWin
15
- ? ['C:\\Program Files\\ripgrep\\rg.exe', 'rg.exe']
16
- : ['/opt/homebrew/bin/rg', '/usr/local/bin/rg', '/usr/bin/rg', 'rg'];
17
-
18
- for (const bin of candidates) {
19
- try {
20
- if (fsSync.existsSync(bin)) return bin;
21
- } catch (e) {}
22
- }
23
- return null;
11
+ const isWin = process.platform === 'win32';
12
+ const fixedCandidates = isWin
13
+ ? ['C:\\Program Files\\ripgrep\\rg.exe']
14
+ : ['/opt/homebrew/bin/rg', '/usr/local/bin/rg', '/usr/bin/rg'];
15
+ for (const candidate of fixedCandidates) {
16
+ try {
17
+ if (fsSync.existsSync(candidate))
18
+ return candidate;
19
+ }
20
+ catch {
21
+ // Ignore permission errors probing candidate paths.
22
+ }
23
+ }
24
+ const pathEnv = process.env.PATH || '';
25
+ const exeName = isWin ? 'rg.exe' : 'rg';
26
+ for (const dir of pathEnv.split(path.delimiter)) {
27
+ if (!dir)
28
+ continue;
29
+ const candidate = path.join(dir, exeName);
30
+ try {
31
+ if (fsSync.existsSync(candidate))
32
+ return candidate;
33
+ }
34
+ catch {
35
+ // Ignore unreadable PATH directory entries.
36
+ }
37
+ }
38
+ return null;
24
39
  }
25
-
26
- // Helper: V5 Cortex SQLite Cache (non-blocking schema init)
27
- function getCortexDb() {
28
- try {
29
- const dbPath = path.join(causyneHome(), 'cortex.db');
30
- if (!fsSync.existsSync(path.dirname(dbPath))) {
31
- fsSync.mkdirSync(path.dirname(dbPath), { recursive: true });
40
+ function globToSuffix(filePattern) {
41
+ if (!filePattern || filePattern === '*')
42
+ return null;
43
+ if (filePattern.startsWith('*.') && !filePattern.slice(2).includes('*')) {
44
+ return filePattern.slice(1).toLowerCase();
32
45
  }
33
- // Lazy check if better-sqlite3 is available in dependencies
34
- const Database = require('better-sqlite3');
35
- const db = new Database(dbPath, { timeout: 2000 });
36
- db.exec(`
37
- CREATE TABLE IF NOT EXISTS code_search_cache (
38
- id INTEGER PRIMARY KEY AUTOINCREMENT,
39
- query TEXT,
40
- search_path TEXT,
41
- results_json TEXT,
42
- timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
43
- );
44
- CREATE INDEX IF NOT EXISTS idx_code_search_query ON code_search_cache(query, search_path);
45
- `);
46
- return db;
47
- } catch (e) {
48
46
  return null;
49
- }
50
47
  }
51
-
52
- export const codeSearcher = {
53
- schema: {
54
- name: 'code.search_ripgrep',
55
- description: 'Blazing fast regex, string, and AST symbol search across entire codebases using dual-engine ripgrep + fast Node stream and V5 Cortex SQLite caching. Surpasses standard CLI glob search.',
56
- parameters: {
57
- type: 'object',
58
- properties: {
59
- query: { type: 'string', description: 'The exact string, symbol, or regular expression pattern to look for across files.' },
60
- searchPath: { type: 'string', description: 'Absolute root directory or file path to search. Defaults to current working directory.' },
61
- isRegex: { type: 'boolean', description: 'If true, treats query as a regular expression pattern. If false, treats as literal string.' },
62
- caseInsensitive: { type: 'boolean', description: 'If true, performs case-insensitive search (default true).' },
63
- filePattern: { type: 'string', description: 'Optional glob filter (e.g. "*.js", "*.py", "*.kt", "*.ts") to restrict search to specific file extensions.' },
64
- astMode: { type: 'boolean', description: 'If true, filters results specifically for AST symbol definitions (classes, functions, interfaces, structs, defs).' }
65
- },
66
- required: ['query']
48
+ function escapeLiteralRegex(text) {
49
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
50
+ }
51
+ function parseRgLine(line) {
52
+ let idx = line.indexOf(':');
53
+ // Skip Windows drive letter prefix like C:\foo:12:bar
54
+ if (idx === 1 && /^[a-zA-Z]$/.test(line[0] ?? '') && (line[2] === '\\' || line[2] === '/')) {
55
+ idx = line.indexOf(':', 2);
67
56
  }
68
- },
69
-
70
- async execute(args) {
71
- try {
72
- const query = args.query;
73
- if (!query) return { success: false, error: 'Query parameter is required.' };
74
-
75
- const targetDir = (args.searchPath || process.cwd()).replace(/^~\//, os.homedir() + '/');
76
- const isRegex = args.isRegex === true;
77
- const caseInsensitive = args.caseInsensitive !== false; // default true
78
- const filePattern = args.filePattern || '*';
79
- const astMode = args.astMode === true;
80
-
81
- // Check V5 Cortex SQLite Cache first
82
- let db = null;
83
- try {
84
- db = getCortexDb();
85
- if (db) {
86
- const cacheKey = `${query}_${isRegex}_${caseInsensitive}_${filePattern}_${astMode}`;
87
- const row = db.prepare('SELECT results_json FROM code_search_cache WHERE query = ? AND search_path = ? AND timestamp >= datetime("now", "-10 minutes") LIMIT 1').get(cacheKey, targetDir);
88
- if (row && row.results_json) {
89
- const cachedResults = JSON.parse(row.results_json);
57
+ while (idx > 0) {
58
+ const nextColon = line.indexOf(':', idx + 1);
59
+ if (nextColon === -1)
60
+ return null;
61
+ const lineNumStr = line.slice(idx + 1, nextColon);
62
+ if (lineNumStr.length > 0 && /^\d+$/.test(lineNumStr)) {
90
63
  return {
91
- success: true,
92
- output: JSON.stringify({
93
- engine: 'Cortex Neural Cache (0ms)',
94
- query: query,
95
- total_matches: cachedResults.length,
96
- matches: cachedResults
97
- }, null, 2)
64
+ File: line.slice(0, idx),
65
+ LineNumber: Number.parseInt(lineNumStr, 10) || 0,
66
+ LineContent: line.slice(nextColon + 1).trim().slice(0, 300)
98
67
  };
99
- }
100
68
  }
101
- } catch (cacheErr) {}
102
-
103
- const matches = [];
104
- const MAX_MATCHES = 100;
105
- const rgBin = getRipgrepBinary();
106
-
107
- // Dual-Engine 1: Ripgrep Binary
108
- if (rgBin) {
109
- const rgArgs = ['-n', '--no-heading', `--max-count=${MAX_MATCHES}`];
110
- if (caseInsensitive) rgArgs.push('-i');
111
- if (!isRegex) rgArgs.push('-F');
112
- if (filePattern && filePattern !== '*') rgArgs.push('-g', filePattern);
113
-
114
- // If AST mode, build an AST regex around the symbol
115
- let finalQuery = query;
116
- if (astMode && !isRegex) {
117
- rgArgs.push('-e');
118
- finalQuery = `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`;
119
- } else {
120
- rgArgs.push('-e', finalQuery);
69
+ idx = nextColon;
70
+ }
71
+ return null;
72
+ }
73
+ function isInvalidGlob(filePattern) {
74
+ return (filePattern.startsWith('-') ||
75
+ /[\x00-\x1f\r\n]/.test(filePattern));
76
+ }
77
+ export const codeSearcher = {
78
+ schema: {
79
+ name: 'code.search_ripgrep',
80
+ description: 'Fast regex, literal string, and symbol search across codebases using ripgrep with bounded async Node fallback.',
81
+ parameters: {
82
+ type: 'object',
83
+ properties: {
84
+ query: {
85
+ type: 'string',
86
+ description: 'The exact string, symbol, or regular expression pattern to look for across files.'
87
+ },
88
+ searchPath: {
89
+ type: 'string',
90
+ description: 'Directory or file path to search. Defaults to workspace root.'
91
+ },
92
+ isRegex: {
93
+ type: 'boolean',
94
+ description: 'If true, treats query as a regular expression pattern. If false, treats as literal string.'
95
+ },
96
+ caseInsensitive: {
97
+ type: 'boolean',
98
+ description: 'If true, performs case-insensitive search (default true).'
99
+ },
100
+ filePattern: {
101
+ type: 'string',
102
+ description: 'Optional glob filter (e.g. "*.js", "*.py", "*.kt", "*.ts") to restrict file extensions.'
103
+ },
104
+ astMode: {
105
+ type: 'boolean',
106
+ description: 'If true, filters results specifically for symbol definitions (classes, functions, interfaces, structs, defs).'
107
+ }
108
+ },
109
+ required: ['query']
121
110
  }
122
- rgArgs.push(targetDir);
123
-
111
+ },
112
+ async execute(args, context) {
124
113
  try {
125
- const { stdout } = await execFileAsync(rgBin, rgArgs, { maxBuffer: 10 * 1024 * 1024 });
126
- const lines = stdout.split('\n').filter(Boolean);
127
- for (const line of lines) {
128
- if (matches.length >= MAX_MATCHES) break;
129
- const parts = line.split(':');
130
- if (parts.length >= 3) {
131
- const file = parts[0];
132
- const lineNo = parseInt(parts[1], 10) || 0;
133
- const content = parts.slice(2).join(':').trim();
134
- matches.push({ File: file, LineNumber: lineNo, LineContent: content });
114
+ if (!args || typeof args.query !== 'string' || args.query.length === 0) {
115
+ return { success: false, error: 'Query parameter is required.' };
135
116
  }
136
- }
137
- } catch (rgErr) {
138
- // If exit code is 1, ripgrep simply found no matches. Otherwise fall through to Node stream.
139
- if (rgErr.code !== 1 && rgErr.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
140
- // Fallback to async Node stream
141
- }
142
- }
143
- }
144
-
145
- // Dual-Engine 2: Fast Asynchronous Node Stream Fallback (if rg returned empty or not installed)
146
- if (matches.length === 0 && (!rgBin || !fsSync.existsSync(rgBin))) {
147
- const EXCLUDE_DIRS = new Set(['node_modules', '.git', '.gradle', 'build', 'dist', '.idea', '.causyne_trash']);
148
-
149
- let patternRegExp;
150
- try {
151
- let pat = isRegex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
152
- if (astMode && !isRegex) {
153
- pat = `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${pat}`;
154
- }
155
- patternRegExp = new RegExp(pat, caseInsensitive ? 'i' : '');
156
- } catch (regErr) {
157
- return { success: false, error: `Invalid regex pattern: ${regErr.message}` };
158
- }
159
-
160
- const extFilter = (filePattern && filePattern !== '*' && filePattern.startsWith('*.'))
161
- ? filePattern.slice(1).toLowerCase()
162
- : null;
163
-
164
- async function walkSearch(dir) {
165
- if (matches.length >= MAX_MATCHES) return;
166
- let dirents;
167
- try {
168
- dirents = await fs.readdir(dir, { withFileTypes: true });
169
- } catch (e) {
170
- return;
171
- }
172
-
173
- const promises = [];
174
- for (const dirent of dirents) {
175
- if (matches.length >= MAX_MATCHES) break;
176
- if (dirent.isDirectory()) {
177
- if (!EXCLUDE_DIRS.has(dirent.name)) {
178
- promises.push(walkSearch(path.join(dir, dirent.name)));
179
- }
180
- } else if (dirent.isFile()) {
181
- if (extFilter && !dirent.name.toLowerCase().endsWith(extFilter)) continue;
182
-
183
- promises.push(
184
- fs.readFile(path.join(dir, dirent.name), 'utf8')
185
- .then(content => {
117
+ const query = args.query;
118
+ const isRegex = args.isRegex === true;
119
+ const caseInsensitive = args.caseInsensitive !== false;
120
+ const filePattern = typeof args.filePattern === 'string' ? args.filePattern.trim() : '*';
121
+ const astMode = args.astMode === true;
122
+ if (filePattern && filePattern !== '*' && isInvalidGlob(filePattern)) {
123
+ return { success: false, error: `Invalid filePattern glob: ${filePattern}` };
124
+ }
125
+ if (isRegex) {
126
+ const unsafeReason = validateRegexSafety(query);
127
+ if (unsafeReason) {
128
+ return { success: false, error: unsafeReason };
129
+ }
130
+ }
131
+ const targetDir = resolveSearchRoot(args.searchPath, context);
132
+ const scope = checkSearchScope(targetDir, context);
133
+ if (!scope.allowed || !scope.realPath) {
134
+ return { success: false, error: scope.error || `Search path not allowed: ${targetDir}` };
135
+ }
136
+ const realTargetDir = scope.realPath;
137
+ let targetStat;
138
+ try {
139
+ targetStat = await fs.stat(realTargetDir);
140
+ }
141
+ catch {
142
+ return { success: false, error: `Search path does not exist: ${targetDir}` };
143
+ }
144
+ const matches = [];
145
+ const rgBin = getRipgrepBinary();
146
+ let engineLabel = rgBin ? `Ripgrep Binary (${rgBin})` : 'Node Async Stream Engine';
147
+ let useNodeFallback = !rgBin;
148
+ let stoppedNotice = '';
149
+ if (rgBin) {
150
+ const rgArgs = [
151
+ '-n',
152
+ '--no-heading',
153
+ '--with-filename',
154
+ `--max-count=${RG_MAX_PER_FILE}`,
155
+ `--max-filesize=${MAX_FILE_BYTES}`
156
+ ];
157
+ if (caseInsensitive)
158
+ rgArgs.push('-i');
159
+ if (!isRegex && !astMode)
160
+ rgArgs.push('-F');
161
+ if (filePattern && filePattern !== '*')
162
+ rgArgs.push('-g', filePattern);
163
+ for (const glob of buildHomeGlobExcludes()) {
164
+ rgArgs.push('-g', glob);
165
+ }
166
+ for (const glob of buildTopLevelHomeExcludes(realTargetDir)) {
167
+ rgArgs.push('-g', glob);
168
+ }
169
+ const effectiveQuery = astMode && !isRegex
170
+ ? `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${escapeLiteralRegex(query)}`
171
+ : query;
172
+ rgArgs.push('-e', effectiveQuery, '--', realTargetDir);
173
+ try {
174
+ const { stdout } = await execFileAsync(rgBin, rgArgs, {
175
+ maxBuffer: 10 * 1024 * 1024,
176
+ timeout: DEFAULT_TIMEOUT_MS,
177
+ signal: context?.signal
178
+ });
179
+ for (const line of stdout.split('\n')) {
180
+ if (!line)
181
+ continue;
182
+ if (matches.length >= MAX_MATCHES)
183
+ break;
184
+ const parsed = parseRgLine(line);
185
+ if (parsed)
186
+ matches.push(parsed);
187
+ }
188
+ }
189
+ catch (rgErr) {
190
+ if (context?.signal?.aborted) {
191
+ return { success: false, aborted: true, error: 'Code search aborted.' };
192
+ }
193
+ const errObj = rgErr;
194
+ if (typeof errObj.stdout === 'string' && errObj.stdout.length > 0) {
195
+ for (const line of errObj.stdout.split('\n')) {
196
+ if (!line)
197
+ continue;
198
+ if (matches.length >= MAX_MATCHES)
199
+ break;
200
+ const parsed = parseRgLine(line);
201
+ if (parsed)
202
+ matches.push(parsed);
203
+ }
204
+ }
205
+ if (errObj.killed) {
206
+ stoppedNotice = `stopped after ${DEFAULT_TIMEOUT_MS}ms budget`;
207
+ }
208
+ else if (errObj.code === 1) {
209
+ // Exit code 1 means zero matches found.
210
+ }
211
+ else if (errObj.code === 2) {
212
+ const stderr = String(errObj.stderr || '').trim();
213
+ if (/regex parse error|error parsing regex/i.test(stderr)) {
214
+ return { success: false, error: `Invalid regex pattern: ${stderr}` };
215
+ }
216
+ useNodeFallback = true;
217
+ }
218
+ else if (errObj.code === 'ENOENT' || errObj.code === 'EACCES') {
219
+ useNodeFallback = true;
220
+ }
221
+ else if (matches.length === 0) {
222
+ useNodeFallback = true;
223
+ }
224
+ }
225
+ }
226
+ if (useNodeFallback && matches.length === 0) {
227
+ engineLabel = 'Node Async Stream Engine';
228
+ let regex;
229
+ if (astMode && !isRegex) {
230
+ const astPat = `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${escapeLiteralRegex(query)}`;
231
+ regex = new RegExp(astPat, caseInsensitive ? 'i' : '');
232
+ }
233
+ else {
234
+ const compiled = compileSafeSearchRegex(query, { isRegex, caseInsensitive });
235
+ if (!compiled.regex) {
236
+ return { success: false, error: compiled.error || 'Invalid regex pattern.' };
237
+ }
238
+ regex = compiled.regex;
239
+ }
240
+ const extFilter = globToSuffix(filePattern);
241
+ const guard = createTraversalGuard({ signal: context?.signal });
242
+ const seen = new Set();
243
+ const scanFile = async (filePath) => {
244
+ if (matches.length >= MAX_MATCHES || guard.checkStopped())
245
+ return;
246
+ if (extFilter && !filePath.toLowerCase().endsWith(extFilter))
247
+ return;
248
+ if (!guard.countFile())
249
+ return;
250
+ let fileStat;
251
+ try {
252
+ fileStat = await fs.stat(filePath);
253
+ }
254
+ catch {
255
+ return;
256
+ }
257
+ if (fileStat.size > MAX_FILE_BYTES)
258
+ return;
259
+ if (await looksBinaryFile(filePath))
260
+ return;
261
+ let content;
262
+ try {
263
+ content = await fs.readFile(filePath, 'utf8');
264
+ }
265
+ catch {
266
+ return;
267
+ }
186
268
  const lines = content.split('\n');
187
269
  for (let i = 0; i < lines.length; i++) {
188
- if (matches.length >= MAX_MATCHES) break;
189
- if (patternRegExp.test(lines[i])) {
190
- matches.push({
191
- File: path.join(dir, dirent.name),
192
- LineNumber: i + 1,
193
- LineContent: lines[i].trim()
194
- });
195
- }
270
+ if (matches.length >= MAX_MATCHES || guard.checkStopped())
271
+ break;
272
+ const line = lines[i];
273
+ if (regex.test(line)) {
274
+ matches.push({
275
+ File: filePath,
276
+ LineNumber: i + 1,
277
+ LineContent: line.trim().slice(0, 300)
278
+ });
279
+ }
196
280
  }
197
- })
198
- .catch(() => {}) // Ignore binary/unreadable files
199
- );
281
+ };
282
+ if (targetStat.isFile()) {
283
+ await scanFile(realTargetDir);
284
+ }
285
+ else {
286
+ const queue = [
287
+ { dir: realTargetDir, real: realTargetDir, depth: 0 }
288
+ ];
289
+ while (queue.length > 0 && matches.length < MAX_MATCHES) {
290
+ if (guard.checkStopped())
291
+ break;
292
+ const current = queue.shift();
293
+ if (seen.has(current.real))
294
+ continue;
295
+ if (!guard.enterDir(current.depth))
296
+ continue;
297
+ seen.add(current.real);
298
+ let dirents;
299
+ try {
300
+ dirents = await fs.readdir(current.dir, { withFileTypes: true });
301
+ }
302
+ catch {
303
+ continue;
304
+ }
305
+ for (const dirent of dirents) {
306
+ if (matches.length >= MAX_MATCHES || guard.checkStopped())
307
+ break;
308
+ if (shouldExcludeChild(current.real, dirent.name))
309
+ continue;
310
+ const full = path.join(current.dir, dirent.name);
311
+ if (dirent.isDirectory()) {
312
+ try {
313
+ const childReal = await fs.realpath(full);
314
+ if (isSafeSymlinkTarget(childReal, realTargetDir, context) && !seen.has(childReal)) {
315
+ queue.push({ dir: full, real: childReal, depth: current.depth + 1 });
316
+ }
317
+ }
318
+ catch {
319
+ // Ignore unreadable subdirectories.
320
+ }
321
+ }
322
+ else if (dirent.isFile()) {
323
+ await scanFile(full);
324
+ }
325
+ else if (dirent.isSymbolicLink()) {
326
+ try {
327
+ const linkReal = await fs.realpath(full);
328
+ if (!isSafeSymlinkTarget(linkReal, realTargetDir, context))
329
+ continue;
330
+ const linkStat = await fs.stat(linkReal);
331
+ if (linkStat.isDirectory()) {
332
+ if (!seen.has(linkReal)) {
333
+ queue.push({ dir: linkReal, real: linkReal, depth: current.depth + 1 });
334
+ }
335
+ }
336
+ else if (linkStat.isFile()) {
337
+ await scanFile(full);
338
+ }
339
+ }
340
+ catch {
341
+ // Ignore broken symlinks.
342
+ }
343
+ }
344
+ }
345
+ }
346
+ }
347
+ if (guard.stopReason === 'aborted') {
348
+ return { success: false, aborted: true, error: 'Code search aborted.' };
349
+ }
350
+ if (guard.stopReason) {
351
+ stoppedNotice = guard.stopNotice();
352
+ }
200
353
  }
201
- }
202
- await Promise.all(promises);
354
+ return {
355
+ success: true,
356
+ output: JSON.stringify({
357
+ engine: engineLabel,
358
+ query,
359
+ total_matches: matches.length,
360
+ ...(stoppedNotice ? { stopped_reason: stoppedNotice } : {}),
361
+ matches: matches.length > 0 ? matches : 'No matches found in target codebase.'
362
+ }, null, 2)
363
+ };
364
+ }
365
+ catch (error) {
366
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
203
367
  }
204
-
205
- await walkSearch(targetDir);
206
- }
207
-
208
- // Cache matches in Cortex SQLite if db active
209
- if (db && matches.length > 0) {
210
- try {
211
- const cacheKey = `${query}_${isRegex}_${caseInsensitive}_${filePattern}_${astMode}`;
212
- db.prepare('INSERT INTO code_search_cache (query, search_path, results_json) VALUES (?, ?, ?)')
213
- .run(cacheKey, targetDir, JSON.stringify(matches));
214
- } catch (cacheStoreErr) {}
215
- }
216
-
217
- return {
218
- success: true,
219
- output: JSON.stringify({
220
- engine: rgBin ? `Ripgrep Binary (${rgBin})` : 'Node Async Stream Engine',
221
- query: query,
222
- total_matches: matches.length,
223
- matches: matches.length > 0 ? matches : "No matches found in target codebase."
224
- }, null, 2)
225
- };
226
- } catch (e) {
227
- return { success: false, error: e.message };
228
368
  }
229
- }
230
369
  };