@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.
- package/package.json +1 -1
- package/src/agentLoop.js +116 -26
- package/src/agentLoop.ts +121 -26
- package/src/contextManager.js +2 -0
- package/src/decideTools.js +9 -0
- package/src/decideTools.ts +9 -0
- package/src/decisionPolicy.js +119 -1
- package/src/decisionPolicy.ts +129 -1
- package/src/historyPruner.js +16 -1
- package/src/historyPruner.ts +13 -1
- package/src/sandbox.js +33 -7
- package/src/skills/skillResourceSafety.js +70 -0
- package/src/skills/skillResourceSafety.ts +77 -0
- package/src/smartToolsUse.js +28 -11
- package/src/smartToolsUse.ts +34 -11
- package/src/taskShape.js +28 -13
- package/src/taskShape.ts +31 -12
- package/src/tools/codeSearcher.js +349 -210
- package/src/tools/codeSearcher.ts +408 -0
- package/src/tools/codebaseSearch.js +182 -68
- package/src/tools/codebaseSearch.ts +221 -0
- package/src/tools/deferredMcpSearch.js +94 -40
- package/src/tools/deferredMcpSearch.ts +89 -30
- package/src/tools/fsFind.js +180 -115
- package/src/tools/fsFind.ts +228 -0
- package/src/tools/fsList.js +149 -69
- package/src/tools/fsList.ts +224 -0
- package/src/tools/fsSearch.js +192 -189
- package/src/tools/fsSearch.ts +241 -0
- package/src/tools/readNativeSkill.js +34 -42
- package/src/tools/readNativeSkill.ts +38 -36
- package/src/tools/searchRelevance.js +70 -0
- package/src/tools/searchRelevance.ts +72 -0
- package/src/tools/toolSelfRepair.js +56 -20
- package/src/tools/toolSelfRepair.ts +58 -19
- package/src/tools/walkerSafety.js +445 -0
- package/src/tools/walkerSafety.ts +516 -0
- package/src/tui/composerGeometry.js +45 -0
- package/src/tui/composerGeometry.ts +80 -0
- package/src/tui/homeView.js +10 -6
- package/src/tui/homeView.ts +10 -6
- package/src/tui/lineEditor.js +8 -0
- package/src/tui/prompt.js +9 -4
- package/src/userSkills.js +183 -203
- package/src/userSkills.ts +301 -0
- package/src/userSkills.d.ts +0 -26
|
@@ -1,230 +1,369 @@
|
|
|
1
|
-
import
|
|
2
|
-
import fsSync from 'fs';
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
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
|
-
|
|
8
|
+
const MAX_MATCHES = 100;
|
|
9
|
+
const RG_MAX_PER_FILE = 50;
|
|
12
10
|
function getRipgrepBinary() {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
-
|
|
123
|
-
|
|
111
|
+
},
|
|
112
|
+
async execute(args, context) {
|
|
124
113
|
try {
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
};
|