@kolivri/memoreal-mcp 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +9 -0
- package/.cursor-plugin/plugin.json +2 -2
- package/CLAUDE.md +29 -29
- package/README.md +188 -11
- package/agents/memoreal.md +25 -9
- package/agents/memoria.md +25 -9
- package/bin/memoreal-hook.mjs +483 -0
- package/bin/memoreal-ns +54 -4
- package/bin/memoreal-ns.cmd +2 -0
- package/bin/memoreal-ns.mjs +945 -0
- package/bin/memoria-ns +54 -5
- package/hooks/hooks.json +11 -11
- package/install.sh +565 -119
- package/manifest.json +1 -1
- package/opencode/memoreal-hooks.js +266 -381
- package/opencode/memoria-hooks.js +45 -10
- package/package.json +26 -1
- package/rules/memoreal.mdc +20 -4
- package/rules/memoria.mdc +6 -3
- package/server.json +2 -2
- package/skills/memoreal-connect/SKILL.md +178 -2
- package/skills/memoria-connect/SKILL.md +178 -2
- package/src/bootstrap.mjs +2850 -0
- package/src/config-store.mjs +1156 -93
- package/src/schemas.mjs +429 -1
- package/src/server.mjs +238 -23
- package/src/wizard.mjs +100 -6
- package/.actor/Dockerfile +0 -6
- package/.actor/actor.json +0 -15
- package/.actor/input_schema.json +0 -92
- package/Dockerfile +0 -5
- package/prd/001-rebrand-memoreal-mcp.md +0 -132
- package/prd/002-connect-oauth-wizard.md +0 -259
- package/test/apify-actor.test.mjs +0 -429
- package/test/config-store.test.mjs +0 -680
- package/test/connect-wizard.test.mjs +0 -936
- package/test/hooks-onboarding.test.mjs +0 -1039
- package/test/memoria-mcp.test.mjs +0 -376
- package/test/wizard-unit.test.mjs +0 -1272
|
@@ -0,0 +1,2850 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { resolveEffectiveApiKey, resolveEffectiveApiUrl } from './config-store.mjs';
|
|
6
|
+
import {
|
|
7
|
+
resolveProjectNamespaceInfo,
|
|
8
|
+
deriveNamespaceCrossOs,
|
|
9
|
+
MEMOREAL_CLIENT_VERSION,
|
|
10
|
+
} from '../bin/memoreal-ns.mjs';
|
|
11
|
+
|
|
12
|
+
export const PROJECT_MARKERS = [
|
|
13
|
+
'CLAUDE.md',
|
|
14
|
+
'AGENTS.md',
|
|
15
|
+
'README.md',
|
|
16
|
+
'package.json',
|
|
17
|
+
'tsconfig.json',
|
|
18
|
+
'jsconfig.json',
|
|
19
|
+
'Cargo.toml',
|
|
20
|
+
'pyproject.toml',
|
|
21
|
+
'setup.py',
|
|
22
|
+
'requirements.txt',
|
|
23
|
+
'go.mod',
|
|
24
|
+
'pom.xml',
|
|
25
|
+
'build.gradle',
|
|
26
|
+
'build.gradle.kts',
|
|
27
|
+
'composer.json',
|
|
28
|
+
'Gemfile',
|
|
29
|
+
'Package.swift',
|
|
30
|
+
'CMakeLists.txt',
|
|
31
|
+
'Makefile',
|
|
32
|
+
'mix.exs',
|
|
33
|
+
'pubspec.yaml',
|
|
34
|
+
'build.sbt',
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
export const CODE_INTEL_TOOLS = [
|
|
38
|
+
'find_file',
|
|
39
|
+
'find_references',
|
|
40
|
+
'impact',
|
|
41
|
+
'call_tree',
|
|
42
|
+
'navigate',
|
|
43
|
+
'get_hierarchy',
|
|
44
|
+
'implementors',
|
|
45
|
+
'dead_code',
|
|
46
|
+
'test_gaps',
|
|
47
|
+
'diff_risk',
|
|
48
|
+
'downstream_effects',
|
|
49
|
+
'root_cause',
|
|
50
|
+
'trace_provenance',
|
|
51
|
+
'explain_diff',
|
|
52
|
+
'explain_error',
|
|
53
|
+
'rename',
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
const CODE_EXTENSIONS = new Set([
|
|
57
|
+
// JavaScript / TypeScript
|
|
58
|
+
'.js',
|
|
59
|
+
'.mjs',
|
|
60
|
+
'.cjs',
|
|
61
|
+
'.jsx',
|
|
62
|
+
'.ts',
|
|
63
|
+
'.mts',
|
|
64
|
+
'.cts',
|
|
65
|
+
'.tsx',
|
|
66
|
+
// Python
|
|
67
|
+
'.py',
|
|
68
|
+
'.pyi',
|
|
69
|
+
// Rust / Go
|
|
70
|
+
'.rs',
|
|
71
|
+
'.go',
|
|
72
|
+
// JVM
|
|
73
|
+
'.java',
|
|
74
|
+
'.kt',
|
|
75
|
+
'.kts',
|
|
76
|
+
'.scala',
|
|
77
|
+
// .NET / C / C++ / Swift / Dart
|
|
78
|
+
'.cs',
|
|
79
|
+
'.c',
|
|
80
|
+
'.h',
|
|
81
|
+
'.cpp',
|
|
82
|
+
'.cc',
|
|
83
|
+
'.cxx',
|
|
84
|
+
'.hpp',
|
|
85
|
+
'.hh',
|
|
86
|
+
'.hxx',
|
|
87
|
+
'.swift',
|
|
88
|
+
'.dart',
|
|
89
|
+
// Web / Scripting
|
|
90
|
+
'.php',
|
|
91
|
+
'.rb',
|
|
92
|
+
'.ex',
|
|
93
|
+
'.exs',
|
|
94
|
+
'.lua',
|
|
95
|
+
'.sh',
|
|
96
|
+
'.bash',
|
|
97
|
+
'.zsh',
|
|
98
|
+
'.sql',
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
const SKIP_DIRS = new Set([
|
|
102
|
+
'node_modules',
|
|
103
|
+
'.git',
|
|
104
|
+
'dist',
|
|
105
|
+
'build',
|
|
106
|
+
'.worktrees',
|
|
107
|
+
'.claude',
|
|
108
|
+
'.opencode',
|
|
109
|
+
'.cursor',
|
|
110
|
+
'.vscode',
|
|
111
|
+
'.codex',
|
|
112
|
+
'.next',
|
|
113
|
+
'.turbo',
|
|
114
|
+
'coverage',
|
|
115
|
+
'target',
|
|
116
|
+
'vendor',
|
|
117
|
+
'venv',
|
|
118
|
+
'.venv',
|
|
119
|
+
'__pycache__',
|
|
120
|
+
'bin',
|
|
121
|
+
'obj',
|
|
122
|
+
'.gradle',
|
|
123
|
+
'.idea',
|
|
124
|
+
'Pods',
|
|
125
|
+
'_build',
|
|
126
|
+
'.dart_tool',
|
|
127
|
+
'out',
|
|
128
|
+
'.nuxt',
|
|
129
|
+
'.svelte-kit',
|
|
130
|
+
]);
|
|
131
|
+
|
|
132
|
+
const MAX_FILE_CHARS = 200_000;
|
|
133
|
+
const MAX_FILE_LINES = 5_000;
|
|
134
|
+
const MAX_LINE_CHARS = 2_000;
|
|
135
|
+
const IDENTIFIER_REGEX = /^(?:#?[\p{ID_Start}_$][\p{ID_Continue}$]*[?!]?)$/u;
|
|
136
|
+
|
|
137
|
+
function linearGlob(text, pattern) {
|
|
138
|
+
const tLen = text.length;
|
|
139
|
+
const pLen = pattern.length;
|
|
140
|
+
|
|
141
|
+
let tIdx = 0;
|
|
142
|
+
let pIdx = 0;
|
|
143
|
+
let starIdx = -1;
|
|
144
|
+
let matchIdx = 0;
|
|
145
|
+
|
|
146
|
+
while (tIdx < tLen) {
|
|
147
|
+
if (pIdx < pLen && (pattern[pIdx] === '?' || pattern[pIdx] === text[tIdx])) {
|
|
148
|
+
tIdx++;
|
|
149
|
+
pIdx++;
|
|
150
|
+
} else if (pIdx < pLen && pattern[pIdx] === '*') {
|
|
151
|
+
starIdx = pIdx;
|
|
152
|
+
matchIdx = tIdx;
|
|
153
|
+
pIdx++;
|
|
154
|
+
} else if (starIdx !== -1) {
|
|
155
|
+
pIdx = starIdx + 1;
|
|
156
|
+
matchIdx++;
|
|
157
|
+
tIdx = matchIdx;
|
|
158
|
+
} else {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
while (pIdx < pLen && pattern[pIdx] === '*') {
|
|
164
|
+
pIdx++;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return pIdx === pLen;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function wildcardMatch(text, rawPattern) {
|
|
171
|
+
if (typeof text !== 'string' || typeof rawPattern !== 'string') return false;
|
|
172
|
+
const normText = text.replace(/\\/g, '/');
|
|
173
|
+
let p = rawPattern.replace(/\\/g, '/');
|
|
174
|
+
if (p.length > 256) p = p.slice(0, 256);
|
|
175
|
+
|
|
176
|
+
p = p.replace(/\*{3,}/g, '**');
|
|
177
|
+
|
|
178
|
+
if (!p.includes('**/')) {
|
|
179
|
+
return linearGlob(normText, p.replace(/\*\*+/g, '*'));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const patterns = new Set();
|
|
183
|
+
patterns.add(p);
|
|
184
|
+
const zeroDir = p.replace(/^(\*\*\/?)+/, '').replace(/\/\*\*(\/|$)/g, '/');
|
|
185
|
+
patterns.add(zeroDir);
|
|
186
|
+
patterns.add(p.replace(/\*\*\//g, ''));
|
|
187
|
+
patterns.add(p.replace(/\*\*\//g, '*/'));
|
|
188
|
+
|
|
189
|
+
for (const pat of patterns) {
|
|
190
|
+
const collapsed = pat.replace(/\*\*+/g, '*');
|
|
191
|
+
if (linearGlob(normText, collapsed)) {
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function buildIdentifierRegex(symbol) {
|
|
200
|
+
const escaped = symbol.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
|
|
201
|
+
const pattern = `(?<![\\p{ID_Continue}$#])${escaped}(?![\\p{ID_Continue}$])`;
|
|
202
|
+
const testRe = new RegExp(pattern, 'u');
|
|
203
|
+
const replaceRe = new RegExp(pattern, 'gu');
|
|
204
|
+
return { testRe, replaceRe };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function boundContent(raw) {
|
|
208
|
+
if (typeof raw !== 'string') return '';
|
|
209
|
+
let content = raw;
|
|
210
|
+
if (content.length > MAX_FILE_CHARS) {
|
|
211
|
+
content = content.slice(0, MAX_FILE_CHARS);
|
|
212
|
+
}
|
|
213
|
+
let lines = content.split(/\r?\n/);
|
|
214
|
+
if (lines.length > MAX_FILE_LINES) {
|
|
215
|
+
lines = lines.slice(0, MAX_FILE_LINES);
|
|
216
|
+
}
|
|
217
|
+
for (let i = 0; i < lines.length; i++) {
|
|
218
|
+
if (lines[i].length > MAX_LINE_CHARS) {
|
|
219
|
+
lines[i] = lines[i].slice(0, MAX_LINE_CHARS);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return lines.join('\n');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function readBoundedFile(filePath) {
|
|
226
|
+
try {
|
|
227
|
+
const st = fs.lstatSync(filePath);
|
|
228
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
229
|
+
return '';
|
|
230
|
+
}
|
|
231
|
+
const maxBytes = MAX_FILE_CHARS * 4;
|
|
232
|
+
const buf = Buffer.alloc(Math.min(st.size, maxBytes));
|
|
233
|
+
let fd;
|
|
234
|
+
let bytesRead = 0;
|
|
235
|
+
try {
|
|
236
|
+
fd = fs.openSync(filePath, 'r');
|
|
237
|
+
bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
238
|
+
} finally {
|
|
239
|
+
if (fd !== undefined) {
|
|
240
|
+
try {
|
|
241
|
+
fs.closeSync(fd);
|
|
242
|
+
} catch {}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const raw = buf.toString('utf8', 0, bytesRead);
|
|
246
|
+
return boundContent(raw);
|
|
247
|
+
} catch {
|
|
248
|
+
return '';
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const CALLEE_RESERVED_WORDS = new Set([
|
|
253
|
+
'if',
|
|
254
|
+
'for',
|
|
255
|
+
'while',
|
|
256
|
+
'do',
|
|
257
|
+
'switch',
|
|
258
|
+
'case',
|
|
259
|
+
'catch',
|
|
260
|
+
'return',
|
|
261
|
+
'function',
|
|
262
|
+
'async',
|
|
263
|
+
'await',
|
|
264
|
+
'import',
|
|
265
|
+
'export',
|
|
266
|
+
'typeof',
|
|
267
|
+
'instanceof',
|
|
268
|
+
'void',
|
|
269
|
+
'delete',
|
|
270
|
+
'new',
|
|
271
|
+
'super',
|
|
272
|
+
'this',
|
|
273
|
+
'throw',
|
|
274
|
+
'yield',
|
|
275
|
+
'def',
|
|
276
|
+
'class',
|
|
277
|
+
'elif',
|
|
278
|
+
'with',
|
|
279
|
+
'try',
|
|
280
|
+
'except',
|
|
281
|
+
'finally',
|
|
282
|
+
'raise',
|
|
283
|
+
'from',
|
|
284
|
+
'fn',
|
|
285
|
+
'pub',
|
|
286
|
+
'struct',
|
|
287
|
+
'trait',
|
|
288
|
+
'impl',
|
|
289
|
+
'match',
|
|
290
|
+
'mut',
|
|
291
|
+
'let',
|
|
292
|
+
'const',
|
|
293
|
+
'where',
|
|
294
|
+
'func',
|
|
295
|
+
'type',
|
|
296
|
+
'select',
|
|
297
|
+
'defer',
|
|
298
|
+
'go',
|
|
299
|
+
'package',
|
|
300
|
+
'interface',
|
|
301
|
+
'map',
|
|
302
|
+
'chan',
|
|
303
|
+
'print',
|
|
304
|
+
'println',
|
|
305
|
+
'assert',
|
|
306
|
+
]);
|
|
307
|
+
|
|
308
|
+
function stripWorktreeSuffix(p) {
|
|
309
|
+
if (typeof p !== 'string') return '';
|
|
310
|
+
return p
|
|
311
|
+
.replace(/\/\.worktrees(\/.*)?$/, '')
|
|
312
|
+
.replace(/\/\.claude\/worktrees(\/.*)?$/, '')
|
|
313
|
+
.replace(/\/\.opencode\/worktrees(\/.*)?$/, '')
|
|
314
|
+
.replace(/\/\.codex\/worktrees(\/.*)?$/, '');
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function resolveGitRoot(targetDir) {
|
|
318
|
+
try {
|
|
319
|
+
const out = execFileSync('git', ['-C', targetDir, 'rev-parse', '--show-toplevel'], {
|
|
320
|
+
encoding: 'utf8',
|
|
321
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
322
|
+
}).trim();
|
|
323
|
+
if (out) {
|
|
324
|
+
return out;
|
|
325
|
+
}
|
|
326
|
+
} catch {}
|
|
327
|
+
return targetDir;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function deriveProjectNamespace(projectDir, explicitNamespace) {
|
|
331
|
+
if (typeof explicitNamespace === 'string' && explicitNamespace.trim().length > 0) {
|
|
332
|
+
let ns = explicitNamespace.trim();
|
|
333
|
+
ns = stripWorktreeSuffix(ns.replace(/\\/g, '/'));
|
|
334
|
+
ns = ns.replace(/^org:+/, '');
|
|
335
|
+
if (ns.length > 1 && !/^[a-zA-Z]:\/$/.test(ns)) ns = ns.replace(/\/+$/, '');
|
|
336
|
+
if (/^[a-zA-Z]:/.test(ns)) ns = ns.replace(/^([a-zA-Z]):\/*/, '$1-');
|
|
337
|
+
return ns.replace(/:\//g, '-').replace(/:/g, '-').replace(/\//g, '-');
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const rawDir = projectDir
|
|
341
|
+
? (typeof projectDir === 'string' && /^[a-zA-Z]:[\\/]/.test(projectDir) ? projectDir : path.resolve(projectDir))
|
|
342
|
+
: process.cwd();
|
|
343
|
+
return resolveProjectNamespaceInfo(rawDir, undefined, {}).namespace;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function hasProjectMarkers(projectDir) {
|
|
347
|
+
if (!projectDir || typeof projectDir !== 'string') return false;
|
|
348
|
+
for (const marker of PROJECT_MARKERS) {
|
|
349
|
+
if (fs.existsSync(path.join(projectDir, marker))) {
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (
|
|
354
|
+
fs.existsSync(path.join(projectDir, '.claude', 'CLAUDE.md')) ||
|
|
355
|
+
fs.existsSync(path.join(projectDir, '.claude', 'claude.md'))
|
|
356
|
+
) {
|
|
357
|
+
return true;
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
const topEntries = fs.readdirSync(projectDir, { withFileTypes: true });
|
|
361
|
+
for (const entry of topEntries) {
|
|
362
|
+
if (entry.isFile()) {
|
|
363
|
+
const lower = entry.name.toLowerCase();
|
|
364
|
+
if (
|
|
365
|
+
lower === 'claude.md' ||
|
|
366
|
+
lower === 'agents.md' ||
|
|
367
|
+
lower === 'readme.md' ||
|
|
368
|
+
lower.endsWith('.csproj') ||
|
|
369
|
+
lower.endsWith('.sln')
|
|
370
|
+
) {
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
} else if (entry.isDirectory() && entry.name.toLowerCase() === '.claude') {
|
|
374
|
+
try {
|
|
375
|
+
const claudeEntries = fs.readdirSync(path.join(projectDir, entry.name), { withFileTypes: true });
|
|
376
|
+
for (const cEntry of claudeEntries) {
|
|
377
|
+
if (cEntry.isFile() && cEntry.name.toLowerCase() === 'claude.md') {
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
} catch {}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
} catch {}
|
|
385
|
+
return false;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function collectSourceFiles(projectDir, { maxFiles = 40 } = {}) {
|
|
389
|
+
const collected = [];
|
|
390
|
+
|
|
391
|
+
function walkDir(dirPath, relativePrefix) {
|
|
392
|
+
if (collected.length >= maxFiles * 2) return;
|
|
393
|
+
let entries = [];
|
|
394
|
+
try {
|
|
395
|
+
entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
|
396
|
+
} catch {
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
401
|
+
|
|
402
|
+
for (const entry of entries) {
|
|
403
|
+
if (entry.name.startsWith('.') && entry.name !== '.cursorrules' && entry.name !== '.windsurfrules') {
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (entry.isSymbolicLink()) {
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const full = path.join(dirPath, entry.name);
|
|
410
|
+
try {
|
|
411
|
+
const st = fs.lstatSync(full);
|
|
412
|
+
if (st.isSymbolicLink()) continue;
|
|
413
|
+
} catch {
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
|
|
417
|
+
if (entry.isDirectory()) {
|
|
418
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
419
|
+
walkDir(full, relPath);
|
|
420
|
+
} else if (entry.isFile()) {
|
|
421
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
422
|
+
if (CODE_EXTENSIONS.has(ext)) {
|
|
423
|
+
collected.push(relPath);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// 1. Scan top-level source files
|
|
430
|
+
try {
|
|
431
|
+
const topEntries = fs.readdirSync(projectDir, { withFileTypes: true });
|
|
432
|
+
topEntries.sort((a, b) => a.name.localeCompare(b.name));
|
|
433
|
+
for (const entry of topEntries) {
|
|
434
|
+
if (entry.isSymbolicLink()) continue;
|
|
435
|
+
const full = path.join(projectDir, entry.name);
|
|
436
|
+
try {
|
|
437
|
+
const st = fs.lstatSync(full);
|
|
438
|
+
if (st.isSymbolicLink()) continue;
|
|
439
|
+
} catch {
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (entry.isFile()) {
|
|
443
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
444
|
+
if (CODE_EXTENSIONS.has(ext)) {
|
|
445
|
+
collected.push(entry.name);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
} catch {}
|
|
450
|
+
|
|
451
|
+
// 2. Scan priority source directories
|
|
452
|
+
const priorityDirs = ['src', 'lib', 'app', 'cmd', 'pkg', 'internal', 'include', 'server', 'client', 'pages', 'components'];
|
|
453
|
+
const scannedDirs = new Set();
|
|
454
|
+
|
|
455
|
+
for (const subDir of priorityDirs) {
|
|
456
|
+
scannedDirs.add(subDir);
|
|
457
|
+
const fullSub = path.join(projectDir, subDir);
|
|
458
|
+
try {
|
|
459
|
+
const st = fs.lstatSync(fullSub);
|
|
460
|
+
if (st.isSymbolicLink()) continue;
|
|
461
|
+
if (st.isDirectory()) {
|
|
462
|
+
walkDir(fullSub, subDir);
|
|
463
|
+
}
|
|
464
|
+
} catch {}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// 3. Scan remaining non-hidden, non-SKIP_DIRS top-level directories
|
|
468
|
+
try {
|
|
469
|
+
const topEntries = fs.readdirSync(projectDir, { withFileTypes: true });
|
|
470
|
+
topEntries.sort((a, b) => a.name.localeCompare(b.name));
|
|
471
|
+
for (const entry of topEntries) {
|
|
472
|
+
if (entry.isSymbolicLink()) continue;
|
|
473
|
+
if (entry.isDirectory()) {
|
|
474
|
+
if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name) || scannedDirs.has(entry.name)) {
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
const full = path.join(projectDir, entry.name);
|
|
478
|
+
try {
|
|
479
|
+
const st = fs.lstatSync(full);
|
|
480
|
+
if (st.isSymbolicLink()) continue;
|
|
481
|
+
} catch {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
walkDir(full, entry.name);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
} catch {}
|
|
488
|
+
|
|
489
|
+
const unique = Array.from(new Set(collected));
|
|
490
|
+
unique.sort((a, b) => a.localeCompare(b));
|
|
491
|
+
return unique.slice(0, maxFiles);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function extractCalleesFromLines(lines, startLineIdx, endLineIdx, ownName) {
|
|
495
|
+
const callees = new Set();
|
|
496
|
+
const subLines = lines.slice(startLineIdx, endLineIdx + 1);
|
|
497
|
+
const text = subLines.join('\n');
|
|
498
|
+
const callRegex = /\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g;
|
|
499
|
+
let match;
|
|
500
|
+
while ((match = callRegex.exec(text)) !== null) {
|
|
501
|
+
const fnName = match[1];
|
|
502
|
+
if (!CALLEE_RESERVED_WORDS.has(fnName) && fnName !== ownName) {
|
|
503
|
+
callees.add(fnName);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return Array.from(callees).sort();
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function findClosingBraceLine(lines, startLineIdx) {
|
|
510
|
+
let openCount = 0;
|
|
511
|
+
let hasOpened = false;
|
|
512
|
+
|
|
513
|
+
for (let i = startLineIdx; i < lines.length; i++) {
|
|
514
|
+
const line = lines[i];
|
|
515
|
+
for (let c = 0; c < line.length; c++) {
|
|
516
|
+
const char = line[c];
|
|
517
|
+
if (char === '{') {
|
|
518
|
+
openCount++;
|
|
519
|
+
hasOpened = true;
|
|
520
|
+
} else if (char === '}') {
|
|
521
|
+
openCount--;
|
|
522
|
+
if (hasOpened && openCount <= 0) {
|
|
523
|
+
return i + 1;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// Fallback: until empty line or next definition
|
|
530
|
+
for (let i = startLineIdx + 1; i < lines.length; i++) {
|
|
531
|
+
const trimmed = lines[i].trim();
|
|
532
|
+
if (!trimmed) {
|
|
533
|
+
return i;
|
|
534
|
+
}
|
|
535
|
+
if (/^(?:export\s+)?(?:async\s+)?(?:function|class|def|fn|func|interface|struct|trait)\b/.test(trimmed)) {
|
|
536
|
+
return i;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return Math.min(lines.length, startLineIdx + 15);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function findPythonBlockEndLine(lines, startLineIdx) {
|
|
544
|
+
const startIndentMatch = lines[startLineIdx].match(/^(\s*)/);
|
|
545
|
+
const baseIndent = startIndentMatch ? startIndentMatch[1].length : 0;
|
|
546
|
+
|
|
547
|
+
for (let i = startLineIdx + 1; i < lines.length; i++) {
|
|
548
|
+
const line = lines[i];
|
|
549
|
+
const trimmed = line.trim();
|
|
550
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
551
|
+
const indentMatch = line.match(/^(\s*)/);
|
|
552
|
+
const lineIndent = indentMatch ? indentMatch[1].length : 0;
|
|
553
|
+
if (lineIndent <= baseIndent) {
|
|
554
|
+
return i;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return lines.length;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function getEndBlockDelta(trimmedLine) {
|
|
561
|
+
const cleaned = trimmedLine.replace(/#.*$/, '').replace(/--.*$/, '').replace(/"[^"]*"/g, '').replace(/'[^']*'/g, '').trim();
|
|
562
|
+
if (!cleaned) return 0;
|
|
563
|
+
|
|
564
|
+
let delta = 0;
|
|
565
|
+
const words = cleaned.split(/[^a-zA-Z0-9_?!]+/);
|
|
566
|
+
|
|
567
|
+
for (const w of words) {
|
|
568
|
+
if (w === 'end') {
|
|
569
|
+
delta--;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const startsWithOpener = /^(?:def|defp|defmodule|defprotocol|defimpl|class|module|if|unless|case|while|until|for|begin|function)\b/.test(cleaned);
|
|
574
|
+
if (startsWithOpener) {
|
|
575
|
+
delta++;
|
|
576
|
+
} else if (/\bdo\b/.test(cleaned)) {
|
|
577
|
+
delta++;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
return delta;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function findEndKeywordLine(lines, startLineIdx) {
|
|
584
|
+
const startClean = lines[startLineIdx].replace(/#.*$/, '').replace(/--.*$/, '').trim();
|
|
585
|
+
if (/\bend\b/.test(startClean.replace(/^(?:def|defp|defmodule|defprotocol|defimpl|class|module|function)\b/, ''))) {
|
|
586
|
+
return startLineIdx + 1;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
let depth = 1;
|
|
590
|
+
for (let i = startLineIdx + 1; i < lines.length; i++) {
|
|
591
|
+
const delta = getEndBlockDelta(lines[i].trim());
|
|
592
|
+
depth += delta;
|
|
593
|
+
if (depth <= 0) {
|
|
594
|
+
return i + 1;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return lines.length;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function parseFileSymbols(relPath, content) {
|
|
601
|
+
const bounded = boundContent(content);
|
|
602
|
+
const lines = bounded.split(/\r?\n/);
|
|
603
|
+
const symbols = [];
|
|
604
|
+
const ext = path.extname(relPath).toLowerCase();
|
|
605
|
+
|
|
606
|
+
const isPython = ext === '.py' || ext === '.pyi';
|
|
607
|
+
const isRust = ext === '.rs';
|
|
608
|
+
const isGo = ext === '.go';
|
|
609
|
+
const isRuby = ext === '.rb';
|
|
610
|
+
const isElixir = ext === '.ex' || ext === '.exs';
|
|
611
|
+
const isLua = ext === '.lua';
|
|
612
|
+
const isShell = ['.sh', '.bash', '.zsh'].includes(ext);
|
|
613
|
+
const isSql = ext === '.sql';
|
|
614
|
+
const isJsTs = ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'].includes(ext);
|
|
615
|
+
const isJava = ext === '.java';
|
|
616
|
+
const isKotlin = ext === '.kt' || ext === '.kts';
|
|
617
|
+
const isScala = ext === '.scala';
|
|
618
|
+
const isCSharp = ext === '.cs';
|
|
619
|
+
const isCpp = ['.c', '.h', '.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx'].includes(ext);
|
|
620
|
+
const isSwift = ext === '.swift';
|
|
621
|
+
const isDart = ext === '.dart';
|
|
622
|
+
const isPhp = ext === '.php';
|
|
623
|
+
|
|
624
|
+
for (let i = 0; i < lines.length; i++) {
|
|
625
|
+
const line = lines[i];
|
|
626
|
+
const trimmed = line.trim();
|
|
627
|
+
if (
|
|
628
|
+
!trimmed ||
|
|
629
|
+
trimmed.startsWith('//') ||
|
|
630
|
+
trimmed.startsWith('/*') ||
|
|
631
|
+
trimmed.startsWith('*') ||
|
|
632
|
+
trimmed.startsWith('--') ||
|
|
633
|
+
(!isJsTs && trimmed.startsWith('#')) ||
|
|
634
|
+
(isJsTs && trimmed.startsWith('#!'))
|
|
635
|
+
) {
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Python class & def
|
|
640
|
+
if (isPython) {
|
|
641
|
+
const pyClassMatch = trimmed.match(/^class\s+([a-zA-Z0-9_]+)(?:\(([^)]*)\))?:/);
|
|
642
|
+
if (pyClassMatch) {
|
|
643
|
+
const name = pyClassMatch[1];
|
|
644
|
+
const bases = pyClassMatch[2]
|
|
645
|
+
? pyClassMatch[2].split(',').map(s => s.trim()).filter(Boolean)
|
|
646
|
+
: [];
|
|
647
|
+
const endLine = findPythonBlockEndLine(lines, i);
|
|
648
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
649
|
+
symbols.push({
|
|
650
|
+
name,
|
|
651
|
+
kind: 'class',
|
|
652
|
+
file: relPath,
|
|
653
|
+
startLine: i + 1,
|
|
654
|
+
endLine,
|
|
655
|
+
extends: bases[0] || null,
|
|
656
|
+
implements: bases.slice(1),
|
|
657
|
+
callees,
|
|
658
|
+
signature: trimmed,
|
|
659
|
+
});
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
const pyDefMatch = trimmed.match(/^(?:async\s+)?def\s+([a-zA-Z0-9_]+)\s*\(/);
|
|
664
|
+
if (pyDefMatch) {
|
|
665
|
+
const name = pyDefMatch[1];
|
|
666
|
+
const endLine = findPythonBlockEndLine(lines, i);
|
|
667
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
668
|
+
symbols.push({
|
|
669
|
+
name,
|
|
670
|
+
kind: 'function',
|
|
671
|
+
file: relPath,
|
|
672
|
+
startLine: i + 1,
|
|
673
|
+
endLine,
|
|
674
|
+
implements: [],
|
|
675
|
+
callees,
|
|
676
|
+
signature: trimmed,
|
|
677
|
+
});
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Ruby
|
|
683
|
+
if (isRuby) {
|
|
684
|
+
const rbClassMatch = trimmed.match(/^class\s+([a-zA-Z0-9_:]+)(?:\s*<\s*([a-zA-Z0-9_:]+))?/);
|
|
685
|
+
if (rbClassMatch) {
|
|
686
|
+
const name = rbClassMatch[1].split('::').pop();
|
|
687
|
+
const base = rbClassMatch[2] ? rbClassMatch[2].split('::').pop() : null;
|
|
688
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
689
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
690
|
+
const includes = [];
|
|
691
|
+
for (let j = i + 1; j < Math.min(endLine, lines.length); j++) {
|
|
692
|
+
const incMatch = lines[j].trim().match(/^include\s+([a-zA-Z0-9_:]+)/);
|
|
693
|
+
if (incMatch) {
|
|
694
|
+
includes.push(incMatch[1].split('::').pop());
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
symbols.push({
|
|
698
|
+
name,
|
|
699
|
+
kind: 'class',
|
|
700
|
+
file: relPath,
|
|
701
|
+
startLine: i + 1,
|
|
702
|
+
endLine,
|
|
703
|
+
extends: base,
|
|
704
|
+
implements: includes,
|
|
705
|
+
callees,
|
|
706
|
+
signature: trimmed,
|
|
707
|
+
});
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const rbModuleMatch = trimmed.match(/^module\s+([a-zA-Z0-9_:]+)/);
|
|
712
|
+
if (rbModuleMatch) {
|
|
713
|
+
const name = rbModuleMatch[1].split('::').pop();
|
|
714
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
715
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
716
|
+
const includes = [];
|
|
717
|
+
for (let j = i + 1; j < Math.min(endLine, lines.length); j++) {
|
|
718
|
+
const incMatch = lines[j].trim().match(/^include\s+([a-zA-Z0-9_:]+)/);
|
|
719
|
+
if (incMatch) {
|
|
720
|
+
includes.push(incMatch[1].split('::').pop());
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
symbols.push({
|
|
724
|
+
name,
|
|
725
|
+
kind: 'module',
|
|
726
|
+
file: relPath,
|
|
727
|
+
startLine: i + 1,
|
|
728
|
+
endLine,
|
|
729
|
+
implements: includes,
|
|
730
|
+
callees,
|
|
731
|
+
signature: trimmed,
|
|
732
|
+
});
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const rbDefMatch = trimmed.match(/^def\s+(?:self\.)?([a-zA-Z0-9_]+[?!]?)\s*(?:\(|$)/);
|
|
737
|
+
if (rbDefMatch) {
|
|
738
|
+
const name = rbDefMatch[1];
|
|
739
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
740
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
741
|
+
symbols.push({
|
|
742
|
+
name,
|
|
743
|
+
kind: 'function',
|
|
744
|
+
file: relPath,
|
|
745
|
+
startLine: i + 1,
|
|
746
|
+
endLine,
|
|
747
|
+
implements: [],
|
|
748
|
+
callees,
|
|
749
|
+
signature: trimmed,
|
|
750
|
+
});
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Elixir
|
|
756
|
+
if (isElixir) {
|
|
757
|
+
const exModuleMatch = trimmed.match(/^defmodule\s+([a-zA-Z0-9_.]+)\s+do/);
|
|
758
|
+
if (exModuleMatch) {
|
|
759
|
+
const fullName = exModuleMatch[1];
|
|
760
|
+
const name = fullName.split('.').pop();
|
|
761
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
762
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
763
|
+
symbols.push({
|
|
764
|
+
name,
|
|
765
|
+
kind: 'module',
|
|
766
|
+
file: relPath,
|
|
767
|
+
startLine: i + 1,
|
|
768
|
+
endLine,
|
|
769
|
+
implements: [],
|
|
770
|
+
callees,
|
|
771
|
+
signature: trimmed,
|
|
772
|
+
});
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const exProtoMatch = trimmed.match(/^defprotocol\s+([a-zA-Z0-9_.]+)\s+do/);
|
|
777
|
+
if (exProtoMatch) {
|
|
778
|
+
const fullName = exProtoMatch[1];
|
|
779
|
+
const name = fullName.split('.').pop();
|
|
780
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
781
|
+
symbols.push({
|
|
782
|
+
name,
|
|
783
|
+
kind: 'interface',
|
|
784
|
+
file: relPath,
|
|
785
|
+
startLine: i + 1,
|
|
786
|
+
endLine,
|
|
787
|
+
implements: [],
|
|
788
|
+
callees: [],
|
|
789
|
+
signature: trimmed,
|
|
790
|
+
});
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const exImplMatch = trimmed.match(/^defimpl\s+([a-zA-Z0-9_.]+)\s*,\s*for:\s*([a-zA-Z0-9_.]+)\s+do/);
|
|
795
|
+
if (exImplMatch) {
|
|
796
|
+
const proto = exImplMatch[1].split('.').pop();
|
|
797
|
+
const forType = exImplMatch[2].split('.').pop();
|
|
798
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
799
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, forType);
|
|
800
|
+
symbols.push({
|
|
801
|
+
name: forType,
|
|
802
|
+
kind: 'impl',
|
|
803
|
+
file: relPath,
|
|
804
|
+
startLine: i + 1,
|
|
805
|
+
endLine,
|
|
806
|
+
implements: [proto],
|
|
807
|
+
callees,
|
|
808
|
+
signature: trimmed,
|
|
809
|
+
});
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const exDefMatch = trimmed.match(/^(?:def|defp)\s+([a-zA-Z0-9_]+[?!]?)\s*(?:\(|do\b|$)/);
|
|
814
|
+
if (exDefMatch) {
|
|
815
|
+
const name = exDefMatch[1];
|
|
816
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
817
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
818
|
+
symbols.push({
|
|
819
|
+
name,
|
|
820
|
+
kind: 'function',
|
|
821
|
+
file: relPath,
|
|
822
|
+
startLine: i + 1,
|
|
823
|
+
endLine,
|
|
824
|
+
implements: [],
|
|
825
|
+
callees,
|
|
826
|
+
signature: trimmed,
|
|
827
|
+
});
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// Lua
|
|
833
|
+
if (isLua) {
|
|
834
|
+
const luaFnMatch = trimmed.match(/^(?:local\s+)?function\s+(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]+)\s*\(/);
|
|
835
|
+
if (luaFnMatch) {
|
|
836
|
+
const name = luaFnMatch[1];
|
|
837
|
+
const endLine = findEndKeywordLine(lines, i);
|
|
838
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
839
|
+
symbols.push({
|
|
840
|
+
name,
|
|
841
|
+
kind: 'function',
|
|
842
|
+
file: relPath,
|
|
843
|
+
startLine: i + 1,
|
|
844
|
+
endLine,
|
|
845
|
+
implements: [],
|
|
846
|
+
callees,
|
|
847
|
+
signature: trimmed,
|
|
848
|
+
});
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Shell
|
|
854
|
+
if (isShell) {
|
|
855
|
+
const shMatch = trimmed.match(/^(?:function\s+([a-zA-Z0-9_]+)(?:\s*\(\s*\))?|([a-zA-Z0-9_]+)\s*\(\s*\))\s*(?:\{|$)/);
|
|
856
|
+
if (shMatch) {
|
|
857
|
+
const name = shMatch[1] || shMatch[2];
|
|
858
|
+
if (name && !CALLEE_RESERVED_WORDS.has(name)) {
|
|
859
|
+
const endLine = trimmed.includes('{') ? findClosingBraceLine(lines, i) : i + 1;
|
|
860
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
861
|
+
symbols.push({
|
|
862
|
+
name,
|
|
863
|
+
kind: 'function',
|
|
864
|
+
file: relPath,
|
|
865
|
+
startLine: i + 1,
|
|
866
|
+
endLine,
|
|
867
|
+
implements: [],
|
|
868
|
+
callees,
|
|
869
|
+
signature: trimmed,
|
|
870
|
+
});
|
|
871
|
+
continue;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// SQL
|
|
877
|
+
if (isSql) {
|
|
878
|
+
const sqlMatch = trimmed.match(/^CREATE(?:\s+OR\s+REPLACE)?\s+(FUNCTION|PROCEDURE|TABLE|VIEW)(?:\s+IF\s+NOT\s+EXISTS)?\s+(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]+)/i);
|
|
879
|
+
if (sqlMatch) {
|
|
880
|
+
const kind = sqlMatch[1].toLowerCase();
|
|
881
|
+
const name = sqlMatch[2];
|
|
882
|
+
symbols.push({
|
|
883
|
+
name,
|
|
884
|
+
kind,
|
|
885
|
+
file: relPath,
|
|
886
|
+
startLine: i + 1,
|
|
887
|
+
endLine: i + 1,
|
|
888
|
+
implements: [],
|
|
889
|
+
callees: [],
|
|
890
|
+
signature: trimmed,
|
|
891
|
+
});
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// Rust
|
|
897
|
+
if (isRust) {
|
|
898
|
+
const rustStructMatch = trimmed.match(/^(?:pub(?:\([^)]*\))?\s+)?struct\s+([a-zA-Z0-9_]+)/);
|
|
899
|
+
if (rustStructMatch) {
|
|
900
|
+
const name = rustStructMatch[1];
|
|
901
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
902
|
+
symbols.push({
|
|
903
|
+
name,
|
|
904
|
+
kind: 'struct',
|
|
905
|
+
file: relPath,
|
|
906
|
+
startLine: i + 1,
|
|
907
|
+
endLine,
|
|
908
|
+
implements: [],
|
|
909
|
+
callees: [],
|
|
910
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
911
|
+
});
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
const rustTraitMatch = trimmed.match(/^(?:pub(?:\([^)]*\))?\s+)?trait\s+([a-zA-Z0-9_]+)/);
|
|
916
|
+
if (rustTraitMatch) {
|
|
917
|
+
const name = rustTraitMatch[1];
|
|
918
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
919
|
+
symbols.push({
|
|
920
|
+
name,
|
|
921
|
+
kind: 'trait',
|
|
922
|
+
file: relPath,
|
|
923
|
+
startLine: i + 1,
|
|
924
|
+
endLine,
|
|
925
|
+
implements: [],
|
|
926
|
+
callees: [],
|
|
927
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
928
|
+
});
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const rustEnumMatch = trimmed.match(/^(?:pub(?:\([^)]*\))?\s+)?enum\s+([a-zA-Z0-9_]+)/);
|
|
933
|
+
if (rustEnumMatch) {
|
|
934
|
+
const name = rustEnumMatch[1];
|
|
935
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
936
|
+
symbols.push({
|
|
937
|
+
name,
|
|
938
|
+
kind: 'enum',
|
|
939
|
+
file: relPath,
|
|
940
|
+
startLine: i + 1,
|
|
941
|
+
endLine,
|
|
942
|
+
implements: [],
|
|
943
|
+
callees: [],
|
|
944
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
945
|
+
});
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const rustImplMatch = trimmed.match(/^impl(?:\s*<[^>]*>)?\s+([a-zA-Z0-9_:]+)(?:\s+for\s+([a-zA-Z0-9_:]+))?/);
|
|
950
|
+
if (rustImplMatch) {
|
|
951
|
+
const traitName = rustImplMatch[2] ? rustImplMatch[1] : null;
|
|
952
|
+
const structName = rustImplMatch[2] ? rustImplMatch[2] : rustImplMatch[1];
|
|
953
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
954
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, structName);
|
|
955
|
+
symbols.push({
|
|
956
|
+
name: structName,
|
|
957
|
+
kind: 'impl',
|
|
958
|
+
file: relPath,
|
|
959
|
+
startLine: i + 1,
|
|
960
|
+
endLine,
|
|
961
|
+
implements: traitName ? [traitName] : [],
|
|
962
|
+
callees,
|
|
963
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
964
|
+
});
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const rustFnMatch = trimmed.match(/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:const\s+)?(?:unsafe\s+)?(?:extern\s+(?:"[^"]*"\s+)?)?fn\s+([a-zA-Z0-9_]+)\s*(?:<[^>]*>)?\s*\(/);
|
|
969
|
+
if (rustFnMatch) {
|
|
970
|
+
const name = rustFnMatch[1];
|
|
971
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
972
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
973
|
+
symbols.push({
|
|
974
|
+
name,
|
|
975
|
+
kind: 'function',
|
|
976
|
+
file: relPath,
|
|
977
|
+
startLine: i + 1,
|
|
978
|
+
endLine,
|
|
979
|
+
implements: [],
|
|
980
|
+
callees,
|
|
981
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
982
|
+
});
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// Go
|
|
988
|
+
if (isGo) {
|
|
989
|
+
const goTypeMatch = trimmed.match(/^type\s+([a-zA-Z0-9_]+)\s+(struct|interface)\b/);
|
|
990
|
+
if (goTypeMatch) {
|
|
991
|
+
const name = goTypeMatch[1];
|
|
992
|
+
const kind = goTypeMatch[2];
|
|
993
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
994
|
+
symbols.push({
|
|
995
|
+
name,
|
|
996
|
+
kind,
|
|
997
|
+
file: relPath,
|
|
998
|
+
startLine: i + 1,
|
|
999
|
+
endLine,
|
|
1000
|
+
implements: [],
|
|
1001
|
+
callees: [],
|
|
1002
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1003
|
+
});
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const goFuncMatch = trimmed.match(/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z0-9_]+)\s*\(/);
|
|
1008
|
+
if (goFuncMatch) {
|
|
1009
|
+
const name = goFuncMatch[1];
|
|
1010
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1011
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1012
|
+
symbols.push({
|
|
1013
|
+
name,
|
|
1014
|
+
kind: 'function',
|
|
1015
|
+
file: relPath,
|
|
1016
|
+
startLine: i + 1,
|
|
1017
|
+
endLine,
|
|
1018
|
+
implements: [],
|
|
1019
|
+
callees,
|
|
1020
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1021
|
+
});
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// Swift
|
|
1027
|
+
if (isSwift) {
|
|
1028
|
+
const swiftTypeMatch = trimmed.match(/^(?:(?:public|private|fileprivate|internal|open|final)\s+)*(class|struct|enum|protocol|actor|extension)\s+([a-zA-Z0-9_]+)(?:<[^>]*>)?(?:\s*:\s*([^{]+))?/);
|
|
1029
|
+
if (swiftTypeMatch) {
|
|
1030
|
+
const kind = swiftTypeMatch[1];
|
|
1031
|
+
const name = swiftTypeMatch[2];
|
|
1032
|
+
const rawProto = swiftTypeMatch[3];
|
|
1033
|
+
const protos = rawProto ? rawProto.split(',').map(s => s.trim()).filter(Boolean) : [];
|
|
1034
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1035
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1036
|
+
symbols.push({
|
|
1037
|
+
name,
|
|
1038
|
+
kind: kind === 'protocol' ? 'interface' : kind,
|
|
1039
|
+
file: relPath,
|
|
1040
|
+
startLine: i + 1,
|
|
1041
|
+
endLine,
|
|
1042
|
+
extends: kind === 'class' ? (protos.length > 1 ? protos[0] : null) : null,
|
|
1043
|
+
implements: kind === 'class' ? (protos.length > 1 ? protos.slice(1) : protos) : protos,
|
|
1044
|
+
callees,
|
|
1045
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1046
|
+
});
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const swiftFuncMatch = trimmed.match(/^(?:(?:public|private|fileprivate|internal|open|static|class|override|mutating|async)\s+)*func\s+([a-zA-Z0-9_]+)\s*(?:<[^>]*>)?\s*\(/);
|
|
1051
|
+
if (swiftFuncMatch) {
|
|
1052
|
+
const name = swiftFuncMatch[1];
|
|
1053
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1054
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1055
|
+
symbols.push({
|
|
1056
|
+
name,
|
|
1057
|
+
kind: 'function',
|
|
1058
|
+
file: relPath,
|
|
1059
|
+
startLine: i + 1,
|
|
1060
|
+
endLine,
|
|
1061
|
+
implements: [],
|
|
1062
|
+
callees,
|
|
1063
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1064
|
+
});
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// Kotlin
|
|
1070
|
+
if (isKotlin) {
|
|
1071
|
+
const ktClassMatch = trimmed.match(/^(?:(?:data|sealed|open|abstract|internal|public|private)\s+)*(class|interface|object)\s+([a-zA-Z0-9_]+)(?:<[^>]*>)?(?:\([^)]*\))?(?:\s*:\s*([^{]+))?/);
|
|
1072
|
+
if (ktClassMatch) {
|
|
1073
|
+
const kind = ktClassMatch[1];
|
|
1074
|
+
const name = ktClassMatch[2];
|
|
1075
|
+
const rawBases = ktClassMatch[3];
|
|
1076
|
+
const bases = rawBases ? rawBases.split(',').map(s => s.replace(/\([^)]*\)/g, '').trim()).filter(Boolean) : [];
|
|
1077
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1078
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1079
|
+
symbols.push({
|
|
1080
|
+
name,
|
|
1081
|
+
kind: kind === 'object' ? 'class' : kind,
|
|
1082
|
+
file: relPath,
|
|
1083
|
+
startLine: i + 1,
|
|
1084
|
+
endLine,
|
|
1085
|
+
extends: bases[0] || null,
|
|
1086
|
+
implements: bases.slice(1),
|
|
1087
|
+
callees,
|
|
1088
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1089
|
+
});
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
const ktFunMatch = trimmed.match(/^(?:(?:suspend|override|open|abstract|public|private|internal)\s+)*fun\s+(?:<[^>]*>\s*)?([a-zA-Z0-9_]+)\s*\(/);
|
|
1094
|
+
if (ktFunMatch) {
|
|
1095
|
+
const name = ktFunMatch[1];
|
|
1096
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1097
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1098
|
+
symbols.push({
|
|
1099
|
+
name,
|
|
1100
|
+
kind: 'function',
|
|
1101
|
+
file: relPath,
|
|
1102
|
+
startLine: i + 1,
|
|
1103
|
+
endLine,
|
|
1104
|
+
implements: [],
|
|
1105
|
+
callees,
|
|
1106
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1107
|
+
});
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Scala
|
|
1113
|
+
if (isScala) {
|
|
1114
|
+
const scalaClassMatch = trimmed.match(/^(?:case\s+)?(class|trait|object)\s+([a-zA-Z0-9_]+)(?:<[^>]*>)?(?:\s+extends\s+([a-zA-Z0-9_.]+))?(?:\s+with\s+([^{]+))?/);
|
|
1115
|
+
if (scalaClassMatch) {
|
|
1116
|
+
const kind = scalaClassMatch[1];
|
|
1117
|
+
const name = scalaClassMatch[2];
|
|
1118
|
+
const base = scalaClassMatch[3] ? scalaClassMatch[3].trim() : null;
|
|
1119
|
+
const rawWith = scalaClassMatch[4];
|
|
1120
|
+
const withList = rawWith ? rawWith.split(/\s+with\s+/).map(s => s.trim()).filter(Boolean) : [];
|
|
1121
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1122
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1123
|
+
symbols.push({
|
|
1124
|
+
name,
|
|
1125
|
+
kind: kind === 'trait' ? 'interface' : kind,
|
|
1126
|
+
file: relPath,
|
|
1127
|
+
startLine: i + 1,
|
|
1128
|
+
endLine,
|
|
1129
|
+
extends: base,
|
|
1130
|
+
implements: withList,
|
|
1131
|
+
callees,
|
|
1132
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1133
|
+
});
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
const scalaDefMatch = trimmed.match(/^def\s+([a-zA-Z0-9_]+)(?:<[^>]*>)?\s*\(/);
|
|
1138
|
+
if (scalaDefMatch) {
|
|
1139
|
+
const name = scalaDefMatch[1];
|
|
1140
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1141
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1142
|
+
symbols.push({
|
|
1143
|
+
name,
|
|
1144
|
+
kind: 'function',
|
|
1145
|
+
file: relPath,
|
|
1146
|
+
startLine: i + 1,
|
|
1147
|
+
endLine,
|
|
1148
|
+
implements: [],
|
|
1149
|
+
callees,
|
|
1150
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1151
|
+
});
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// JavaScript / TypeScript
|
|
1157
|
+
if (isJsTs) {
|
|
1158
|
+
// CommonJS module.exports = function name(...)
|
|
1159
|
+
const cjsFnMatch = trimmed.match(/^module\.exports\s*=\s*(?:async\s+)?function\s+([a-zA-Z0-9_$]+)/);
|
|
1160
|
+
if (cjsFnMatch) {
|
|
1161
|
+
const name = cjsFnMatch[1];
|
|
1162
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1163
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1164
|
+
symbols.push({
|
|
1165
|
+
name,
|
|
1166
|
+
kind: 'function',
|
|
1167
|
+
file: relPath,
|
|
1168
|
+
startLine: i + 1,
|
|
1169
|
+
endLine,
|
|
1170
|
+
implements: [],
|
|
1171
|
+
callees,
|
|
1172
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1173
|
+
});
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// CommonJS (module.)exports.name = ...
|
|
1178
|
+
const cjsExportMatch = trimmed.match(/^(?:module\.)?exports\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s*)?(?:function|\([^)]*\)\s*=>|[a-zA-Z_$][a-zA-Z0-9_$]*\s*=>)/);
|
|
1179
|
+
if (cjsExportMatch) {
|
|
1180
|
+
const name = cjsExportMatch[1];
|
|
1181
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1182
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1183
|
+
symbols.push({
|
|
1184
|
+
name,
|
|
1185
|
+
kind: 'function',
|
|
1186
|
+
file: relPath,
|
|
1187
|
+
startLine: i + 1,
|
|
1188
|
+
endLine,
|
|
1189
|
+
implements: [],
|
|
1190
|
+
callees,
|
|
1191
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1192
|
+
});
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// Class definitions (JS / TS)
|
|
1197
|
+
const classMatch = trimmed.match(/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([a-zA-Z0-9_$]+)(?:\s+extends\s+([a-zA-Z0-9_$]+))?(?:\s+implements\s+([^{]+))?/);
|
|
1198
|
+
if (classMatch) {
|
|
1199
|
+
const name = classMatch[1];
|
|
1200
|
+
const extendsClass = classMatch[2] || null;
|
|
1201
|
+
const rawImplements = classMatch[3];
|
|
1202
|
+
const implementsList = rawImplements
|
|
1203
|
+
? rawImplements.split(',').map(s => s.replace(/<[^>]*>/g, '').trim()).filter(Boolean)
|
|
1204
|
+
: [];
|
|
1205
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1206
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1207
|
+
symbols.push({
|
|
1208
|
+
name,
|
|
1209
|
+
kind: 'class',
|
|
1210
|
+
file: relPath,
|
|
1211
|
+
startLine: i + 1,
|
|
1212
|
+
endLine,
|
|
1213
|
+
extends: extendsClass,
|
|
1214
|
+
implements: implementsList,
|
|
1215
|
+
callees,
|
|
1216
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1217
|
+
});
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// Interfaces (TS)
|
|
1222
|
+
const ifaceMatch = trimmed.match(/^(?:export\s+)?interface\s+([a-zA-Z0-9_$]+)(?:\s+extends\s+([^{]+))?/);
|
|
1223
|
+
if (ifaceMatch) {
|
|
1224
|
+
const name = ifaceMatch[1];
|
|
1225
|
+
const rawExtends = ifaceMatch[2];
|
|
1226
|
+
const extendsList = rawExtends
|
|
1227
|
+
? rawExtends.split(',').map(s => s.replace(/<[^>]*>/g, '').trim()).filter(Boolean)
|
|
1228
|
+
: [];
|
|
1229
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1230
|
+
symbols.push({
|
|
1231
|
+
name,
|
|
1232
|
+
kind: 'interface',
|
|
1233
|
+
file: relPath,
|
|
1234
|
+
startLine: i + 1,
|
|
1235
|
+
endLine,
|
|
1236
|
+
extends: extendsList[0] || null,
|
|
1237
|
+
implements: extendsList,
|
|
1238
|
+
callees: [],
|
|
1239
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1240
|
+
});
|
|
1241
|
+
continue;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// Enums
|
|
1245
|
+
const enumMatch = trimmed.match(/^(?:export\s+)?(?:const\s+)?enum\s+([a-zA-Z0-9_$]+)/);
|
|
1246
|
+
if (enumMatch) {
|
|
1247
|
+
const name = enumMatch[1];
|
|
1248
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1249
|
+
symbols.push({
|
|
1250
|
+
name,
|
|
1251
|
+
kind: 'enum',
|
|
1252
|
+
file: relPath,
|
|
1253
|
+
startLine: i + 1,
|
|
1254
|
+
endLine,
|
|
1255
|
+
implements: [],
|
|
1256
|
+
callees: [],
|
|
1257
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1258
|
+
});
|
|
1259
|
+
continue;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// Types
|
|
1263
|
+
const typeMatch = trimmed.match(/^(?:export\s+)?type\s+([a-zA-Z0-9_$]+)(?:<[^>]*>)?\s*=/);
|
|
1264
|
+
if (typeMatch) {
|
|
1265
|
+
const name = typeMatch[1];
|
|
1266
|
+
symbols.push({
|
|
1267
|
+
name,
|
|
1268
|
+
kind: 'type',
|
|
1269
|
+
file: relPath,
|
|
1270
|
+
startLine: i + 1,
|
|
1271
|
+
endLine: i + 1,
|
|
1272
|
+
implements: [],
|
|
1273
|
+
callees: [],
|
|
1274
|
+
signature: trimmed.trim(),
|
|
1275
|
+
});
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
// Standard function declaration
|
|
1280
|
+
const fnMatch = trimmed.match(/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function(?:\s*\*|\s+)([a-zA-Z0-9_$]+)\s*\(/);
|
|
1281
|
+
if (fnMatch) {
|
|
1282
|
+
const name = fnMatch[1];
|
|
1283
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1284
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1285
|
+
symbols.push({
|
|
1286
|
+
name,
|
|
1287
|
+
kind: 'function',
|
|
1288
|
+
file: relPath,
|
|
1289
|
+
startLine: i + 1,
|
|
1290
|
+
endLine,
|
|
1291
|
+
implements: [],
|
|
1292
|
+
callees,
|
|
1293
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1294
|
+
});
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// Variable function expression or arrow function
|
|
1299
|
+
const varFnMatch = trimmed.match(/^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)(?:\s*:\s*[^=]+)?\s*=\s*(?:async\s*)?(?:(?:\([^)]*\)|[a-zA-Z0-9_$]+)\s*=>|function\b)/);
|
|
1300
|
+
if (varFnMatch) {
|
|
1301
|
+
const name = varFnMatch[1];
|
|
1302
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1303
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1304
|
+
symbols.push({
|
|
1305
|
+
name,
|
|
1306
|
+
kind: 'function',
|
|
1307
|
+
file: relPath,
|
|
1308
|
+
startLine: i + 1,
|
|
1309
|
+
endLine,
|
|
1310
|
+
implements: [],
|
|
1311
|
+
callees,
|
|
1312
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1313
|
+
});
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// Class Methods, Getters/Setters & #private methods
|
|
1318
|
+
if (trimmed.includes('{')) {
|
|
1319
|
+
const strippedJs = trimmed.replace(/^(?:(?:public|private|protected|static|readonly|override|abstract|async|get|set)\s+)+/, '');
|
|
1320
|
+
const methodMatch = strippedJs.match(/^(#?[a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?:<[^>]*>)?\s*\([^;()]*\)\s*(?::\s*[^{;=]+)?\s*\{/);
|
|
1321
|
+
if (methodMatch) {
|
|
1322
|
+
const name = methodMatch[1];
|
|
1323
|
+
if (!CALLEE_RESERVED_WORDS.has(name) && name !== 'constructor') {
|
|
1324
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1325
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1326
|
+
symbols.push({
|
|
1327
|
+
name,
|
|
1328
|
+
kind: 'method',
|
|
1329
|
+
file: relPath,
|
|
1330
|
+
startLine: i + 1,
|
|
1331
|
+
endLine,
|
|
1332
|
+
implements: [],
|
|
1333
|
+
callees,
|
|
1334
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1335
|
+
});
|
|
1336
|
+
continue;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// Java, C#, C++, PHP, Dart classes & methods
|
|
1343
|
+
if (isJava || isCSharp || isCpp || isPhp || isDart) {
|
|
1344
|
+
// Classes / interfaces / enums / records / structs
|
|
1345
|
+
const typeDefMatch = trimmed.match(/^(?:(?:public|private|protected|internal|static|final|abstract|sealed|virtual|override|partial|readonly|open)\s+)*(class|interface|enum|record|struct)\s+([a-zA-Z0-9_]+)(?:<[^>]*>)?(?:\s+extends\s+([a-zA-Z0-9_.]+))?(?:\s+implements\s+([^{]+))?(?:\s*:\s*([^{]+))?/);
|
|
1346
|
+
if (typeDefMatch) {
|
|
1347
|
+
const kind = typeDefMatch[1];
|
|
1348
|
+
const name = typeDefMatch[2];
|
|
1349
|
+
let extendsName = typeDefMatch[3] ? typeDefMatch[3].trim() : null;
|
|
1350
|
+
let implementsList = [];
|
|
1351
|
+
if (typeDefMatch[4]) {
|
|
1352
|
+
implementsList = typeDefMatch[4].split(',').map(s => s.trim()).filter(Boolean);
|
|
1353
|
+
} else if (typeDefMatch[5]) {
|
|
1354
|
+
const colonBases = typeDefMatch[5].split(',').map(s => s.replace(/\b(?:public|private|protected|internal)\b/g, '').trim()).filter(Boolean);
|
|
1355
|
+
if (colonBases.length > 0) {
|
|
1356
|
+
extendsName = colonBases[0];
|
|
1357
|
+
implementsList = colonBases.slice(1);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1361
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1362
|
+
symbols.push({
|
|
1363
|
+
name,
|
|
1364
|
+
kind: kind === 'record' ? 'class' : kind,
|
|
1365
|
+
file: relPath,
|
|
1366
|
+
startLine: i + 1,
|
|
1367
|
+
endLine,
|
|
1368
|
+
extends: extendsName,
|
|
1369
|
+
implements: implementsList,
|
|
1370
|
+
callees,
|
|
1371
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1372
|
+
});
|
|
1373
|
+
continue;
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// PHP function
|
|
1377
|
+
if (isPhp) {
|
|
1378
|
+
const phpFnMatch = trimmed.match(/^(?:(?:public|private|protected|static)\s+)*function\s+([a-zA-Z0-9_]+)\s*\(/);
|
|
1379
|
+
if (phpFnMatch) {
|
|
1380
|
+
const name = phpFnMatch[1];
|
|
1381
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1382
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, name);
|
|
1383
|
+
symbols.push({
|
|
1384
|
+
name,
|
|
1385
|
+
kind: 'function',
|
|
1386
|
+
file: relPath,
|
|
1387
|
+
startLine: i + 1,
|
|
1388
|
+
endLine,
|
|
1389
|
+
implements: [],
|
|
1390
|
+
callees,
|
|
1391
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1392
|
+
});
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
// Typed methods
|
|
1398
|
+
if (trimmed.includes('{')) {
|
|
1399
|
+
const strippedMods = trimmed.replace(/^(?:(?:public|private|protected|internal|static|final|abstract|synchronized|virtual|override|async|inline|constexpr|extern|readonly|get|set)\s+)+/, '');
|
|
1400
|
+
const typedMethodMatch = strippedMods.match(/^([A-Za-z_][\w:<>,.?[\]*&]*(?:\s+[A-Za-z_*&][\w:<>,.?[\]*&]*){0,3})\s+(?:([A-Za-z_]\w*)::)?([A-Za-z_]\w*)\s*\([^;()]*\)\s*(?:throws\s+[^{;]+|const\s*)?\{/);
|
|
1401
|
+
if (typedMethodMatch) {
|
|
1402
|
+
const methodName = typedMethodMatch[3];
|
|
1403
|
+
if (!CALLEE_RESERVED_WORDS.has(methodName) && methodName !== 'if' && methodName !== 'for' && methodName !== 'while' && methodName !== 'switch' && methodName !== 'catch') {
|
|
1404
|
+
const endLine = findClosingBraceLine(lines, i);
|
|
1405
|
+
const callees = extractCalleesFromLines(lines, i, endLine - 1, methodName);
|
|
1406
|
+
symbols.push({
|
|
1407
|
+
name: methodName,
|
|
1408
|
+
kind: 'method',
|
|
1409
|
+
file: relPath,
|
|
1410
|
+
startLine: i + 1,
|
|
1411
|
+
endLine,
|
|
1412
|
+
implements: [],
|
|
1413
|
+
callees,
|
|
1414
|
+
signature: trimmed.replace(/\{$/, '').trim(),
|
|
1415
|
+
});
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
return symbols;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
export function scanProjectCodeIndex(projectDir, { maxFiles = 40 } = {}) {
|
|
1427
|
+
const targetDir = path.resolve(projectDir || process.cwd());
|
|
1428
|
+
const files = collectSourceFiles(targetDir, { maxFiles });
|
|
1429
|
+
const allSymbols = [];
|
|
1430
|
+
const fileMap = new Map();
|
|
1431
|
+
|
|
1432
|
+
for (const relPath of files) {
|
|
1433
|
+
const fullPath = path.join(targetDir, relPath);
|
|
1434
|
+
const content = readBoundedFile(fullPath);
|
|
1435
|
+
if (content === null) {
|
|
1436
|
+
continue;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
const fileSymbols = parseFileSymbols(relPath, content);
|
|
1440
|
+
fileMap.set(relPath, {
|
|
1441
|
+
file: relPath,
|
|
1442
|
+
linesCount: content.split(/\r?\n/).length,
|
|
1443
|
+
symbols: fileSymbols,
|
|
1444
|
+
});
|
|
1445
|
+
for (const sym of fileSymbols) {
|
|
1446
|
+
allSymbols.push(sym);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
return {
|
|
1451
|
+
files,
|
|
1452
|
+
symbols: allSymbols,
|
|
1453
|
+
fileMap,
|
|
1454
|
+
[Symbol.iterator]() {
|
|
1455
|
+
return allSymbols[Symbol.iterator]();
|
|
1456
|
+
},
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
const MEMOREAL_RULE_CONTENT = `---
|
|
1461
|
+
name: memoreal-workflow
|
|
1462
|
+
description: Use Memoreal MCP tools for deterministic cross-session memory, belief revision, and code intelligence before grepping files blind
|
|
1463
|
+
alwaysApply: true
|
|
1464
|
+
---
|
|
1465
|
+
|
|
1466
|
+
memoreal-workflow:
|
|
1467
|
+
|
|
1468
|
+
- At the start of a coding session, call \`build_context\` with your project \`namespace\` and a concise task query (and \`health\` in parallel) to load prior architectural decisions, user rules, and active tasks into Memoreal.
|
|
1469
|
+
- Before grepping blind or assuming missing context, call \`recall_memories\`, \`search_code\`, or \`explain_code\`.
|
|
1470
|
+
- Persist durable architectural decisions, bug root causes, and user corrections with \`encode_memory\` (or \`batch_encode\` for multiple facts), rate recalled memories with \`feedback\`, and run \`consolidate\` at session wrap-up.
|
|
1471
|
+
`;
|
|
1472
|
+
|
|
1473
|
+
export async function bootstrapProjectContext({
|
|
1474
|
+
projectDir = process.cwd(),
|
|
1475
|
+
apiUrl,
|
|
1476
|
+
apiKey,
|
|
1477
|
+
namespace,
|
|
1478
|
+
fetchImpl = globalThis.fetch,
|
|
1479
|
+
writeIdeRules = false,
|
|
1480
|
+
} = {}) {
|
|
1481
|
+
const targetDir = path.resolve(projectDir);
|
|
1482
|
+
const nsInfo = resolveProjectNamespaceInfo(targetDir, namespace, {});
|
|
1483
|
+
const resolvedNamespace = nsInfo.namespace;
|
|
1484
|
+
const effectiveApiUrl = resolveEffectiveApiUrl(apiUrl);
|
|
1485
|
+
const effectiveApiKey = resolveEffectiveApiKey(apiKey, { apiUrl: effectiveApiUrl });
|
|
1486
|
+
|
|
1487
|
+
const headers = {
|
|
1488
|
+
'Content-Type': 'application/json',
|
|
1489
|
+
'X-Memoreal-Client-Version': MEMOREAL_CLIENT_VERSION,
|
|
1490
|
+
'User-Agent': `@kolivri/memoreal-mcp/${MEMOREAL_CLIENT_VERSION}`,
|
|
1491
|
+
};
|
|
1492
|
+
if (effectiveApiKey) {
|
|
1493
|
+
headers.Authorization = `Bearer ${effectiveApiKey}`;
|
|
1494
|
+
}
|
|
1495
|
+
if (!namespace && nsInfo.isCodeProject && nsInfo.legacyNamespace && nsInfo.legacyNamespace !== nsInfo.namespace) {
|
|
1496
|
+
headers['X-Memoreal-Legacy-Namespace'] = nsInfo.legacyNamespace;
|
|
1497
|
+
headers['X-Memoreal-Code-Project'] = '1';
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// 1. Import markdown documentation & rules
|
|
1501
|
+
const knownDocNames = new Set([
|
|
1502
|
+
'claude.md',
|
|
1503
|
+
'claude.local.md',
|
|
1504
|
+
'agents.md',
|
|
1505
|
+
'readme.md',
|
|
1506
|
+
'.cursorrules',
|
|
1507
|
+
'.windsurfrules',
|
|
1508
|
+
]);
|
|
1509
|
+
|
|
1510
|
+
const candidateDocs = [];
|
|
1511
|
+
try {
|
|
1512
|
+
const topEntries = fs.readdirSync(targetDir, { withFileTypes: true });
|
|
1513
|
+
for (const entry of topEntries) {
|
|
1514
|
+
if (entry.isFile() && knownDocNames.has(entry.name.toLowerCase())) {
|
|
1515
|
+
candidateDocs.push(entry.name);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
} catch {}
|
|
1519
|
+
|
|
1520
|
+
try {
|
|
1521
|
+
const claudeDir = path.join(targetDir, '.claude');
|
|
1522
|
+
if (fs.existsSync(claudeDir)) {
|
|
1523
|
+
const claudeEntries = fs.readdirSync(claudeDir, { withFileTypes: true });
|
|
1524
|
+
for (const entry of claudeEntries) {
|
|
1525
|
+
if (entry.isFile() && (entry.name.toLowerCase() === 'claude.md' || entry.name.toLowerCase() === 'claude.local.md')) {
|
|
1526
|
+
candidateDocs.push(path.join('.claude', entry.name).replace(/\\/g, '/'));
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
} catch {}
|
|
1531
|
+
|
|
1532
|
+
if (candidateDocs.length === 0) {
|
|
1533
|
+
const fallbackList = ['CLAUDE.md', 'AGENTS.md', '.cursorrules', '.windsurfrules', 'README.md', path.join('.claude', 'CLAUDE.md')];
|
|
1534
|
+
for (const fb of fallbackList) {
|
|
1535
|
+
if (fs.existsSync(path.join(targetDir, fb))) {
|
|
1536
|
+
candidateDocs.push(fb.replace(/\\/g, '/'));
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
function docPriority(name) {
|
|
1542
|
+
const base = path.basename(name).toLowerCase();
|
|
1543
|
+
const isNested = name.startsWith('.claude');
|
|
1544
|
+
if (base === 'claude.md') return isNested ? 2 : 1;
|
|
1545
|
+
if (base === 'claude.local.md') return isNested ? 4 : 3;
|
|
1546
|
+
if (base === 'agents.md') return 5;
|
|
1547
|
+
if (base === '.cursorrules') return 6;
|
|
1548
|
+
if (base === '.windsurfrules') return 7;
|
|
1549
|
+
if (base === 'readme.md') return 8;
|
|
1550
|
+
return 9;
|
|
1551
|
+
}
|
|
1552
|
+
candidateDocs.sort((a, b) => docPriority(a) - docPriority(b));
|
|
1553
|
+
|
|
1554
|
+
const seenRealPaths = new Set();
|
|
1555
|
+
const seenInodes = new Set();
|
|
1556
|
+
const validDocs = [];
|
|
1557
|
+
|
|
1558
|
+
for (const docFile of candidateDocs) {
|
|
1559
|
+
const fullDocPath = path.join(targetDir, docFile);
|
|
1560
|
+
if (!fs.existsSync(fullDocPath)) continue;
|
|
1561
|
+
|
|
1562
|
+
let st;
|
|
1563
|
+
try {
|
|
1564
|
+
st = fs.statSync(fullDocPath);
|
|
1565
|
+
if (!st.isFile()) continue;
|
|
1566
|
+
} catch {
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
let realKey;
|
|
1571
|
+
try {
|
|
1572
|
+
realKey = fs.realpathSync.native ? fs.realpathSync.native(fullDocPath) : fs.realpathSync(fullDocPath);
|
|
1573
|
+
} catch {
|
|
1574
|
+
try {
|
|
1575
|
+
realKey = fs.realpathSync(fullDocPath);
|
|
1576
|
+
} catch {
|
|
1577
|
+
realKey = path.resolve(fullDocPath).toLowerCase();
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
const normalizedKey = (process.platform === 'win32' || process.platform === 'darwin')
|
|
1582
|
+
? realKey.toLowerCase()
|
|
1583
|
+
: realKey;
|
|
1584
|
+
|
|
1585
|
+
if (seenRealPaths.has(normalizedKey)) {
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
if (st.ino && st.dev) {
|
|
1590
|
+
const inodeKey = `${st.dev}:${st.ino}`;
|
|
1591
|
+
if (seenInodes.has(inodeKey)) {
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
seenInodes.add(inodeKey);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
seenRealPaths.add(normalizedKey);
|
|
1598
|
+
validDocs.push({ docFile: docFile.replace(/\\/g, '/'), fullDocPath });
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
const importedDocs = [];
|
|
1602
|
+
|
|
1603
|
+
for (const doc of validDocs) {
|
|
1604
|
+
const content = readBoundedFile(doc.fullDocPath);
|
|
1605
|
+
if (!content || !content.trim()) continue;
|
|
1606
|
+
|
|
1607
|
+
try {
|
|
1608
|
+
const resp = await fetchImpl(`${effectiveApiUrl}/v1/memories/import`, {
|
|
1609
|
+
method: 'POST',
|
|
1610
|
+
headers,
|
|
1611
|
+
body: JSON.stringify({
|
|
1612
|
+
namespace: resolvedNamespace,
|
|
1613
|
+
content,
|
|
1614
|
+
type: 'semantic',
|
|
1615
|
+
}),
|
|
1616
|
+
});
|
|
1617
|
+
if (resp && resp.ok) {
|
|
1618
|
+
importedDocs.push(doc.docFile);
|
|
1619
|
+
}
|
|
1620
|
+
} catch {
|
|
1621
|
+
// Do not push on HTTP error or network failure
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
// 2. Scan code index (up to 40 files) and batch import symbols (capped at 150)
|
|
1626
|
+
const indexResult = scanProjectCodeIndex(targetDir, { maxFiles: 40 });
|
|
1627
|
+
const symbolMemories = indexResult.symbols.map(s => {
|
|
1628
|
+
let desc = `[code:${s.kind}] ${s.name} in ${s.file}:${s.startLine}-${s.endLine}`;
|
|
1629
|
+
if (s.implements && s.implements.length > 0) {
|
|
1630
|
+
desc += ` implements ${s.implements.join(', ')}`;
|
|
1631
|
+
}
|
|
1632
|
+
if (s.callees && s.callees.length > 0) {
|
|
1633
|
+
desc += ` calls: ${s.callees.slice(0, 10).join(', ')}`;
|
|
1634
|
+
}
|
|
1635
|
+
const ctx = [
|
|
1636
|
+
['file', s.file],
|
|
1637
|
+
['symbol', s.name],
|
|
1638
|
+
['kind', s.kind],
|
|
1639
|
+
['line', String(s.startLine)],
|
|
1640
|
+
['lines', `${s.startLine}-${s.endLine}`],
|
|
1641
|
+
];
|
|
1642
|
+
if (s.callees && s.callees.length > 0) {
|
|
1643
|
+
ctx.push(['calls', s.callees.slice(0, 10).join(',')]);
|
|
1644
|
+
}
|
|
1645
|
+
if (s.implements && s.implements.length > 0) {
|
|
1646
|
+
ctx.push(['implements', s.implements.join(',')]);
|
|
1647
|
+
}
|
|
1648
|
+
return {
|
|
1649
|
+
content: desc,
|
|
1650
|
+
type: 'semantic',
|
|
1651
|
+
salience: 0.7,
|
|
1652
|
+
context: ctx,
|
|
1653
|
+
};
|
|
1654
|
+
});
|
|
1655
|
+
|
|
1656
|
+
const batchMemories = symbolMemories.slice(0, 150);
|
|
1657
|
+
let batchOk = false;
|
|
1658
|
+
|
|
1659
|
+
if (batchMemories.length > 0) {
|
|
1660
|
+
try {
|
|
1661
|
+
const batchResp = await fetchImpl(`${effectiveApiUrl}/v1/memories/batch`, {
|
|
1662
|
+
method: 'POST',
|
|
1663
|
+
headers,
|
|
1664
|
+
body: JSON.stringify({
|
|
1665
|
+
namespace: resolvedNamespace,
|
|
1666
|
+
memories: batchMemories,
|
|
1667
|
+
}),
|
|
1668
|
+
});
|
|
1669
|
+
batchOk = Boolean(batchResp && batchResp.ok);
|
|
1670
|
+
} catch {
|
|
1671
|
+
batchOk = false;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
const symbolsIndexed = (batchMemories.length > 0 && batchOk) ? batchMemories.length : 0;
|
|
1676
|
+
|
|
1677
|
+
// 3. Write IDE rules if requested and .cursor directory exists
|
|
1678
|
+
let ideRulesWritten = false;
|
|
1679
|
+
if (writeIdeRules) {
|
|
1680
|
+
const cursorDir = path.join(targetDir, '.cursor');
|
|
1681
|
+
if (fs.existsSync(cursorDir)) {
|
|
1682
|
+
const rulesDir = path.join(cursorDir, 'rules');
|
|
1683
|
+
fs.mkdirSync(rulesDir, { recursive: true });
|
|
1684
|
+
const ruleFile = path.join(rulesDir, 'memoreal.mdc');
|
|
1685
|
+
if (fs.existsSync(ruleFile)) {
|
|
1686
|
+
const bakFile = ruleFile + '.bak';
|
|
1687
|
+
fs.copyFileSync(ruleFile, bakFile);
|
|
1688
|
+
}
|
|
1689
|
+
let ruleContent = MEMOREAL_RULE_CONTENT;
|
|
1690
|
+
try {
|
|
1691
|
+
const bundledRulePath = path.resolve(
|
|
1692
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
1693
|
+
'..',
|
|
1694
|
+
'rules',
|
|
1695
|
+
'memoreal.mdc'
|
|
1696
|
+
);
|
|
1697
|
+
if (fs.existsSync(bundledRulePath)) {
|
|
1698
|
+
ruleContent = fs.readFileSync(bundledRulePath, 'utf8');
|
|
1699
|
+
}
|
|
1700
|
+
} catch {}
|
|
1701
|
+
fs.writeFileSync(ruleFile, ruleContent, 'utf8');
|
|
1702
|
+
ideRulesWritten = true;
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
return {
|
|
1707
|
+
ok: true,
|
|
1708
|
+
success: true,
|
|
1709
|
+
bootstrapped: true,
|
|
1710
|
+
namespace: resolvedNamespace,
|
|
1711
|
+
...(nsInfo.legacyNamespace ? { legacyNamespace: nsInfo.legacyNamespace } : {}),
|
|
1712
|
+
docsImported: importedDocs,
|
|
1713
|
+
docs_imported: importedDocs.length,
|
|
1714
|
+
importedCount: importedDocs.length,
|
|
1715
|
+
symbolsIndexed,
|
|
1716
|
+
symbols_extracted: indexResult.symbols.length,
|
|
1717
|
+
totalSymbolsScanned: indexResult.symbols.length,
|
|
1718
|
+
filesScanned: indexResult.files.length,
|
|
1719
|
+
ideRulesWritten,
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
function isTestFile(filePath) {
|
|
1724
|
+
const normalized = filePath.replace(/\\/g, '/');
|
|
1725
|
+
const baseName = path.basename(normalized);
|
|
1726
|
+
const ext = path.extname(normalized).toLowerCase();
|
|
1727
|
+
|
|
1728
|
+
// Test directories
|
|
1729
|
+
if (
|
|
1730
|
+
normalized.startsWith('test/') ||
|
|
1731
|
+
normalized.startsWith('tests/') ||
|
|
1732
|
+
normalized.startsWith('spec/') ||
|
|
1733
|
+
normalized.includes('/test/') ||
|
|
1734
|
+
normalized.includes('/tests/') ||
|
|
1735
|
+
normalized.includes('/spec/') ||
|
|
1736
|
+
normalized.includes('__tests__/') ||
|
|
1737
|
+
normalized.includes('src/test/')
|
|
1738
|
+
) {
|
|
1739
|
+
return true;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// File naming patterns per language
|
|
1743
|
+
if (baseName.includes('.test.') || baseName.includes('.spec.')) {
|
|
1744
|
+
return true;
|
|
1745
|
+
}
|
|
1746
|
+
if (ext === '.go' && baseName.endsWith('_test.go')) {
|
|
1747
|
+
return true;
|
|
1748
|
+
}
|
|
1749
|
+
if ((ext === '.py' || ext === '.pyi') && (baseName.startsWith('test_') || baseName.endsWith('_test.py'))) {
|
|
1750
|
+
return true;
|
|
1751
|
+
}
|
|
1752
|
+
if (ext === '.java' && (baseName.endsWith('Test.java') || baseName.endsWith('Tests.java'))) {
|
|
1753
|
+
return true;
|
|
1754
|
+
}
|
|
1755
|
+
if ((ext === '.kt' || ext === '.kts') && (baseName.endsWith('Test.kt') || baseName.endsWith('Tests.kt') || baseName.endsWith('Spec.kt'))) {
|
|
1756
|
+
return true;
|
|
1757
|
+
}
|
|
1758
|
+
if (ext === '.scala' && (baseName.endsWith('Test.scala') || baseName.endsWith('Spec.scala'))) {
|
|
1759
|
+
return true;
|
|
1760
|
+
}
|
|
1761
|
+
if (ext === '.cs' && (baseName.endsWith('Test.cs') || baseName.endsWith('Tests.cs'))) {
|
|
1762
|
+
return true;
|
|
1763
|
+
}
|
|
1764
|
+
if (ext === '.rb' && (baseName.endsWith('_spec.rb') || baseName.endsWith('_test.rb'))) {
|
|
1765
|
+
return true;
|
|
1766
|
+
}
|
|
1767
|
+
if (ext === '.exs' && baseName.endsWith('_test.exs')) {
|
|
1768
|
+
return true;
|
|
1769
|
+
}
|
|
1770
|
+
if (ext === '.php' && baseName.endsWith('Test.php')) {
|
|
1771
|
+
return true;
|
|
1772
|
+
}
|
|
1773
|
+
if (ext === '.dart' && baseName.endsWith('_test.dart')) {
|
|
1774
|
+
return true;
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
return false;
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
function getCandidateTestPaths(relPath) {
|
|
1781
|
+
const ext = path.extname(relPath).toLowerCase();
|
|
1782
|
+
const baseName = path.basename(relPath, ext);
|
|
1783
|
+
const dirName = path.dirname(relPath);
|
|
1784
|
+
|
|
1785
|
+
const candidates = [];
|
|
1786
|
+
if (['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
|
|
1787
|
+
candidates.push(`test/${baseName}.test.mjs`);
|
|
1788
|
+
candidates.push(`test/${baseName}.test.js`);
|
|
1789
|
+
candidates.push(`test/${baseName}.test.ts`);
|
|
1790
|
+
candidates.push(`tests/${baseName}.test.js`);
|
|
1791
|
+
candidates.push(`tests/${baseName}.test.ts`);
|
|
1792
|
+
candidates.push(`${dirName}/${baseName}.test${ext}`);
|
|
1793
|
+
candidates.push(`${dirName}/${baseName}.spec${ext}`);
|
|
1794
|
+
} else if (ext === '.py' || ext === '.pyi') {
|
|
1795
|
+
candidates.push(`tests/test_${baseName}.py`);
|
|
1796
|
+
candidates.push(`test/test_${baseName}.py`);
|
|
1797
|
+
candidates.push(`${dirName}/test_${baseName}.py`);
|
|
1798
|
+
candidates.push(`${dirName}/${baseName}_test.py`);
|
|
1799
|
+
} else if (ext === '.go') {
|
|
1800
|
+
candidates.push(`${dirName}/${baseName}_test.go`);
|
|
1801
|
+
candidates.push(`test/${baseName}_test.go`);
|
|
1802
|
+
} else if (ext === '.rs') {
|
|
1803
|
+
candidates.push(`tests/${baseName}.rs`);
|
|
1804
|
+
candidates.push(`tests/${baseName}_test.rs`);
|
|
1805
|
+
candidates.push(`test/${baseName}.rs`);
|
|
1806
|
+
} else if (ext === '.java') {
|
|
1807
|
+
candidates.push(`src/test/java/${baseName}Test.java`);
|
|
1808
|
+
candidates.push(`src/test/java/${baseName}Tests.java`);
|
|
1809
|
+
candidates.push(`test/${baseName}Test.java`);
|
|
1810
|
+
candidates.push(`tests/${baseName}Test.java`);
|
|
1811
|
+
} else if (ext === '.kt' || ext === '.kts') {
|
|
1812
|
+
candidates.push(`src/test/kotlin/${baseName}Test.kt`);
|
|
1813
|
+
candidates.push(`test/${baseName}Test.kt`);
|
|
1814
|
+
candidates.push(`test/${baseName}Spec.kt`);
|
|
1815
|
+
} else if (ext === '.scala') {
|
|
1816
|
+
candidates.push(`src/test/scala/${baseName}Spec.scala`);
|
|
1817
|
+
candidates.push(`test/${baseName}Spec.scala`);
|
|
1818
|
+
candidates.push(`test/${baseName}Test.scala`);
|
|
1819
|
+
} else if (ext === '.cs') {
|
|
1820
|
+
candidates.push(`tests/${baseName}Tests.cs`);
|
|
1821
|
+
candidates.push(`test/${baseName}Tests.cs`);
|
|
1822
|
+
candidates.push(`test/${baseName}Test.cs`);
|
|
1823
|
+
} else if (ext === '.rb') {
|
|
1824
|
+
candidates.push(`spec/${baseName}_spec.rb`);
|
|
1825
|
+
candidates.push(`test/${baseName}_test.rb`);
|
|
1826
|
+
} else if (ext === '.ex' || ext === '.exs') {
|
|
1827
|
+
candidates.push(`test/${baseName}_test.exs`);
|
|
1828
|
+
} else if (ext === '.php') {
|
|
1829
|
+
candidates.push(`tests/${baseName}Test.php`);
|
|
1830
|
+
candidates.push(`test/${baseName}Test.php`);
|
|
1831
|
+
} else if (ext === '.dart') {
|
|
1832
|
+
candidates.push(`test/${baseName}_test.dart`);
|
|
1833
|
+
} else {
|
|
1834
|
+
candidates.push(`test/${baseName}.test.js`);
|
|
1835
|
+
candidates.push(`test/${baseName}.test.mjs`);
|
|
1836
|
+
}
|
|
1837
|
+
return candidates;
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
function getIdiomaticMissingTestPath(relPath) {
|
|
1841
|
+
const ext = path.extname(relPath).toLowerCase();
|
|
1842
|
+
const baseName = path.basename(relPath, ext);
|
|
1843
|
+
const dirName = path.dirname(relPath);
|
|
1844
|
+
|
|
1845
|
+
if (['.js', '.mjs', '.cjs', '.jsx'].includes(ext)) {
|
|
1846
|
+
return `test/${baseName}.test.mjs`;
|
|
1847
|
+
}
|
|
1848
|
+
if (['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
|
|
1849
|
+
return `test/${baseName}.test.ts`;
|
|
1850
|
+
}
|
|
1851
|
+
if (ext === '.py' || ext === '.pyi') {
|
|
1852
|
+
return `tests/test_${baseName}.py`;
|
|
1853
|
+
}
|
|
1854
|
+
if (ext === '.go') {
|
|
1855
|
+
return `${dirName}/${baseName}_test.go`;
|
|
1856
|
+
}
|
|
1857
|
+
if (ext === '.rs') {
|
|
1858
|
+
return `tests/${baseName}_test.rs`;
|
|
1859
|
+
}
|
|
1860
|
+
if (ext === '.java') {
|
|
1861
|
+
return `src/test/java/${baseName}Test.java`;
|
|
1862
|
+
}
|
|
1863
|
+
if (ext === '.kt' || ext === '.kts') {
|
|
1864
|
+
return `test/${baseName}Test.kt`;
|
|
1865
|
+
}
|
|
1866
|
+
if (ext === '.scala') {
|
|
1867
|
+
return `test/${baseName}Spec.scala`;
|
|
1868
|
+
}
|
|
1869
|
+
if (ext === '.cs') {
|
|
1870
|
+
return `tests/${baseName}Tests.cs`;
|
|
1871
|
+
}
|
|
1872
|
+
if (ext === '.rb') {
|
|
1873
|
+
return `spec/${baseName}_spec.rb`;
|
|
1874
|
+
}
|
|
1875
|
+
if (ext === '.ex' || ext === '.exs') {
|
|
1876
|
+
return `test/${baseName}_test.exs`;
|
|
1877
|
+
}
|
|
1878
|
+
if (ext === '.php') {
|
|
1879
|
+
return `tests/${baseName}Test.php`;
|
|
1880
|
+
}
|
|
1881
|
+
if (ext === '.dart') {
|
|
1882
|
+
return `test/${baseName}_test.dart`;
|
|
1883
|
+
}
|
|
1884
|
+
return `test/${baseName}.test.mjs`;
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
function extractStackFrames(text) {
|
|
1888
|
+
if (typeof text !== 'string') return [];
|
|
1889
|
+
const bounded = boundContent(String(text || ''));
|
|
1890
|
+
const frames = [];
|
|
1891
|
+
const seen = new Set();
|
|
1892
|
+
|
|
1893
|
+
function addFrame(file, lineStr) {
|
|
1894
|
+
const line = parseInt(lineStr, 10);
|
|
1895
|
+
if (!file || isNaN(line) || line <= 0) return;
|
|
1896
|
+
const cleanFile = file.trim().replace(/^["']|["']$/g, '');
|
|
1897
|
+
const key = `${cleanFile}:${line}`;
|
|
1898
|
+
if (!seen.has(key)) {
|
|
1899
|
+
seen.add(key);
|
|
1900
|
+
frames.push({ file: cleanFile, line });
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
const extList = 'js|mjs|cjs|jsx|ts|mts|cts|tsx|py|pyi|rs|go|java|kt|kts|scala|cs|c|h|cpp|cc|cxx|hpp|hh|hxx|swift|dart|php|rb|ex|exs|lua|sh|sql';
|
|
1905
|
+
const genRe = new RegExp(`(?<![\\w./\\\\-])([\\w./\\\\-]+\\.(?:${extList})):(\\d+)(?::\\d+)?`, 'i');
|
|
1906
|
+
|
|
1907
|
+
const rawLines = bounded.split(/\r?\n/);
|
|
1908
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
1909
|
+
const line = rawLines[i].slice(0, 2000);
|
|
1910
|
+
if (!line) continue;
|
|
1911
|
+
|
|
1912
|
+
// 1. Python: File "app.py", line 10
|
|
1913
|
+
const pyMatch = line.match(/File\s+"([^"]+)",\s+line\s+(\d+)/);
|
|
1914
|
+
if (pyMatch) {
|
|
1915
|
+
addFrame(pyMatch[1], pyMatch[2]);
|
|
1916
|
+
continue;
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
// 2. Java / Kotlin / Scala: (Cls.java:10)
|
|
1920
|
+
const jvmMatch = line.match(/\(([\w./\\-]+\.(?:java|kt|kts|scala)):(\d+)\)/);
|
|
1921
|
+
if (jvmMatch) {
|
|
1922
|
+
addFrame(jvmMatch[1], jvmMatch[2]);
|
|
1923
|
+
continue;
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
// 3. C#: in /path/File.cs:line 10
|
|
1927
|
+
const csMatch = line.match(/\bin\s+([^\r\n:]+?\.cs):line\s+(\d+)/i);
|
|
1928
|
+
if (csMatch) {
|
|
1929
|
+
addFrame(csMatch[1], csMatch[2]);
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// 4. PHP: File.php on line 10 OR File.php(10)
|
|
1934
|
+
const phpMatch = line.match(/(?<![\w./\\-])([\w./\\-]+\.php)(?:\s+on\s+line\s+(\d+)|\((\d+)\))/i);
|
|
1935
|
+
if (phpMatch) {
|
|
1936
|
+
addFrame(phpMatch[1], phpMatch[2] || phpMatch[3]);
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
// 5. Rust: at src/lib.rs:10:5 OR --> src/lib.rs:10:5
|
|
1941
|
+
const rustMatch = line.match(/(?:at\s+|-->\s+)([\w./\\-]+\.rs):(\d+)/);
|
|
1942
|
+
if (rustMatch) {
|
|
1943
|
+
addFrame(rustMatch[1], rustMatch[2]);
|
|
1944
|
+
continue;
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
// 6. Ruby: file.rb:10:in
|
|
1948
|
+
const rbMatch = line.match(/(?<![\w./\\-])([\w./\\-]+\.rb):(\d+):in\b/);
|
|
1949
|
+
if (rbMatch) {
|
|
1950
|
+
addFrame(rbMatch[1], rbMatch[2]);
|
|
1951
|
+
continue;
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
// 7. General V8 / Go / C / C++ / Swift: file.ext:line
|
|
1955
|
+
const genMatch = line.match(genRe);
|
|
1956
|
+
if (genMatch) {
|
|
1957
|
+
addFrame(genMatch[1], genMatch[2]);
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
return frames;
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
export function runLocalCodeIntelFallback(toolName, args = {}, projectDir = process.cwd()) {
|
|
1965
|
+
const targetDir = path.resolve(args.project_dir || args.path || projectDir);
|
|
1966
|
+
const index = scanProjectCodeIndex(targetDir, { maxFiles: 100 });
|
|
1967
|
+
|
|
1968
|
+
switch (toolName) {
|
|
1969
|
+
case 'find_file': {
|
|
1970
|
+
const rawQuery = (args.query || args.pattern || args.name || '').trim();
|
|
1971
|
+
const limit = Number(args.limit) > 0 ? Number(args.limit) : 20;
|
|
1972
|
+
const q = rawQuery.toLowerCase();
|
|
1973
|
+
let matches = [];
|
|
1974
|
+
if (!q) {
|
|
1975
|
+
matches = [...index.files];
|
|
1976
|
+
} else if (q.includes('*') || q.includes('?')) {
|
|
1977
|
+
matches = index.files.filter(f => {
|
|
1978
|
+
const fLower = f.toLowerCase();
|
|
1979
|
+
const baseLower = path.basename(f).toLowerCase();
|
|
1980
|
+
return wildcardMatch(fLower, q) || wildcardMatch(baseLower, q);
|
|
1981
|
+
});
|
|
1982
|
+
} else {
|
|
1983
|
+
matches = index.files.filter(f => f.toLowerCase().includes(q) || path.basename(f).toLowerCase().includes(q));
|
|
1984
|
+
}
|
|
1985
|
+
const limitedMatches = matches.slice(0, limit);
|
|
1986
|
+
const results = limitedMatches.map(f => ({
|
|
1987
|
+
file: f,
|
|
1988
|
+
path: f,
|
|
1989
|
+
name: path.basename(f),
|
|
1990
|
+
}));
|
|
1991
|
+
return {
|
|
1992
|
+
query: rawQuery,
|
|
1993
|
+
files: limitedMatches,
|
|
1994
|
+
matches: limitedMatches,
|
|
1995
|
+
results,
|
|
1996
|
+
total_matches: matches.length,
|
|
1997
|
+
total_candidates: matches.length,
|
|
1998
|
+
};
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
case 'find_references': {
|
|
2002
|
+
const target = (args.symbol || args.target || args.query || '').trim();
|
|
2003
|
+
const limit = Number(args.limit) > 0 ? Number(args.limit) : 50;
|
|
2004
|
+
if (!target) {
|
|
2005
|
+
return {
|
|
2006
|
+
symbol: '',
|
|
2007
|
+
target: '',
|
|
2008
|
+
references: [],
|
|
2009
|
+
count: 0,
|
|
2010
|
+
results: [],
|
|
2011
|
+
total_candidates: 0,
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
const references = [];
|
|
2015
|
+
const { testRe } = buildIdentifierRegex(target);
|
|
2016
|
+
|
|
2017
|
+
for (const relPath of index.files) {
|
|
2018
|
+
const full = path.join(targetDir, relPath);
|
|
2019
|
+
const content = readBoundedFile(full);
|
|
2020
|
+
if (!content) continue;
|
|
2021
|
+
const lines = content.split(/\r?\n/);
|
|
2022
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2023
|
+
if (testRe.test(lines[i])) {
|
|
2024
|
+
const lineTrim = lines[i].trim();
|
|
2025
|
+
references.push({
|
|
2026
|
+
file: relPath,
|
|
2027
|
+
line: i + 1,
|
|
2028
|
+
line_content: lineTrim,
|
|
2029
|
+
snippet: lineTrim,
|
|
2030
|
+
});
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
const limitedRefs = references.slice(0, limit);
|
|
2036
|
+
const results = limitedRefs.map(r => ({
|
|
2037
|
+
file: r.file,
|
|
2038
|
+
line: r.line,
|
|
2039
|
+
content: r.line_content,
|
|
2040
|
+
snippet: r.snippet,
|
|
2041
|
+
memory: { content: `${r.file}:${r.line}: ${r.line_content}` },
|
|
2042
|
+
}));
|
|
2043
|
+
|
|
2044
|
+
return {
|
|
2045
|
+
symbol: target,
|
|
2046
|
+
target,
|
|
2047
|
+
references: limitedRefs,
|
|
2048
|
+
count: limitedRefs.length,
|
|
2049
|
+
results,
|
|
2050
|
+
total_candidates: references.length,
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
case 'impact': {
|
|
2055
|
+
const target = (args.symbol || args.target || args.file || '').trim();
|
|
2056
|
+
const maxDepth = Number(args.max_depth) || 5;
|
|
2057
|
+
const limit = Number(args.limit) || 200;
|
|
2058
|
+
const affected = [];
|
|
2059
|
+
const directCallers = [];
|
|
2060
|
+
const affectedFiles = new Set();
|
|
2061
|
+
const visited = new Set();
|
|
2062
|
+
|
|
2063
|
+
if (target) {
|
|
2064
|
+
const queue = [[target, 0]];
|
|
2065
|
+
visited.add(target);
|
|
2066
|
+
|
|
2067
|
+
while (queue.length > 0 && affected.length < limit) {
|
|
2068
|
+
const [curr, depth] = queue.shift();
|
|
2069
|
+
if (depth >= maxDepth) continue;
|
|
2070
|
+
|
|
2071
|
+
for (const sym of index.symbols) {
|
|
2072
|
+
if (sym.callees && sym.callees.includes(curr)) {
|
|
2073
|
+
if (!visited.has(sym.name)) {
|
|
2074
|
+
visited.add(sym.name);
|
|
2075
|
+
const callerObj = {
|
|
2076
|
+
name: sym.name,
|
|
2077
|
+
file: sym.file,
|
|
2078
|
+
line: sym.startLine,
|
|
2079
|
+
kind: sym.kind,
|
|
2080
|
+
depth: depth + 1,
|
|
2081
|
+
confidence: Math.max(0.2, Number((1.0 - (depth * 0.15)).toFixed(2))),
|
|
2082
|
+
};
|
|
2083
|
+
if (depth === 0) {
|
|
2084
|
+
directCallers.push(callerObj);
|
|
2085
|
+
}
|
|
2086
|
+
affected.push(callerObj);
|
|
2087
|
+
affectedFiles.add(sym.file);
|
|
2088
|
+
queue.push([sym.name, depth + 1]);
|
|
2089
|
+
if (affected.length >= limit) break;
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
// Also check file name match
|
|
2096
|
+
for (const file of index.files) {
|
|
2097
|
+
if (file.includes(target)) {
|
|
2098
|
+
affectedFiles.add(file);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
const impactScore = affected.length * 10 + affectedFiles.size * 5;
|
|
2104
|
+
const riskLevel = impactScore > 40 ? 'high' : impactScore > 10 ? 'medium' : 'low';
|
|
2105
|
+
|
|
2106
|
+
return {
|
|
2107
|
+
symbol: target,
|
|
2108
|
+
target,
|
|
2109
|
+
affected,
|
|
2110
|
+
direct_callers: directCallers,
|
|
2111
|
+
affected_files: Array.from(affectedFiles),
|
|
2112
|
+
impact_score: impactScore,
|
|
2113
|
+
risk_level: riskLevel,
|
|
2114
|
+
results: affected,
|
|
2115
|
+
total_candidates: affected.length,
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
case 'call_tree': {
|
|
2120
|
+
const target = (args.symbol || args.target || '').trim();
|
|
2121
|
+
const direction = args.direction === 'out' ? 'out' : 'in';
|
|
2122
|
+
const maxDepth = Number(args.max_depth) || 5;
|
|
2123
|
+
|
|
2124
|
+
const visited = new Set();
|
|
2125
|
+
let nodeCount = 0;
|
|
2126
|
+
|
|
2127
|
+
function buildTree(currentName, depth) {
|
|
2128
|
+
if (depth > maxDepth || visited.has(currentName)) return null;
|
|
2129
|
+
visited.add(currentName);
|
|
2130
|
+
nodeCount++;
|
|
2131
|
+
|
|
2132
|
+
const node = {
|
|
2133
|
+
name: currentName,
|
|
2134
|
+
depth,
|
|
2135
|
+
children: [],
|
|
2136
|
+
};
|
|
2137
|
+
|
|
2138
|
+
if (direction === 'out') {
|
|
2139
|
+
// Outgoing calls: what does currentName call?
|
|
2140
|
+
const matchSym = index.symbols.find(s => s.name === currentName);
|
|
2141
|
+
if (matchSym && matchSym.callees) {
|
|
2142
|
+
for (const callee of matchSym.callees) {
|
|
2143
|
+
const child = buildTree(callee, depth + 1);
|
|
2144
|
+
if (child) node.children.push(child);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
} else {
|
|
2148
|
+
// Incoming calls: what calls currentName?
|
|
2149
|
+
const callers = index.symbols.filter(s => s.callees && s.callees.includes(currentName));
|
|
2150
|
+
for (const caller of callers) {
|
|
2151
|
+
const child = buildTree(caller.name, depth + 1);
|
|
2152
|
+
if (child) node.children.push(child);
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
visited.delete(currentName);
|
|
2157
|
+
return node;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
const tree = target ? buildTree(target, 1) : null;
|
|
2161
|
+
const resolvedTree = tree || { name: target || 'none', depth: 0, children: [] };
|
|
2162
|
+
return {
|
|
2163
|
+
symbol: target,
|
|
2164
|
+
target,
|
|
2165
|
+
direction,
|
|
2166
|
+
max_depth: maxDepth,
|
|
2167
|
+
tree: resolvedTree,
|
|
2168
|
+
total_nodes: nodeCount,
|
|
2169
|
+
results: tree ? [tree] : [],
|
|
2170
|
+
total_candidates: nodeCount,
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
case 'navigate': {
|
|
2175
|
+
const target = (args.symbol || args.target || '').trim();
|
|
2176
|
+
const cursor = (args.cursor || '').trim();
|
|
2177
|
+
const destination = args.destination || 'definition';
|
|
2178
|
+
const maxChildren = Number(args.max_children) || 40;
|
|
2179
|
+
const locations = [];
|
|
2180
|
+
|
|
2181
|
+
if (target) {
|
|
2182
|
+
if (destination === 'references') {
|
|
2183
|
+
const refResult = runLocalCodeIntelFallback('find_references', { target }, targetDir);
|
|
2184
|
+
for (const ref of refResult.references) {
|
|
2185
|
+
locations.push({
|
|
2186
|
+
id: `ref:${ref.file}:${ref.line}`,
|
|
2187
|
+
file: ref.file,
|
|
2188
|
+
line: ref.line,
|
|
2189
|
+
kind: 'reference',
|
|
2190
|
+
snippet: ref.snippet || ref.line_content,
|
|
2191
|
+
});
|
|
2192
|
+
}
|
|
2193
|
+
} else {
|
|
2194
|
+
const matching = index.symbols.filter(s => s.name === target || s.name.toLowerCase() === target.toLowerCase());
|
|
2195
|
+
for (const m of matching) {
|
|
2196
|
+
locations.push({
|
|
2197
|
+
id: `symbol:${m.file}:${m.startLine}`,
|
|
2198
|
+
name: m.name,
|
|
2199
|
+
file: m.file,
|
|
2200
|
+
line: m.startLine,
|
|
2201
|
+
end_line: m.endLine,
|
|
2202
|
+
kind: m.kind,
|
|
2203
|
+
signature: m.signature,
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
const nodeName = target || path.basename(targetDir);
|
|
2210
|
+
const node = {
|
|
2211
|
+
id: cursor || target || 'root',
|
|
2212
|
+
kind: target ? 'symbol' : 'project',
|
|
2213
|
+
name: nodeName,
|
|
2214
|
+
};
|
|
2215
|
+
|
|
2216
|
+
const children = locations.length > 0
|
|
2217
|
+
? locations.slice(0, maxChildren)
|
|
2218
|
+
: index.files.slice(0, maxChildren).map(f => ({ id: `file:${f}`, kind: 'file', path: f }));
|
|
2219
|
+
|
|
2220
|
+
return {
|
|
2221
|
+
target,
|
|
2222
|
+
symbol: target,
|
|
2223
|
+
cursor,
|
|
2224
|
+
destination,
|
|
2225
|
+
node,
|
|
2226
|
+
children,
|
|
2227
|
+
locations,
|
|
2228
|
+
results: locations.length > 0 ? locations : children,
|
|
2229
|
+
total_candidates: locations.length > 0 ? locations.length : children.length,
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
case 'get_hierarchy': {
|
|
2234
|
+
const target = (args.node || args.target || args.symbol || args.class || '').trim();
|
|
2235
|
+
const maxChildren = Number(args.max_children) || 40;
|
|
2236
|
+
const matchingSym = index.symbols.find(s => s.name === target);
|
|
2237
|
+
const supertypes = matchingSym && matchingSym.implements ? [...matchingSym.implements] : [];
|
|
2238
|
+
if (matchingSym && matchingSym.extends) {
|
|
2239
|
+
supertypes.unshift(matchingSym.extends);
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
const subtypes = [];
|
|
2243
|
+
for (const sym of index.symbols) {
|
|
2244
|
+
if (sym.name !== target) {
|
|
2245
|
+
if (sym.implements && sym.implements.includes(target)) {
|
|
2246
|
+
subtypes.push({ name: sym.name, file: sym.file, relation: 'implements', kind: sym.kind });
|
|
2247
|
+
} else if (sym.extends === target) {
|
|
2248
|
+
subtypes.push({ name: sym.name, file: sym.file, relation: 'extends', kind: sym.kind });
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
const ancestors = [
|
|
2254
|
+
{ id: 'project:root', kind: 'project', name: path.basename(targetDir) },
|
|
2255
|
+
];
|
|
2256
|
+
if (matchingSym) {
|
|
2257
|
+
ancestors.push({ id: `file:${matchingSym.file}`, kind: 'file', path: matchingSym.file });
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
let descendants = [];
|
|
2261
|
+
if (subtypes.length > 0) {
|
|
2262
|
+
descendants = subtypes.map(s => ({
|
|
2263
|
+
id: `symbol:${s.name}`,
|
|
2264
|
+
name: s.name,
|
|
2265
|
+
kind: s.kind || 'symbol',
|
|
2266
|
+
file: s.file,
|
|
2267
|
+
relation: s.relation,
|
|
2268
|
+
}));
|
|
2269
|
+
} else if (matchingSym) {
|
|
2270
|
+
const fileEntry = index.fileMap.get(matchingSym.file);
|
|
2271
|
+
if (fileEntry && fileEntry.symbols) {
|
|
2272
|
+
descendants = fileEntry.symbols
|
|
2273
|
+
.filter(s => s.name !== target)
|
|
2274
|
+
.map(s => ({ id: `symbol:${s.name}`, name: s.name, kind: s.kind, file: s.file }));
|
|
2275
|
+
}
|
|
2276
|
+
} else if (target && index.files.includes(target)) {
|
|
2277
|
+
const fileEntry = index.fileMap.get(target);
|
|
2278
|
+
if (fileEntry && fileEntry.symbols) {
|
|
2279
|
+
descendants = fileEntry.symbols.map(s => ({
|
|
2280
|
+
id: `symbol:${s.name}`,
|
|
2281
|
+
name: s.name,
|
|
2282
|
+
kind: s.kind,
|
|
2283
|
+
file: s.file,
|
|
2284
|
+
}));
|
|
2285
|
+
}
|
|
2286
|
+
} else {
|
|
2287
|
+
descendants = index.symbols.map(s => ({
|
|
2288
|
+
id: `symbol:${s.name}`,
|
|
2289
|
+
name: s.name,
|
|
2290
|
+
kind: s.kind,
|
|
2291
|
+
file: s.file,
|
|
2292
|
+
}));
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
const descendantsTotal = descendants.length;
|
|
2296
|
+
const limitedDescendants = descendants.slice(0, maxChildren);
|
|
2297
|
+
|
|
2298
|
+
return {
|
|
2299
|
+
node: target,
|
|
2300
|
+
target,
|
|
2301
|
+
symbol: target,
|
|
2302
|
+
ancestors,
|
|
2303
|
+
descendants: limitedDescendants,
|
|
2304
|
+
descendants_total: descendantsTotal,
|
|
2305
|
+
supertypes,
|
|
2306
|
+
subtypes,
|
|
2307
|
+
implements: matchingSym?.implements || [],
|
|
2308
|
+
hierarchy: {
|
|
2309
|
+
name: target,
|
|
2310
|
+
supertypes,
|
|
2311
|
+
subtypes,
|
|
2312
|
+
},
|
|
2313
|
+
results: [...supertypes, ...subtypes.map(s => s.name)],
|
|
2314
|
+
total_candidates: supertypes.length + subtypes.length,
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
case 'implementors': {
|
|
2319
|
+
const target = (args.symbol || args.interface_name || args.trait || args.target || args.interface || '').trim();
|
|
2320
|
+
const implementors = [];
|
|
2321
|
+
|
|
2322
|
+
function matchesTrait(implName, searchTarget) {
|
|
2323
|
+
if (!implName || !searchTarget) return false;
|
|
2324
|
+
if (implName === searchTarget) return true;
|
|
2325
|
+
if (implName.endsWith(`::${searchTarget}`) || implName.endsWith(`.${searchTarget}`)) return true;
|
|
2326
|
+
const bareImpl = implName.split(/[.:]/).pop();
|
|
2327
|
+
const bareTarget = searchTarget.split(/[.:]/).pop();
|
|
2328
|
+
return bareImpl === bareTarget;
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
if (target) {
|
|
2332
|
+
for (const sym of index.symbols) {
|
|
2333
|
+
const allTraits = [...(sym.implements || [])];
|
|
2334
|
+
if (sym.extends && (sym.kind === 'class' || sym.kind === 'struct' || sym.kind === 'interface')) {
|
|
2335
|
+
allTraits.push(sym.extends);
|
|
2336
|
+
}
|
|
2337
|
+
if (allTraits.some(trait => matchesTrait(trait, target))) {
|
|
2338
|
+
implementors.push({
|
|
2339
|
+
name: sym.name,
|
|
2340
|
+
file: sym.file,
|
|
2341
|
+
line: sym.startLine,
|
|
2342
|
+
kind: sym.kind,
|
|
2343
|
+
signature: sym.signature,
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
return {
|
|
2350
|
+
symbol: target,
|
|
2351
|
+
target,
|
|
2352
|
+
implementors,
|
|
2353
|
+
count: implementors.length,
|
|
2354
|
+
results: implementors,
|
|
2355
|
+
total_candidates: implementors.length,
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
case 'dead_code': {
|
|
2360
|
+
const limit = Number(args.limit) || 200;
|
|
2361
|
+
const unusedSymbols = [];
|
|
2362
|
+
for (const sym of index.symbols) {
|
|
2363
|
+
// Skip common entrypoints
|
|
2364
|
+
if (sym.file.includes('server') || sym.file.includes('index') || sym.file.includes('main')) {
|
|
2365
|
+
continue;
|
|
2366
|
+
}
|
|
2367
|
+
let called = false;
|
|
2368
|
+
for (const other of index.symbols) {
|
|
2369
|
+
if (other !== sym && other.callees && other.callees.includes(sym.name)) {
|
|
2370
|
+
called = true;
|
|
2371
|
+
break;
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
if (!called) {
|
|
2375
|
+
unusedSymbols.push({
|
|
2376
|
+
name: sym.name,
|
|
2377
|
+
file: sym.file,
|
|
2378
|
+
line: sym.startLine,
|
|
2379
|
+
kind: sym.kind,
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
const limitedUnused = unusedSymbols.slice(0, limit);
|
|
2385
|
+
|
|
2386
|
+
return {
|
|
2387
|
+
candidates: limitedUnused,
|
|
2388
|
+
caveat: 'Static local reference scan; verify public exports and dynamic invocations before removal.',
|
|
2389
|
+
unused_symbols: limitedUnused,
|
|
2390
|
+
count: limitedUnused.length,
|
|
2391
|
+
results: limitedUnused,
|
|
2392
|
+
total_candidates: unusedSymbols.length,
|
|
2393
|
+
};
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
case 'test_gaps': {
|
|
2397
|
+
const limit = Number(args.limit) || 200;
|
|
2398
|
+
const uncoveredFiles = [];
|
|
2399
|
+
const missingTests = [];
|
|
2400
|
+
|
|
2401
|
+
const testFiles = index.files.filter(f => isTestFile(f));
|
|
2402
|
+
const testReferencedSymbols = new Set();
|
|
2403
|
+
for (const tf of testFiles) {
|
|
2404
|
+
const fileEntry = index.fileMap.get(tf);
|
|
2405
|
+
if (fileEntry && fileEntry.symbols) {
|
|
2406
|
+
for (const s of fileEntry.symbols) {
|
|
2407
|
+
if (s.callees) {
|
|
2408
|
+
for (const c of s.callees) testReferencedSymbols.add(c);
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
for (const relPath of index.files) {
|
|
2415
|
+
if (isTestFile(relPath)) {
|
|
2416
|
+
continue;
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
const ext = path.extname(relPath).toLowerCase();
|
|
2420
|
+
const fullSourcePath = path.join(targetDir, relPath);
|
|
2421
|
+
const content = readBoundedFile(fullSourcePath);
|
|
2422
|
+
|
|
2423
|
+
// Rust inline tests #[cfg(test)] or mod tests
|
|
2424
|
+
if (ext === '.rs' && content && (/#\[cfg\(test\)\]/.test(content) || /\bmod\s+tests\b/.test(content))) {
|
|
2425
|
+
continue;
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
const candidates = getCandidateTestPaths(relPath);
|
|
2429
|
+
let hasTest = candidates.some(c => fs.existsSync(path.join(targetDir, c)) || index.files.includes(c));
|
|
2430
|
+
|
|
2431
|
+
if (!hasTest) {
|
|
2432
|
+
const fileEntry = index.fileMap.get(relPath);
|
|
2433
|
+
if (fileEntry && fileEntry.symbols && fileEntry.symbols.length > 0) {
|
|
2434
|
+
for (const sym of fileEntry.symbols) {
|
|
2435
|
+
if (testReferencedSymbols.has(sym.name)) {
|
|
2436
|
+
hasTest = true;
|
|
2437
|
+
break;
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
if (!hasTest) {
|
|
2444
|
+
uncoveredFiles.push(relPath);
|
|
2445
|
+
missingTests.push(getIdiomaticMissingTestPath(relPath));
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
const limitedFiles = uncoveredFiles.slice(0, limit);
|
|
2450
|
+
const gaps = limitedFiles.map(f => ({ file: f, path: f, name: path.basename(f) }));
|
|
2451
|
+
|
|
2452
|
+
return {
|
|
2453
|
+
gaps,
|
|
2454
|
+
total_gaps: uncoveredFiles.length,
|
|
2455
|
+
uncovered_files: limitedFiles,
|
|
2456
|
+
missing_tests: missingTests.slice(0, limit),
|
|
2457
|
+
gap_count: uncoveredFiles.length,
|
|
2458
|
+
results: limitedFiles,
|
|
2459
|
+
total_candidates: uncoveredFiles.length,
|
|
2460
|
+
};
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
case 'diff_risk': {
|
|
2464
|
+
let diffText = String(args.diff || args.patch || '');
|
|
2465
|
+
const changedItems = Array.isArray(args.changed) ? args.changed : [];
|
|
2466
|
+
|
|
2467
|
+
if (!diffText && changedItems.length === 0) {
|
|
2468
|
+
try {
|
|
2469
|
+
diffText = execFileSync('git', ['-C', targetDir, 'diff', 'HEAD'], {
|
|
2470
|
+
encoding: 'utf8',
|
|
2471
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
2472
|
+
});
|
|
2473
|
+
} catch {}
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
let additions = 0;
|
|
2477
|
+
let deletions = 0;
|
|
2478
|
+
let touchesSignatures = false;
|
|
2479
|
+
const modifiedSymbols = [];
|
|
2480
|
+
const risks = [];
|
|
2481
|
+
const sigRe = /\b(?:function|class|def|defp|defmodule|defprotocol|defimpl|fn|func|fun|interface|struct|trait|enum|record|protocol|actor|extension|module)\b/;
|
|
2482
|
+
const symSigRe = /\b(?:function|class|def|defp|defmodule|defprotocol|defimpl|fn|func|fun|interface|struct|trait|enum|record|protocol|actor|extension|module)\s+([a-zA-Z_$][\w$]*[?!]?)/;
|
|
2483
|
+
|
|
2484
|
+
if (diffText) {
|
|
2485
|
+
const diffLines = diffText.split(/\r?\n/);
|
|
2486
|
+
for (const dl of diffLines) {
|
|
2487
|
+
if (dl.startsWith('+') && !dl.startsWith('+++')) {
|
|
2488
|
+
additions++;
|
|
2489
|
+
if (sigRe.test(dl)) {
|
|
2490
|
+
touchesSignatures = true;
|
|
2491
|
+
const symMatch = dl.match(symSigRe);
|
|
2492
|
+
if (symMatch && !modifiedSymbols.includes(symMatch[1])) {
|
|
2493
|
+
modifiedSymbols.push(symMatch[1]);
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
} else if (dl.startsWith('-') && !dl.startsWith('---')) {
|
|
2497
|
+
deletions++;
|
|
2498
|
+
if (sigRe.test(dl)) {
|
|
2499
|
+
touchesSignatures = true;
|
|
2500
|
+
const symMatch = dl.match(symSigRe);
|
|
2501
|
+
if (symMatch && !modifiedSymbols.includes(symMatch[1])) {
|
|
2502
|
+
modifiedSymbols.push(symMatch[1]);
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
|
|
2509
|
+
// Check callers for changedItems or modifiedSymbols
|
|
2510
|
+
const itemsToCheck = Array.from(new Set([...changedItems, ...modifiedSymbols]));
|
|
2511
|
+
for (const item of itemsToCheck) {
|
|
2512
|
+
const callers = index.symbols.filter(s => s.callees && s.callees.includes(item));
|
|
2513
|
+
for (const c of callers) {
|
|
2514
|
+
risks.push({
|
|
2515
|
+
symbol: c.name,
|
|
2516
|
+
file: c.file,
|
|
2517
|
+
line: c.startLine,
|
|
2518
|
+
target: item,
|
|
2519
|
+
risk: 'medium',
|
|
2520
|
+
reason: `Calls modified symbol ${item}`,
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
if (callers.length === 0) {
|
|
2524
|
+
risks.push({
|
|
2525
|
+
target: item,
|
|
2526
|
+
file: item,
|
|
2527
|
+
risk: 'low',
|
|
2528
|
+
reason: 'Modified definition or changed file',
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
const riskScore = additions + deletions + (touchesSignatures ? 30 : 0) + (changedItems.length * 10);
|
|
2534
|
+
const riskLevel = riskScore > 100 ? 'high' : riskScore > 30 ? 'medium' : 'low';
|
|
2535
|
+
const breakingChangeRisk = touchesSignatures || deletions > 50;
|
|
2536
|
+
|
|
2537
|
+
if (risks.length === 0) {
|
|
2538
|
+
risks.push({
|
|
2539
|
+
target: 'workspace',
|
|
2540
|
+
risk_level: riskLevel,
|
|
2541
|
+
risk_score: riskScore,
|
|
2542
|
+
risk: riskLevel,
|
|
2543
|
+
reason: `Evaluated diff (+${additions}/-${deletions})`,
|
|
2544
|
+
});
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
const summary = `Diff evaluated as ${riskLevel} risk (score ${riskScore}, +${additions}/-${deletions}, ${risks.length} at-risk items)`;
|
|
2548
|
+
|
|
2549
|
+
return {
|
|
2550
|
+
risks,
|
|
2551
|
+
summary,
|
|
2552
|
+
risk_level: riskLevel,
|
|
2553
|
+
risk_score: riskScore,
|
|
2554
|
+
additions,
|
|
2555
|
+
deletions,
|
|
2556
|
+
modified_symbols: modifiedSymbols,
|
|
2557
|
+
breaking_change_risk: breakingChangeRisk,
|
|
2558
|
+
results: risks,
|
|
2559
|
+
total_candidates: risks.length,
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
case 'downstream_effects': {
|
|
2564
|
+
const target = (args.id || args.target || args.symbol || args.file || '').trim();
|
|
2565
|
+
const downstreamSymbols = [];
|
|
2566
|
+
const affectedModules = new Set();
|
|
2567
|
+
const affectedTests = [];
|
|
2568
|
+
|
|
2569
|
+
if (target) {
|
|
2570
|
+
for (const sym of index.symbols) {
|
|
2571
|
+
if (sym.callees && sym.callees.includes(target)) {
|
|
2572
|
+
downstreamSymbols.push({
|
|
2573
|
+
name: sym.name,
|
|
2574
|
+
file: sym.file,
|
|
2575
|
+
line: sym.startLine,
|
|
2576
|
+
kind: sym.kind,
|
|
2577
|
+
});
|
|
2578
|
+
affectedModules.add(sym.file);
|
|
2579
|
+
if (sym.file.includes('test')) {
|
|
2580
|
+
affectedTests.push(sym.file);
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
const effects = downstreamSymbols.map(s => ({
|
|
2587
|
+
id: `effect:${s.name}`,
|
|
2588
|
+
name: s.name,
|
|
2589
|
+
file: s.file,
|
|
2590
|
+
line: s.line,
|
|
2591
|
+
kind: s.kind || 'symbol',
|
|
2592
|
+
}));
|
|
2593
|
+
|
|
2594
|
+
const depthReached = downstreamSymbols.length > 0 ? 1 : 0;
|
|
2595
|
+
|
|
2596
|
+
return {
|
|
2597
|
+
id: target,
|
|
2598
|
+
target,
|
|
2599
|
+
symbol: target,
|
|
2600
|
+
effects,
|
|
2601
|
+
depth_reached: depthReached,
|
|
2602
|
+
downstream_symbols: downstreamSymbols,
|
|
2603
|
+
affected_modules: Array.from(affectedModules),
|
|
2604
|
+
affected_tests: affectedTests,
|
|
2605
|
+
results: downstreamSymbols,
|
|
2606
|
+
total_candidates: downstreamSymbols.length,
|
|
2607
|
+
};
|
|
2608
|
+
}
|
|
2609
|
+
|
|
2610
|
+
case 'root_cause': {
|
|
2611
|
+
const errorText = String(args.id || args.error || args.trace || args.message || args.symbol || '');
|
|
2612
|
+
const potentialCauses = [];
|
|
2613
|
+
const matchedFiles = [];
|
|
2614
|
+
|
|
2615
|
+
const frames = extractStackFrames(errorText);
|
|
2616
|
+
for (const frame of frames) {
|
|
2617
|
+
matchedFiles.push(frame.file);
|
|
2618
|
+
potentialCauses.push({
|
|
2619
|
+
file: frame.file,
|
|
2620
|
+
line: frame.line,
|
|
2621
|
+
snippet: `Frame match at ${frame.file}:${frame.line}`,
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
const causes = potentialCauses.map((c, idx) => ({
|
|
2626
|
+
id: `cause:${idx + 1}`,
|
|
2627
|
+
file: c.file,
|
|
2628
|
+
line: c.line,
|
|
2629
|
+
description: c.snippet,
|
|
2630
|
+
snippet: c.snippet,
|
|
2631
|
+
}));
|
|
2632
|
+
|
|
2633
|
+
const rootCauseId = causes.length > 0 ? causes[0].id : (errorText ? `root:${errorText.slice(0, 16)}` : null);
|
|
2634
|
+
|
|
2635
|
+
return {
|
|
2636
|
+
id: errorText,
|
|
2637
|
+
error: errorText,
|
|
2638
|
+
causes,
|
|
2639
|
+
root_cause_id: rootCauseId,
|
|
2640
|
+
potential_causes: potentialCauses,
|
|
2641
|
+
matched_files: Array.from(new Set(matchedFiles)),
|
|
2642
|
+
root_cause_hypotheses: potentialCauses.map(c => `Potential fault origin at ${c.file}:${c.line}`),
|
|
2643
|
+
results: potentialCauses,
|
|
2644
|
+
total_candidates: potentialCauses.length,
|
|
2645
|
+
};
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
case 'trace_provenance': {
|
|
2649
|
+
const target = (args.id || args.target || args.symbol || args.file || '').trim();
|
|
2650
|
+
const originSymbol = index.symbols.find(s => s.name === target);
|
|
2651
|
+
const history = [];
|
|
2652
|
+
|
|
2653
|
+
if (originSymbol) {
|
|
2654
|
+
history.push({
|
|
2655
|
+
id: `origin:${originSymbol.name}`,
|
|
2656
|
+
action: 'defined',
|
|
2657
|
+
file: originSymbol.file,
|
|
2658
|
+
line: originSymbol.startLine,
|
|
2659
|
+
kind: originSymbol.kind,
|
|
2660
|
+
});
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
const chain = history.length > 0
|
|
2664
|
+
? [...history]
|
|
2665
|
+
: [{ id: `target:${target}`, action: 'referenced', file: null, line: null }];
|
|
2666
|
+
|
|
2667
|
+
const trustScore = originSymbol ? 1.0 : 0.5;
|
|
2668
|
+
|
|
2669
|
+
return {
|
|
2670
|
+
id: target,
|
|
2671
|
+
target,
|
|
2672
|
+
symbol: target,
|
|
2673
|
+
chain,
|
|
2674
|
+
trust_score: trustScore,
|
|
2675
|
+
origin_file: originSymbol?.file || null,
|
|
2676
|
+
definition_line: originSymbol?.startLine || null,
|
|
2677
|
+
history,
|
|
2678
|
+
provenance: {
|
|
2679
|
+
symbol: target,
|
|
2680
|
+
file: originSymbol?.file || null,
|
|
2681
|
+
line: originSymbol?.startLine || null,
|
|
2682
|
+
kind: originSymbol?.kind || null,
|
|
2683
|
+
},
|
|
2684
|
+
results: originSymbol ? [originSymbol] : [],
|
|
2685
|
+
total_candidates: originSymbol ? 1 : 0,
|
|
2686
|
+
};
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
case 'explain_diff': {
|
|
2690
|
+
let diffText = String(args.diff || args.patch || '');
|
|
2691
|
+
if (!diffText) {
|
|
2692
|
+
try {
|
|
2693
|
+
const gitArgs = args.staged ? ['diff', '--staged'] : ['diff', 'HEAD'];
|
|
2694
|
+
diffText = execFileSync('git', ['-C', targetDir, ...gitArgs], {
|
|
2695
|
+
encoding: 'utf8',
|
|
2696
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
2697
|
+
});
|
|
2698
|
+
} catch {}
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
const filesChanged = [];
|
|
2702
|
+
const modifiedSymbolNames = [];
|
|
2703
|
+
let additions = 0;
|
|
2704
|
+
let deletions = 0;
|
|
2705
|
+
const sigRe = /\b(?:function|class|def|defp|defmodule|defprotocol|defimpl|fn|func|fun|interface|struct|trait|enum|record|protocol|actor|extension|module)\s+([a-zA-Z_$][\w$]*[?!]?)/;
|
|
2706
|
+
|
|
2707
|
+
if (diffText) {
|
|
2708
|
+
const lines = diffText.split(/\r?\n/);
|
|
2709
|
+
for (const line of lines) {
|
|
2710
|
+
if (line.startsWith('diff --git')) {
|
|
2711
|
+
const m = line.match(/diff --git a\/(.*) b\/(.*)/);
|
|
2712
|
+
if (m && m[2]) filesChanged.push(m[2]);
|
|
2713
|
+
} else if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
2714
|
+
additions++;
|
|
2715
|
+
const fnMatch = line.match(sigRe);
|
|
2716
|
+
if (fnMatch && !modifiedSymbolNames.includes(fnMatch[1])) {
|
|
2717
|
+
modifiedSymbolNames.push(fnMatch[1]);
|
|
2718
|
+
}
|
|
2719
|
+
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
|
2720
|
+
deletions++;
|
|
2721
|
+
const fnMatch = line.match(sigRe);
|
|
2722
|
+
if (fnMatch && !modifiedSymbolNames.includes(fnMatch[1])) {
|
|
2723
|
+
modifiedSymbolNames.push(fnMatch[1]);
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
const summary = `${filesChanged.length} files changed, +${additions} insertions, -${deletions} deletions`;
|
|
2730
|
+
return {
|
|
2731
|
+
explanation: summary,
|
|
2732
|
+
impacted_symbols: modifiedSymbolNames,
|
|
2733
|
+
summary,
|
|
2734
|
+
files_changed: filesChanged,
|
|
2735
|
+
additions,
|
|
2736
|
+
deletions,
|
|
2737
|
+
results: filesChanged.map(f => ({ file: f })),
|
|
2738
|
+
total_candidates: filesChanged.length,
|
|
2739
|
+
};
|
|
2740
|
+
}
|
|
2741
|
+
|
|
2742
|
+
case 'explain_error': {
|
|
2743
|
+
const errorText = String(args.error || args.trace || args.message || '');
|
|
2744
|
+
let errorType = 'Error';
|
|
2745
|
+
let message = errorText;
|
|
2746
|
+
|
|
2747
|
+
const typeMatch = errorText.match(/^([A-Za-z0-9_.]+(?:Error|Exception)):\s*(.*)/m) || errorText.match(/^(panic):\s*(.*)/m);
|
|
2748
|
+
if (typeMatch) {
|
|
2749
|
+
errorType = typeMatch[1];
|
|
2750
|
+
message = typeMatch[2];
|
|
2751
|
+
}
|
|
2752
|
+
|
|
2753
|
+
let explanation = 'An error occurred during execution.';
|
|
2754
|
+
let recommendedFix = 'Inspect stack trace variables and verify input arguments.';
|
|
2755
|
+
|
|
2756
|
+
if (errorType === 'TypeError') {
|
|
2757
|
+
explanation = 'A value was not of the expected type or a null/undefined property was accessed.';
|
|
2758
|
+
recommendedFix = 'Add optional chaining (?.) or guard checks before property access.';
|
|
2759
|
+
} else if (errorType === 'ReferenceError') {
|
|
2760
|
+
explanation = 'An identifier was referenced that has not been declared or imported.';
|
|
2761
|
+
recommendedFix = 'Ensure the variable or function is defined and imported in the file.';
|
|
2762
|
+
} else if (errorType === 'SyntaxError') {
|
|
2763
|
+
explanation = 'The code contains invalid syntax preventing parsing or compilation.';
|
|
2764
|
+
recommendedFix = 'Check brackets, quotes, or trailing commas near the error location.';
|
|
2765
|
+
} else if (errorType.includes('NullPointer') || errorType.includes('NilPointer')) {
|
|
2766
|
+
explanation = 'A null/nil pointer reference was dereferenced.';
|
|
2767
|
+
recommendedFix = 'Add null/nil guard checks before dereferencing.';
|
|
2768
|
+
} else if (errorType.includes('KeyError') || errorType.includes('IndexOutOf') || errorType.includes('ArrayIndex')) {
|
|
2769
|
+
explanation = 'An invalid key or out-of-bounds index was accessed.';
|
|
2770
|
+
recommendedFix = 'Check collection bounds or verify key existence before accessing.';
|
|
2771
|
+
} else if (errorType.toLowerCase().includes('panic')) {
|
|
2772
|
+
explanation = 'A runtime panic halted program execution.';
|
|
2773
|
+
recommendedFix = 'Inspect failing assertion, unwrap call, or bounds check.';
|
|
2774
|
+
}
|
|
2775
|
+
|
|
2776
|
+
const frames = extractStackFrames(errorText);
|
|
2777
|
+
const matchedFrames = frames.map(f => `${f.file}:${f.line}`);
|
|
2778
|
+
if (matchedFrames.length > 0) {
|
|
2779
|
+
explanation += ` Failing frames detected: ${Array.from(new Set(matchedFrames)).join(', ')}.`;
|
|
2780
|
+
}
|
|
2781
|
+
|
|
2782
|
+
return {
|
|
2783
|
+
explanation,
|
|
2784
|
+
suggested_fix: recommendedFix,
|
|
2785
|
+
recommended_fix: recommendedFix,
|
|
2786
|
+
error_type: errorType,
|
|
2787
|
+
message,
|
|
2788
|
+
results: [{
|
|
2789
|
+
error_type: errorType,
|
|
2790
|
+
message,
|
|
2791
|
+
explanation,
|
|
2792
|
+
recommended_fix: recommendedFix,
|
|
2793
|
+
suggested_fix: recommendedFix,
|
|
2794
|
+
}],
|
|
2795
|
+
total_candidates: 1,
|
|
2796
|
+
};
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
case 'rename': {
|
|
2800
|
+
const oldName = (args.symbol || args.old_name || args.from || '').trim();
|
|
2801
|
+
const newName = (args.new_name || args.to || '').trim();
|
|
2802
|
+
const limit = Number(args.limit) > 0 ? Number(args.limit) : 200;
|
|
2803
|
+
const worklist = [];
|
|
2804
|
+
|
|
2805
|
+
const isValidOld = oldName && IDENTIFIER_REGEX.test(oldName);
|
|
2806
|
+
const isValidNew = newName && IDENTIFIER_REGEX.test(newName);
|
|
2807
|
+
|
|
2808
|
+
if (isValidOld && isValidNew) {
|
|
2809
|
+
const { testRe, replaceRe } = buildIdentifierRegex(oldName);
|
|
2810
|
+
|
|
2811
|
+
for (const relPath of index.files) {
|
|
2812
|
+
const full = path.join(targetDir, relPath);
|
|
2813
|
+
const content = readBoundedFile(full);
|
|
2814
|
+
if (!content) continue;
|
|
2815
|
+
const lines = content.split(/\r?\n/);
|
|
2816
|
+
|
|
2817
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2818
|
+
const line = lines[i];
|
|
2819
|
+
if (testRe.test(line)) {
|
|
2820
|
+
const replacement = line.replace(replaceRe, () => newName);
|
|
2821
|
+
worklist.push({
|
|
2822
|
+
file: relPath,
|
|
2823
|
+
line: i + 1,
|
|
2824
|
+
original: line,
|
|
2825
|
+
replacement,
|
|
2826
|
+
snippet: line.trim(),
|
|
2827
|
+
});
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
const limitedWorklist = worklist.slice(0, limit);
|
|
2834
|
+
|
|
2835
|
+
return {
|
|
2836
|
+
symbol: oldName,
|
|
2837
|
+
old_name: oldName,
|
|
2838
|
+
new_name: newName,
|
|
2839
|
+
dry_run: true,
|
|
2840
|
+
worklist: limitedWorklist,
|
|
2841
|
+
total_occurrences: worklist.length,
|
|
2842
|
+
results: limitedWorklist,
|
|
2843
|
+
total_candidates: worklist.length,
|
|
2844
|
+
};
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
default:
|
|
2848
|
+
throw new Error(`Unsupported code intelligence tool: ${toolName}`);
|
|
2849
|
+
}
|
|
2850
|
+
}
|