@grundy40/contextslice 0.0.0-stage → 0.3.1
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/LICENSE +21 -0
- package/README.md +104 -2
- package/bin/ctxslice-mcp.mjs +1104 -0
- package/bin/ctxslice.mjs +745 -0
- package/package.json +38 -4
package/bin/ctxslice.mjs
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ctxslice.mjs — Zero-Config Multi-Language Local AST Context Pre-Compiler (v0.3.1)
|
|
4
|
+
* Features: Multi-Language AST Extractors, State-Machine Brace Matcher, True Call Graph (BFS), TF-IDF, Directory Quota Cap
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
const CJK_RE = /[一-鿿-ゟ゠-ヿ가-]/;
|
|
10
|
+
const CJK_RUN_RE = new RegExp('[一-鿿-ゟ゠-ヿ가-]+', 'g');
|
|
11
|
+
const CJK_WORDS = {
|
|
12
|
+
"登": [
|
|
13
|
+
"login",
|
|
14
|
+
"auth",
|
|
15
|
+
"verify",
|
|
16
|
+
"signin"
|
|
17
|
+
],
|
|
18
|
+
"入": [
|
|
19
|
+
"login",
|
|
20
|
+
"enter",
|
|
21
|
+
"init"
|
|
22
|
+
],
|
|
23
|
+
"登录": [
|
|
24
|
+
"login",
|
|
25
|
+
"signin",
|
|
26
|
+
"auth"
|
|
27
|
+
],
|
|
28
|
+
"登入": [
|
|
29
|
+
"login",
|
|
30
|
+
"signin",
|
|
31
|
+
"auth"
|
|
32
|
+
],
|
|
33
|
+
"ログイン": [
|
|
34
|
+
"login",
|
|
35
|
+
"signin"
|
|
36
|
+
],
|
|
37
|
+
"로그인": [
|
|
38
|
+
"login",
|
|
39
|
+
"signin"
|
|
40
|
+
],
|
|
41
|
+
"认证": [
|
|
42
|
+
"auth",
|
|
43
|
+
"verify",
|
|
44
|
+
"authentication"
|
|
45
|
+
],
|
|
46
|
+
"認證": [
|
|
47
|
+
"auth",
|
|
48
|
+
"verify",
|
|
49
|
+
"authentication"
|
|
50
|
+
],
|
|
51
|
+
"認証": [
|
|
52
|
+
"auth",
|
|
53
|
+
"authentication"
|
|
54
|
+
],
|
|
55
|
+
"인증": [
|
|
56
|
+
"auth",
|
|
57
|
+
"authentication"
|
|
58
|
+
],
|
|
59
|
+
"验证": [
|
|
60
|
+
"verify",
|
|
61
|
+
"validate"
|
|
62
|
+
],
|
|
63
|
+
"驗證": [
|
|
64
|
+
"verify",
|
|
65
|
+
"validate"
|
|
66
|
+
],
|
|
67
|
+
"検証": [
|
|
68
|
+
"verify",
|
|
69
|
+
"validate"
|
|
70
|
+
],
|
|
71
|
+
"검증": [
|
|
72
|
+
"verify",
|
|
73
|
+
"validate"
|
|
74
|
+
],
|
|
75
|
+
"權限": [
|
|
76
|
+
"permission",
|
|
77
|
+
"role",
|
|
78
|
+
"authz"
|
|
79
|
+
],
|
|
80
|
+
"权限": [
|
|
81
|
+
"permission",
|
|
82
|
+
"role",
|
|
83
|
+
"authz"
|
|
84
|
+
],
|
|
85
|
+
"権限": [
|
|
86
|
+
"permission",
|
|
87
|
+
"role"
|
|
88
|
+
],
|
|
89
|
+
"권한": [
|
|
90
|
+
"permission",
|
|
91
|
+
"role"
|
|
92
|
+
],
|
|
93
|
+
"令牌": [
|
|
94
|
+
"token",
|
|
95
|
+
"jwt"
|
|
96
|
+
],
|
|
97
|
+
"權杖": [
|
|
98
|
+
"token",
|
|
99
|
+
"jwt"
|
|
100
|
+
],
|
|
101
|
+
"トークン": [
|
|
102
|
+
"token"
|
|
103
|
+
],
|
|
104
|
+
"토큰": [
|
|
105
|
+
"token"
|
|
106
|
+
],
|
|
107
|
+
"解析": [
|
|
108
|
+
"parse",
|
|
109
|
+
"analyze"
|
|
110
|
+
],
|
|
111
|
+
"解": [
|
|
112
|
+
"decode",
|
|
113
|
+
"parse"
|
|
114
|
+
],
|
|
115
|
+
"析": [
|
|
116
|
+
"analyze",
|
|
117
|
+
"parse"
|
|
118
|
+
],
|
|
119
|
+
"パース": [
|
|
120
|
+
"parse"
|
|
121
|
+
],
|
|
122
|
+
"파싱": [
|
|
123
|
+
"parse"
|
|
124
|
+
],
|
|
125
|
+
"数据": [
|
|
126
|
+
"data"
|
|
127
|
+
],
|
|
128
|
+
"數據": [
|
|
129
|
+
"data"
|
|
130
|
+
],
|
|
131
|
+
"データ": [
|
|
132
|
+
"data"
|
|
133
|
+
],
|
|
134
|
+
"데이터": [
|
|
135
|
+
"data"
|
|
136
|
+
],
|
|
137
|
+
"結構": [
|
|
138
|
+
"struct",
|
|
139
|
+
"structure"
|
|
140
|
+
],
|
|
141
|
+
"结构": [
|
|
142
|
+
"struct",
|
|
143
|
+
"structure"
|
|
144
|
+
],
|
|
145
|
+
"構造": [
|
|
146
|
+
"struct",
|
|
147
|
+
"structure"
|
|
148
|
+
],
|
|
149
|
+
"구조": [
|
|
150
|
+
"struct",
|
|
151
|
+
"structure"
|
|
152
|
+
],
|
|
153
|
+
"接口": [
|
|
154
|
+
"api",
|
|
155
|
+
"interface"
|
|
156
|
+
],
|
|
157
|
+
"介面": [
|
|
158
|
+
"api",
|
|
159
|
+
"interface"
|
|
160
|
+
],
|
|
161
|
+
"インターフェース": [
|
|
162
|
+
"interface",
|
|
163
|
+
"api"
|
|
164
|
+
],
|
|
165
|
+
"인터페이스": [
|
|
166
|
+
"interface",
|
|
167
|
+
"api"
|
|
168
|
+
],
|
|
169
|
+
"服务": [
|
|
170
|
+
"service"
|
|
171
|
+
],
|
|
172
|
+
"服務": [
|
|
173
|
+
"service"
|
|
174
|
+
],
|
|
175
|
+
"サービス": [
|
|
176
|
+
"service"
|
|
177
|
+
],
|
|
178
|
+
"서비스": [
|
|
179
|
+
"service"
|
|
180
|
+
],
|
|
181
|
+
"路由": [
|
|
182
|
+
"router",
|
|
183
|
+
"route"
|
|
184
|
+
],
|
|
185
|
+
"路徑": [
|
|
186
|
+
"path",
|
|
187
|
+
"route"
|
|
188
|
+
],
|
|
189
|
+
"路径": [
|
|
190
|
+
"path",
|
|
191
|
+
"route"
|
|
192
|
+
],
|
|
193
|
+
"ルート": [
|
|
194
|
+
"route",
|
|
195
|
+
"router"
|
|
196
|
+
],
|
|
197
|
+
"라우트": [
|
|
198
|
+
"route",
|
|
199
|
+
"router"
|
|
200
|
+
],
|
|
201
|
+
"數據庫": [
|
|
202
|
+
"database",
|
|
203
|
+
"db"
|
|
204
|
+
],
|
|
205
|
+
"数据库": [
|
|
206
|
+
"database",
|
|
207
|
+
"db"
|
|
208
|
+
],
|
|
209
|
+
"データベース": [
|
|
210
|
+
"database",
|
|
211
|
+
"db"
|
|
212
|
+
],
|
|
213
|
+
"데이터베이스": [
|
|
214
|
+
"database",
|
|
215
|
+
"db"
|
|
216
|
+
],
|
|
217
|
+
"緩存": [
|
|
218
|
+
"cache"
|
|
219
|
+
],
|
|
220
|
+
"缓存": [
|
|
221
|
+
"cache"
|
|
222
|
+
],
|
|
223
|
+
"キャッシュ": [
|
|
224
|
+
"cache"
|
|
225
|
+
],
|
|
226
|
+
"캐시": [
|
|
227
|
+
"cache"
|
|
228
|
+
],
|
|
229
|
+
"存儲": [
|
|
230
|
+
"store",
|
|
231
|
+
"storage"
|
|
232
|
+
],
|
|
233
|
+
"存储": [
|
|
234
|
+
"store",
|
|
235
|
+
"storage"
|
|
236
|
+
],
|
|
237
|
+
"ストレージ": [
|
|
238
|
+
"storage"
|
|
239
|
+
],
|
|
240
|
+
"스토리지": [
|
|
241
|
+
"storage"
|
|
242
|
+
],
|
|
243
|
+
"配置": [
|
|
244
|
+
"config",
|
|
245
|
+
"configuration"
|
|
246
|
+
],
|
|
247
|
+
"設定": [
|
|
248
|
+
"config",
|
|
249
|
+
"setup",
|
|
250
|
+
"setting"
|
|
251
|
+
],
|
|
252
|
+
"設定ファイル": [
|
|
253
|
+
"config"
|
|
254
|
+
],
|
|
255
|
+
"설정": [
|
|
256
|
+
"config",
|
|
257
|
+
"setting"
|
|
258
|
+
],
|
|
259
|
+
"環境": [
|
|
260
|
+
"env",
|
|
261
|
+
"environment"
|
|
262
|
+
],
|
|
263
|
+
"环境": [
|
|
264
|
+
"env",
|
|
265
|
+
"environment"
|
|
266
|
+
],
|
|
267
|
+
"환경": [
|
|
268
|
+
"env",
|
|
269
|
+
"environment"
|
|
270
|
+
],
|
|
271
|
+
"錯誤": [
|
|
272
|
+
"error",
|
|
273
|
+
"exception"
|
|
274
|
+
],
|
|
275
|
+
"错误": [
|
|
276
|
+
"error",
|
|
277
|
+
"exception"
|
|
278
|
+
],
|
|
279
|
+
"エラー": [
|
|
280
|
+
"error"
|
|
281
|
+
],
|
|
282
|
+
"에러": [
|
|
283
|
+
"error"
|
|
284
|
+
],
|
|
285
|
+
"異常": [
|
|
286
|
+
"exception",
|
|
287
|
+
"error"
|
|
288
|
+
],
|
|
289
|
+
"异常": [
|
|
290
|
+
"exception",
|
|
291
|
+
"error"
|
|
292
|
+
],
|
|
293
|
+
"日誌": [
|
|
294
|
+
"log",
|
|
295
|
+
"logger"
|
|
296
|
+
],
|
|
297
|
+
"日志": [
|
|
298
|
+
"log",
|
|
299
|
+
"logger"
|
|
300
|
+
],
|
|
301
|
+
"ログ": [
|
|
302
|
+
"log"
|
|
303
|
+
],
|
|
304
|
+
"로그": [
|
|
305
|
+
"log"
|
|
306
|
+
],
|
|
307
|
+
"調試": [
|
|
308
|
+
"debug"
|
|
309
|
+
],
|
|
310
|
+
"调试": [
|
|
311
|
+
"debug"
|
|
312
|
+
],
|
|
313
|
+
"デバッグ": [
|
|
314
|
+
"debug"
|
|
315
|
+
],
|
|
316
|
+
"디버그": [
|
|
317
|
+
"debug"
|
|
318
|
+
],
|
|
319
|
+
"測試": [
|
|
320
|
+
"test",
|
|
321
|
+
"spec"
|
|
322
|
+
],
|
|
323
|
+
"测试": [
|
|
324
|
+
"test",
|
|
325
|
+
"spec"
|
|
326
|
+
],
|
|
327
|
+
"テスト": [
|
|
328
|
+
"test"
|
|
329
|
+
],
|
|
330
|
+
"테스트": [
|
|
331
|
+
"test"
|
|
332
|
+
]
|
|
333
|
+
};
|
|
334
|
+
const EN_CJK = {};
|
|
335
|
+
for (const zh in CJK_WORDS) { for (const en of CJK_WORDS[zh]) { if (!EN_CJK[en]) EN_CJK[en] = []; EN_CJK[en].push(zh); } }
|
|
336
|
+
function containsCJK(s) { return CJK_RE.test(s); }
|
|
337
|
+
function tokenizeCJK2gram(text) {
|
|
338
|
+
const runs = String(text || '').match(CJK_RUN_RE) || [];
|
|
339
|
+
const out = [];
|
|
340
|
+
for (const run of runs) {
|
|
341
|
+
let i = 0;
|
|
342
|
+
while (i < run.length) {
|
|
343
|
+
if (i + 1 < run.length) { out.push(run[i] + run[i + 1]); i += 2; }
|
|
344
|
+
else { out.push(run[i]); i += 1; }
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
function bilingualLookup(term) {
|
|
350
|
+
const out = [];
|
|
351
|
+
if (CJK_WORDS[term]) out.push(...CJK_WORDS[term]);
|
|
352
|
+
if (EN_CJK[term]) out.push(...EN_CJK[term]);
|
|
353
|
+
return out;
|
|
354
|
+
}
|
|
355
|
+
function expandQueryTerms(query) {
|
|
356
|
+
const q = String(query || '').toLowerCase();
|
|
357
|
+
const terms = new Set(q.split(/\s+/).filter(Boolean));
|
|
358
|
+
const asciiParts = q.match(/[a-z0-9_]+/g) || [];
|
|
359
|
+
for (const p of asciiParts) {
|
|
360
|
+
if (p.length >= 2) terms.add(p);
|
|
361
|
+
for (const t of bilingualLookup(p)) terms.add(t);
|
|
362
|
+
}
|
|
363
|
+
if (containsCJK(q)) {
|
|
364
|
+
for (const gram of tokenizeCJK2gram(q)) {
|
|
365
|
+
terms.add(gram);
|
|
366
|
+
for (const t of bilingualLookup(gram)) terms.add(t);
|
|
367
|
+
}
|
|
368
|
+
for (const run of q.match(CJK_RUN_RE) || []) terms.add(run);
|
|
369
|
+
}
|
|
370
|
+
return [...terms].filter(Boolean);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const args = process.argv.slice(2);
|
|
374
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
375
|
+
process.stdout.write('ctxslice v0.3.1\n');
|
|
376
|
+
process.exit(0);
|
|
377
|
+
}
|
|
378
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
379
|
+
process.stdout.write(
|
|
380
|
+
'ContextSlice CLI v0.3.1 — Zero-Config Multi-Language AST Slicer\n\n' +
|
|
381
|
+
'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
|
|
382
|
+
'Options:\n --root <dir> Target repository path (default: current directory)\n' +
|
|
383
|
+
' --budget <num> Max token budget (default: 32768)\n' +
|
|
384
|
+
' -v, --version Show version\n' +
|
|
385
|
+
' -h, --help Show help\n'
|
|
386
|
+
);
|
|
387
|
+
process.exit(0);
|
|
388
|
+
}
|
|
389
|
+
const rootFlag = args.indexOf('--root');
|
|
390
|
+
const targetRoot = rootFlag !== -1 && args[rootFlag + 1] ? path.resolve(args[rootFlag + 1]) : process.cwd();
|
|
391
|
+
const budgetFlag = args.indexOf('--budget');
|
|
392
|
+
const budget = budgetFlag !== -1 ? Number(args[budgetFlag + 1]) : 32768;
|
|
393
|
+
const skipIdx = new Set([rootFlag, rootFlag + 1, budgetFlag, budgetFlag + 1]);
|
|
394
|
+
const query = args.find((a, idx) => !skipIdx.has(idx) && !a.startsWith('--')) || 'fix bug';
|
|
395
|
+
const IGNORE = new Set([
|
|
396
|
+
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
397
|
+
'venv', '.venv', '__pycache__', 'vendor', 'target', '.build', '.swiftpm', 'DerivedData', 'Pods', 'bin', 'obj'
|
|
398
|
+
]);
|
|
399
|
+
const BINARY_EXT = new Set([
|
|
400
|
+
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.ico', '.icns', '.tif', '.tiff', '.svg',
|
|
401
|
+
'.mp4', '.mov', '.avi', '.mkv', '.webm', '.wmv', '.flv', '.mp3', '.wav', '.ogg', '.flac', '.aac', '.m4a', '.wma',
|
|
402
|
+
'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.tgz', '.iso', '.dmg',
|
|
403
|
+
'.exe', '.dll', '.so', '.dylib', '.bin', '.o', '.a', '.obj', '.lib', '.wasm', '.class', '.jar', '.war', '.pyc', '.pyo',
|
|
404
|
+
'.ttf', '.otf', '.woff', '.woff2', '.eot',
|
|
405
|
+
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods', '.odp', '.rtf',
|
|
406
|
+
'.db', '.sqlite', '.sqlite3', '.mdb', '.psd', '.ai', '.sketch', '.fig', '.xd', '.blend'
|
|
407
|
+
]);
|
|
408
|
+
const NOISE_FILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock|Gemfile\.lock|composer\.lock|go\.sum|Podfile\.lock|packages\.lock\.json|\.env(\..*)?|\.pem|\.key|credentials\.json|service-account.*\.json|secrets\.json)$|\.min\.(js|mjs|cjs|css)$|\.map$/i;
|
|
409
|
+
const CONTROL_WORDS = new Set(['if', 'else', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'typeof', 'do', 'try']);
|
|
410
|
+
|
|
411
|
+
function isTextCandidate(full) {
|
|
412
|
+
if (BINARY_EXT.has(path.extname(full).toLowerCase())) return false;
|
|
413
|
+
if (NOISE_FILE.test(full.replace(/\\/g, '/'))) return false;
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function isBinaryBuffer(buf) {
|
|
418
|
+
const len = Math.min(buf.length, 8192);
|
|
419
|
+
if (len === 0) return false;
|
|
420
|
+
let suspicious = 0;
|
|
421
|
+
for (let i = 0; i < len; i++) {
|
|
422
|
+
const b = buf[i];
|
|
423
|
+
if (b === 0 || b < 9 || b === 11 || b === 12 || (b > 13 && b < 32) || b === 127) suspicious++;
|
|
424
|
+
}
|
|
425
|
+
return suspicious / len > 0.08;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function walk(dir, acc = []) {
|
|
429
|
+
if (!fs.existsSync(dir)) return acc;
|
|
430
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
431
|
+
if (IGNORE.has(entry.name)) continue;
|
|
432
|
+
const full = path.join(dir, entry.name);
|
|
433
|
+
if (entry.isDirectory()) walk(full, acc);
|
|
434
|
+
else if (isTextCandidate(full)) acc.push(full);
|
|
435
|
+
}
|
|
436
|
+
return acc;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function estimateTokens(str) {
|
|
440
|
+
return Math.max(1, Math.round(str.length / 3.8));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function maskCommentsAndStrings(code) {
|
|
444
|
+
return code
|
|
445
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
|
|
446
|
+
.replace(/\/\/.*$/gm, (m) => ' '.repeat(m.length))
|
|
447
|
+
.replace(/#.*$/gm, (m) => ' '.repeat(m.length))
|
|
448
|
+
.replace(/`(?:\\[\s\S]|[^`\\])*`/g, (m) => m.replace(/[^\n]/g, ' '))
|
|
449
|
+
.replace(/"(?:\\.|[^"\\])*"/g, (m) => ' '.repeat(m.length))
|
|
450
|
+
.replace(/'(?:\\.|[^'\\])*'/g, (m) => ' '.repeat(m.length));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function findBraceEnd(lines, startIdx) {
|
|
454
|
+
const maskedLines = maskCommentsAndStrings(lines.slice(startIdx).join('\n')).split('\n');
|
|
455
|
+
let depth = 0, opened = false, endRel = 0;
|
|
456
|
+
for (let j = 0; j < maskedLines.length; j++) {
|
|
457
|
+
const line = maskedLines[j];
|
|
458
|
+
for (let k = 0; k < line.length; k++) {
|
|
459
|
+
const ch = line[k];
|
|
460
|
+
if (ch === '{') { depth++; opened = true; }
|
|
461
|
+
else if (ch === '}') depth--;
|
|
462
|
+
}
|
|
463
|
+
endRel = j;
|
|
464
|
+
if (opened && depth <= 0) break;
|
|
465
|
+
if (!opened && line.trim().endsWith(';')) break;
|
|
466
|
+
}
|
|
467
|
+
return startIdx + endRel;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function extractBlocks(code, ext, fileName) {
|
|
471
|
+
const e = (ext || '').toLowerCase();
|
|
472
|
+
const lines = code.split('\n');
|
|
473
|
+
const blocks = [];
|
|
474
|
+
|
|
475
|
+
for (let i = 0; i < lines.length; i++) {
|
|
476
|
+
const line = lines[i];
|
|
477
|
+
const trimmed = line.trim();
|
|
478
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('/*')) continue;
|
|
479
|
+
|
|
480
|
+
let name = null;
|
|
481
|
+
let kind = 'function';
|
|
482
|
+
let m = null;
|
|
483
|
+
|
|
484
|
+
if (e === '.py' || e === '.pyw') {
|
|
485
|
+
m = line.match(/^(?:async\s+)?(def|class)\s+([A-Za-z_][A-Za-z0-9_]*)/);
|
|
486
|
+
if (m) {
|
|
487
|
+
name = m[2];
|
|
488
|
+
kind = m[1] === 'class' ? 'class' : 'function';
|
|
489
|
+
let end = i;
|
|
490
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
491
|
+
if (lines[j].trim() === '' || /^\s+/.test(lines[j])) end = j;
|
|
492
|
+
else break;
|
|
493
|
+
}
|
|
494
|
+
while (end > i && lines[end].trim() === '') end--;
|
|
495
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
496
|
+
const skeleton = end - i > 2 ? `${lines[i]}\n # ... ${end - i} lines folded` : full;
|
|
497
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
498
|
+
i = end;
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
if (e === '.go') {
|
|
504
|
+
m = line.match(/^func\s+(?:\([^)]+\)\s+)?([A-Za-z0-9_]+)/);
|
|
505
|
+
if (m) {
|
|
506
|
+
name = m[1];
|
|
507
|
+
kind = 'function';
|
|
508
|
+
const end = findBraceEnd(lines, i);
|
|
509
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
510
|
+
const sigIdx = full.indexOf('{');
|
|
511
|
+
const skeleton = (sigIdx === -1 || end - i < 3) ? full : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
512
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
513
|
+
i = end;
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (e === '.rs') {
|
|
519
|
+
m = line.match(/^(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?(fn|struct|enum|impl|trait)\s+([A-Za-z0-9_]+)/);
|
|
520
|
+
if (m) {
|
|
521
|
+
kind = m[1];
|
|
522
|
+
name = m[2];
|
|
523
|
+
const end = findBraceEnd(lines, i);
|
|
524
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
525
|
+
const sigIdx = full.indexOf('{');
|
|
526
|
+
const skeleton = (sigIdx === -1 || end - i < 3) ? full : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
527
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
528
|
+
if (kind !== 'impl') i = end;
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (e === '.java' || e === '.kt' || e === '.kts' || e === '.cs') {
|
|
534
|
+
m = line.match(/^(?:\s)*(?:public|private|protected|internal|static|final|async|override|abstract|default|native|synchronized|\s)+[\w<>\[\],\s]+\s+([A-Za-z0-9_]+)\s*\(/);
|
|
535
|
+
if (!m) {
|
|
536
|
+
m = line.match(/^(?:\s)*(?:public|private|protected|internal|static|final|abstract|\s)*(class|interface|record|enum|struct)\s+([A-Za-z0-9_]+)/);
|
|
537
|
+
if (m) { kind = m[1]; name = m[2]; }
|
|
538
|
+
} else {
|
|
539
|
+
name = m[1]; kind = 'method';
|
|
540
|
+
}
|
|
541
|
+
if (name) {
|
|
542
|
+
const end = findBraceEnd(lines, i);
|
|
543
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
544
|
+
const sigIdx = full.indexOf('{');
|
|
545
|
+
const skeleton = (sigIdx === -1 || end - i < 3) ? full : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
546
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
547
|
+
if (kind !== 'class') i = end;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (e === '.c' || e === '.h' || e === '.cpp' || e === '.hpp' || e === '.cc' || e === '.cxx') {
|
|
553
|
+
m = line.match(/^(?:class|struct|enum)\s+([A-Za-z0-9_]+)/);
|
|
554
|
+
if (m) {
|
|
555
|
+
kind = 'class'; name = m[1];
|
|
556
|
+
} else {
|
|
557
|
+
m = line.match(/^(?:(?:inline|static|virtual|explicit|constexpr|friend)\s+)*[\w:*&<>\[\]\s]+\s+([A-Za-z0-9_]+)\s*\([^;)]*\)\s*(?:const)?\s*(?:noexcept)?\s*\{?/);
|
|
558
|
+
if (m && !line.includes('return ') && !line.includes('typedef ')) { name = m[1]; kind = 'function'; }
|
|
559
|
+
}
|
|
560
|
+
if (name) {
|
|
561
|
+
const end = findBraceEnd(lines, i);
|
|
562
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
563
|
+
const sigIdx = full.indexOf('{');
|
|
564
|
+
const skeleton = (sigIdx === -1 || end - i < 3) ? full : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
565
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
566
|
+
if (kind !== 'class' && kind !== 'struct') i = end;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
m = line.match(/^(?:export\s+(?:default\s+)?)?(?:async\s+)?(function|class|interface|type|enum|const)\s+([A-Za-z0-9_$]+)/);
|
|
572
|
+
if (!m) {
|
|
573
|
+
m = line.match(/^(?:(?:public|protected|private|static|final|abstract)\s+)*(?:function|func)\s+([A-Za-z0-9_$]+)/);
|
|
574
|
+
if (m) { name = m[1]; kind = 'function'; }
|
|
575
|
+
} else {
|
|
576
|
+
name = m[2]; kind = m[1];
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (name) {
|
|
580
|
+
const end = findBraceEnd(lines, i);
|
|
581
|
+
const full = lines.slice(i, end + 1).join('\n');
|
|
582
|
+
const sigIdx = full.indexOf('{');
|
|
583
|
+
const skeleton = (kind === 'interface' || kind === 'type' || sigIdx === -1 || end - i < 4)
|
|
584
|
+
? full
|
|
585
|
+
: full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
586
|
+
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
587
|
+
if (kind !== 'class' && kind !== 'module') i = end;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (blocks.length === 0 && lines.length > 0) {
|
|
592
|
+
const name = path.basename(fileName || ('file' + e));
|
|
593
|
+
const full = code;
|
|
594
|
+
const skeleton = lines.length > 25 ? lines.slice(0, 20).join('\n') + `\n/* ... ${lines.length - 20} lines folded ... */` : full;
|
|
595
|
+
blocks.push({ name, kind: 'module', startLine: 1, endLine: lines.length, full, skeleton });
|
|
596
|
+
}
|
|
597
|
+
return blocks;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const files = walk(targetRoot);
|
|
601
|
+
const terms = expandQueryTerms(query);
|
|
602
|
+
const allRawBlocks = [];
|
|
603
|
+
for (const filePath of files) {
|
|
604
|
+
try {
|
|
605
|
+
const buf = fs.readFileSync(filePath);
|
|
606
|
+
if (isBinaryBuffer(buf)) continue;
|
|
607
|
+
const content = buf.toString('utf8');
|
|
608
|
+
const relPath = path.relative(targetRoot, filePath);
|
|
609
|
+
const items = extractBlocks(content, path.extname(filePath), relPath);
|
|
610
|
+
for (const b of items) {
|
|
611
|
+
allRawBlocks.push({
|
|
612
|
+
...b,
|
|
613
|
+
filePath: relPath,
|
|
614
|
+
rawTokens: estimateTokens(b.full),
|
|
615
|
+
skelTokens: estimateTokens(b.skeleton),
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
} catch {}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const totalBlocks = Math.max(1, allRawBlocks.length);
|
|
622
|
+
const termDF = {};
|
|
623
|
+
for (const t of terms) {
|
|
624
|
+
let df = 0;
|
|
625
|
+
for (const b of allRawBlocks) {
|
|
626
|
+
if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
|
|
627
|
+
df++;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
termDF[t] = Math.max(1, df);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const scored = allRawBlocks.map((b) => {
|
|
634
|
+
const lower = b.full.toLowerCase();
|
|
635
|
+
const relLower = b.filePath.toLowerCase();
|
|
636
|
+
let score = 0;
|
|
637
|
+
for (const t of terms) {
|
|
638
|
+
const df = termDF[t] || 1;
|
|
639
|
+
const idf = Math.log(1 + (totalBlocks / df));
|
|
640
|
+
const scarcityMultiplier = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
|
|
641
|
+
const nameMatch = b.name.toLowerCase().includes(t) ? 35 : 0;
|
|
642
|
+
const pathMatch = relLower.includes(t) ? 25 : 0;
|
|
643
|
+
const bodyOcc = lower.split(t).length - 1;
|
|
644
|
+
const bodyScore = Math.min(15, 3 * Math.log1p(bodyOcc));
|
|
645
|
+
score += (nameMatch + pathMatch + bodyScore) * idf * scarcityMultiplier;
|
|
646
|
+
}
|
|
647
|
+
return { ...b, score };
|
|
648
|
+
}).sort((a, b) => b.score - a.score);
|
|
649
|
+
|
|
650
|
+
// True Call Graph (SymbolMap + Word-Boundary Call Matching + BFS maxHops)
|
|
651
|
+
const symbolMap = new Map();
|
|
652
|
+
for (let i = 0; i < scored.length; i++) {
|
|
653
|
+
const b = scored[i];
|
|
654
|
+
if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
|
|
655
|
+
if (!symbolMap.has(b.name)) symbolMap.set(b.name, []);
|
|
656
|
+
symbolMap.get(b.name).push(i);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const callAdj = Array.from({ length: scored.length }, () => new Set());
|
|
660
|
+
const definedNames = Array.from(symbolMap.keys());
|
|
661
|
+
for (let i = 0; i < scored.length; i++) {
|
|
662
|
+
const caller = scored[i];
|
|
663
|
+
const maskedCaller = maskCommentsAndStrings(caller.full);
|
|
664
|
+
for (const sym of definedNames) {
|
|
665
|
+
if (sym === caller.name) continue;
|
|
666
|
+
if (maskedCaller.includes(sym)) {
|
|
667
|
+
const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
668
|
+
if (new RegExp('\\b' + esc + '\\s*\\(', 'm').test(maskedCaller)) {
|
|
669
|
+
for (const t of (symbolMap.get(sym) || [])) {
|
|
670
|
+
callAdj[i].add(t);
|
|
671
|
+
callAdj[t].add(i);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const hopDistances = new Map();
|
|
678
|
+
const bfsQ = [];
|
|
679
|
+
for (let i = 0; i < scored.length; i++) {
|
|
680
|
+
if (scored[i].score > 0 && bfsQ.length < 3) {
|
|
681
|
+
bfsQ.push(i);
|
|
682
|
+
hopDistances.set(i, 0);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
let qHead = 0;
|
|
686
|
+
while (qHead < bfsQ.length) {
|
|
687
|
+
const curr = bfsQ[qHead++];
|
|
688
|
+
const curHop = hopDistances.get(curr) ?? 0;
|
|
689
|
+
if (curHop >= 2) continue;
|
|
690
|
+
for (const nbr of callAdj[curr]) {
|
|
691
|
+
if (!hopDistances.has(nbr)) {
|
|
692
|
+
hopDistances.set(nbr, curHop + 1);
|
|
693
|
+
bfsQ.push(nbr);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
let remaining = budget;
|
|
699
|
+
const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.1" budget="' + budget + '">'];
|
|
700
|
+
const includedIds = new Set();
|
|
701
|
+
const dirBudgetUsed = {};
|
|
702
|
+
const maxDirBudget = budget * 0.65;
|
|
703
|
+
|
|
704
|
+
const candidateItems = [];
|
|
705
|
+
for (let i = 0; i < scored.length; i++) {
|
|
706
|
+
const item = scored[i];
|
|
707
|
+
const topDir = item.filePath.split(path.sep)[0] || 'root';
|
|
708
|
+
const curDir = dirBudgetUsed[topDir] || 0;
|
|
709
|
+
const hop = hopDistances.get(i);
|
|
710
|
+
const isFocal = hop === 0 || (i < 2 && item.score > 0);
|
|
711
|
+
const key = item.filePath + ':' + item.startLine;
|
|
712
|
+
|
|
713
|
+
if (isFocal && item.rawTokens <= remaining && curDir + item.rawTokens <= maxDirBudget) {
|
|
714
|
+
remaining -= item.rawTokens;
|
|
715
|
+
dirBudgetUsed[topDir] = curDir + item.rawTokens;
|
|
716
|
+
includedIds.add(key);
|
|
717
|
+
out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
|
|
718
|
+
out.push(item.full);
|
|
719
|
+
} else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
|
|
720
|
+
const linked = (hop !== undefined && hop <= 2) || item.score > 0;
|
|
721
|
+
if (linked || i < 12) {
|
|
722
|
+
remaining -= item.skelTokens;
|
|
723
|
+
dirBudgetUsed[topDir] = curDir + item.skelTokens;
|
|
724
|
+
includedIds.add(key);
|
|
725
|
+
out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
|
|
726
|
+
out.push(item.skeleton);
|
|
727
|
+
} else {
|
|
728
|
+
candidateItems.push(item);
|
|
729
|
+
}
|
|
730
|
+
} else {
|
|
731
|
+
candidateItems.push(item);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
|
|
736
|
+
if (omitted.length > 0) {
|
|
737
|
+
out.push('<omitted_top_matches>');
|
|
738
|
+
for (const o of omitted) {
|
|
739
|
+
out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
|
|
740
|
+
}
|
|
741
|
+
out.push('</omitted_top_matches>');
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
out.push('</context_slice>');
|
|
745
|
+
process.stdout.write(out.join('\n') + '\n');
|