@grundy40/contextslice 0.3.5 → 0.4.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/README.md +10 -38
- package/bin/ctxslice-mcp.mjs +1155 -282
- package/bin/ctxslice.mjs +1036 -243
- package/package.json +3 -3
package/bin/ctxslice-mcp.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.
|
|
3
|
+
* ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.1
|
|
4
4
|
* Features: Embedded Base64 Tree-sitter WASM + Lazy Cache (~/.contextslice/parsers),
|
|
5
5
|
* State-Machine Brace Matcher Fallback, True Call Graph (BFS), TF-IDF, subPath Sandbox, mtime Cache
|
|
6
6
|
*/
|
|
@@ -11,10 +11,957 @@ import readline from 'node:readline';
|
|
|
11
11
|
import { createRequire } from 'node:module';
|
|
12
12
|
|
|
13
13
|
if (process.argv.includes('--version') || process.argv.includes('-v')) {
|
|
14
|
-
process.stdout.write('ctxslice-mcp v0.
|
|
14
|
+
process.stdout.write('ctxslice-mcp v0.4.1\n');
|
|
15
15
|
process.exit(0);
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
|
|
19
|
+
const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
|
|
20
|
+
const EN_CONVERSATIONAL_STOPWORDS = new Set([
|
|
21
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
|
|
22
|
+
'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
|
|
23
|
+
'how', 'why', 'what', 'when', 'where', 'who', 'which', 'whom', 'whose',
|
|
24
|
+
'can', 'could', 'would', 'should', 'will', 'shall', 'may', 'might', 'must',
|
|
25
|
+
'do', 'does', 'did', 'done', 'doing', 'have', 'has', 'had', 'having',
|
|
26
|
+
'please', 'pls', 'help', 'me', 'my', 'we', 'our', 'you', 'your', 'they', 'their',
|
|
27
|
+
'it', 'its', 'this', 'that', 'these', 'those', 'there', 'here',
|
|
28
|
+
'and', 'or', 'but', 'so', 'than', 'too', 'very', 'just', 'only', 'also',
|
|
29
|
+
'fix', 'modify', 'want', 'need', 'tell'
|
|
30
|
+
]);
|
|
31
|
+
const ZH_CONVERSATIONAL_STOPWORDS_RE = /為什麼|为什么|怎麼樣|怎么样|怎麼|怎么|如何|請幫我|请帮我|幫我|帮我|請問|请问|修改|更改|調整|调整|一下|什麼|什么|這個|这个|那個|那个|哪裡|哪里|[的了嗎呢啊吧著着過把被給跟與及]/g;
|
|
32
|
+
|
|
33
|
+
function estimateTokens(str) {
|
|
34
|
+
if (!str) return 0;
|
|
35
|
+
let cjk = 0;
|
|
36
|
+
for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
|
|
37
|
+
return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function escapeXmlAttr(value) {
|
|
41
|
+
return String(value || '')
|
|
42
|
+
.replace(/&/g, '&')
|
|
43
|
+
.replace(/"/g, '"')
|
|
44
|
+
.replace(/</g, '<')
|
|
45
|
+
.replace(/>/g, '>');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function escapeXmlText(value) {
|
|
49
|
+
return String(value || '')
|
|
50
|
+
.replace(/&/g, '&')
|
|
51
|
+
.replace(/</g, '<')
|
|
52
|
+
.replace(/>/g, '>');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function mergeLineRanges(ranges) {
|
|
56
|
+
if (!ranges || ranges.length === 0) return [];
|
|
57
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
58
|
+
const merged = [];
|
|
59
|
+
for (const r of sorted) {
|
|
60
|
+
const s = Math.max(1, r[0]);
|
|
61
|
+
const e = Math.max(s, r[1]);
|
|
62
|
+
if (merged.length === 0) {
|
|
63
|
+
merged.push([s, e]);
|
|
64
|
+
} else {
|
|
65
|
+
const prev = merged[merged.length - 1];
|
|
66
|
+
if (s <= prev[1] + 1) prev[1] = Math.max(prev[1], e);
|
|
67
|
+
else merged.push([s, e]);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return merged;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function formatShownLines(ranges) {
|
|
74
|
+
const merged = mergeLineRanges(ranges);
|
|
75
|
+
if (merged.length === 0) return 'none';
|
|
76
|
+
return merged.map((r) => (r[0] === r[1] ? String(r[0]) : r[0] + '-' + r[1])).join(', ');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function slicePlainTextConfigWindow(content, queryTerms) {
|
|
80
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
81
|
+
if (lines.length <= 200) return null;
|
|
82
|
+
|
|
83
|
+
const matchedLines = [];
|
|
84
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
85
|
+
for (let i = 0; i < lines.length; i++) {
|
|
86
|
+
const lower = lines[i].toLowerCase();
|
|
87
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
88
|
+
matchedLines.push(i + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const rawRanges = matchedLines.length > 0
|
|
94
|
+
? matchedLines.map((ln) => [Math.max(1, ln - 40), Math.min(lines.length, ln + 40)])
|
|
95
|
+
: [[1, Math.min(lines.length, 81)]];
|
|
96
|
+
|
|
97
|
+
const merged = mergeLineRanges(rawRanges);
|
|
98
|
+
const parts = [];
|
|
99
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
100
|
+
const s = merged[idx][0];
|
|
101
|
+
const e = merged[idx][1];
|
|
102
|
+
if (idx > 0) {
|
|
103
|
+
const prevEnd = merged[idx - 1][1];
|
|
104
|
+
parts.push('// ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ...');
|
|
105
|
+
}
|
|
106
|
+
parts.push(lines.slice(s - 1, e).join('\n'));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const windowedCode = parts.join('\n');
|
|
110
|
+
return {
|
|
111
|
+
windowedCode,
|
|
112
|
+
ranges: merged,
|
|
113
|
+
tokens: estimateTokens(windowedCode)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
|
|
118
|
+
const sorted = [...fileEntries].sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
119
|
+
const out = [];
|
|
120
|
+
let usedTokens = 0;
|
|
121
|
+
let omittedCount = 0;
|
|
122
|
+
for (const f of sorted) {
|
|
123
|
+
const line = ' ' + f.relPath + ' (' + f.lineCount + ' lines)';
|
|
124
|
+
const tk = estimateTokens(line);
|
|
125
|
+
if (usedTokens + tk > maxTokens && out.length > 0) {
|
|
126
|
+
omittedCount++;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
usedTokens += tk;
|
|
130
|
+
out.push(line);
|
|
131
|
+
}
|
|
132
|
+
if (omittedCount > 0) {
|
|
133
|
+
out.push(' ... (' + omittedCount + ' more files omitted to keep overview within ~1.8K tokens)');
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
const DOC_EXT_RE = /\.(md|mdx|rst|adoc|asciidoc)$/i;
|
|
138
|
+
const DOC_PATH_RE = /(^|\/)(docs?|documentation|wiki|guides?)\/|(^|\/)(README|CHANGELOG|HISTORY|CONTRIBUTING|CHANGES|RELEASES|MIGRATION|UPGRADING|AUTHORS|NOTICE|LICENSE)([^/]*)$/i;
|
|
139
|
+
const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|specs|testing|fixtures?|benchmarks?|examples?|samples?)\/|(\.|_)(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.[^/]+$/i;
|
|
140
|
+
const SYNTAX_NOISE_WORDS = new Set([
|
|
141
|
+
'class', 'def', 'function', 'func', 'fn', 'struct', 'interface', 'type', 'enum',
|
|
142
|
+
'const', 'let', 'var', 'async', 'await', 'import', 'export', 'return',
|
|
143
|
+
'public', 'private', 'protected', 'static'
|
|
144
|
+
]);
|
|
145
|
+
|
|
146
|
+
function classifyFileRole(filePath) {
|
|
147
|
+
const norm = String(filePath || '').replace(/\\/g, '/');
|
|
148
|
+
if (DOC_EXT_RE.test(norm) || DOC_PATH_RE.test(norm)) return 'doc';
|
|
149
|
+
if (TEST_PATH_RE.test(norm)) return 'test';
|
|
150
|
+
return 'source';
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function getQueryRoleIntents(query) {
|
|
154
|
+
const q = String(query || '').toLowerCase();
|
|
155
|
+
return {
|
|
156
|
+
wantsDocs: /\b(readme|changelog|docs|documentation|markdown|guide)\b|\.md\b|文件|說明/.test(q),
|
|
157
|
+
wantsTests: /\b(tests?|specs?|pytest|unittest|jest|vitest)\b|測試/.test(q)
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
|
|
162
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
163
|
+
if (lines.length <= 45) {
|
|
164
|
+
return {
|
|
165
|
+
windowedCode: content,
|
|
166
|
+
ranges: [[1, Math.max(1, lines.length)]],
|
|
167
|
+
tokens: estimateTokens(content)
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const matchedLines = [];
|
|
171
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
172
|
+
for (let i = 0; i < lines.length; i++) {
|
|
173
|
+
const lower = lines[i].toLowerCase();
|
|
174
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
175
|
+
matchedLines.push(i + 1);
|
|
176
|
+
if (matchedLines.length >= 3) break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const rawRanges = matchedLines.length > 0
|
|
181
|
+
? matchedLines.slice(0, 2).map((ln) => [Math.max(1, ln - radius), Math.min(lines.length, ln + radius)])
|
|
182
|
+
: [[1, Math.min(lines.length, 24)]];
|
|
183
|
+
const merged = mergeLineRanges(rawRanges);
|
|
184
|
+
const parts = [];
|
|
185
|
+
const usedRanges = [];
|
|
186
|
+
let accTokens = 0;
|
|
187
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
188
|
+
const s = merged[idx][0];
|
|
189
|
+
const e = merged[idx][1];
|
|
190
|
+
const sliceLines = [];
|
|
191
|
+
let endWritten = s - 1;
|
|
192
|
+
for (let ln = s; ln <= e; ln++) {
|
|
193
|
+
const candidate = lines[ln - 1];
|
|
194
|
+
const tk = estimateTokens(candidate);
|
|
195
|
+
if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
|
|
196
|
+
sliceLines.push(candidate);
|
|
197
|
+
accTokens += tk;
|
|
198
|
+
endWritten = ln;
|
|
199
|
+
}
|
|
200
|
+
if (sliceLines.length === 0) break;
|
|
201
|
+
if (idx > 0 && usedRanges.length > 0) {
|
|
202
|
+
const prevEnd = usedRanges[usedRanges.length - 1][1];
|
|
203
|
+
if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
|
|
204
|
+
}
|
|
205
|
+
parts.push(sliceLines.join('\n'));
|
|
206
|
+
usedRanges.push([s, endWritten]);
|
|
207
|
+
if (accTokens >= maxTokens) break;
|
|
208
|
+
}
|
|
209
|
+
if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < lines.length) {
|
|
210
|
+
parts.push('<!-- ... ' + (lines.length - usedRanges[usedRanges.length - 1][1]) + ' remaining doc lines omitted ... -->');
|
|
211
|
+
}
|
|
212
|
+
const windowedCode = parts.join('\n');
|
|
213
|
+
return {
|
|
214
|
+
windowedCode,
|
|
215
|
+
ranges: usedRanges.length > 0 ? usedRanges : [[1, Math.min(lines.length, 20)]],
|
|
216
|
+
tokens: estimateTokens(windowedCode)
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function findPythonSignatureEndIdx(lines, startIdx) {
|
|
221
|
+
let paren = 0, bracket = 0, brace = 0;
|
|
222
|
+
const maxScan = Math.min(lines.length - 1, startIdx + 25);
|
|
223
|
+
for (let j = startIdx; j <= maxScan; j++) {
|
|
224
|
+
const raw = lines[j];
|
|
225
|
+
let k = 0;
|
|
226
|
+
while (k < raw.length) {
|
|
227
|
+
const ch = raw[k];
|
|
228
|
+
if (ch === '#') break;
|
|
229
|
+
if (ch === '"' || ch === "'") {
|
|
230
|
+
const quote = ch;
|
|
231
|
+
k++;
|
|
232
|
+
while (k < raw.length) {
|
|
233
|
+
if (raw[k] === '\\') { k += 2; continue; }
|
|
234
|
+
if (raw[k] === quote) { k++; break; }
|
|
235
|
+
k++;
|
|
236
|
+
}
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (ch === '(') paren++;
|
|
240
|
+
else if (ch === ')') paren = Math.max(0, paren - 1);
|
|
241
|
+
else if (ch === '[') bracket++;
|
|
242
|
+
else if (ch === ']') bracket = Math.max(0, bracket - 1);
|
|
243
|
+
else if (ch === '{') brace++;
|
|
244
|
+
else if (ch === '}') brace = Math.max(0, brace - 1);
|
|
245
|
+
k++;
|
|
246
|
+
}
|
|
247
|
+
const noComment = raw.replace(/#.*$/, '').trimEnd();
|
|
248
|
+
if (paren <= 0 && bracket <= 0 && brace <= 0 && noComment.endsWith(':')) return j;
|
|
249
|
+
}
|
|
250
|
+
return startIdx;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function findPythonBlockEndIdx(lines, sigEndIdx, baseIndent) {
|
|
254
|
+
let end = sigEndIdx;
|
|
255
|
+
let inTriple = null;
|
|
256
|
+
for (let j = sigEndIdx + 1; j < lines.length; j++) {
|
|
257
|
+
const raw = lines[j];
|
|
258
|
+
const trimmed = raw.trim();
|
|
259
|
+
if (inTriple) {
|
|
260
|
+
end = j;
|
|
261
|
+
if ((raw.split(inTriple).length - 1) % 2 === 1) inTriple = null;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (trimmed === '') { end = j; continue; }
|
|
265
|
+
const indent = (raw.match(/^\s*/) || [''])[0].length;
|
|
266
|
+
if (indent <= baseIndent) break;
|
|
267
|
+
end = j;
|
|
268
|
+
const tm = trimmed.match(/^("""|''')/);
|
|
269
|
+
if (tm && (trimmed.split(tm[1]).length - 1) % 2 === 1) inTriple = tm[1];
|
|
270
|
+
}
|
|
271
|
+
while (end > sigEndIdx && lines[end].trim() === '') end--;
|
|
272
|
+
return end;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function buildPythonClassSkeleton(fullClassCode, classStartLine = 1, expandedMethodRanges = []) {
|
|
276
|
+
const lines = String(fullClassCode || '').split('\n');
|
|
277
|
+
if (lines.length <= 4) return fullClassCode;
|
|
278
|
+
let classDefRel = 0;
|
|
279
|
+
while (classDefRel < lines.length && lines[classDefRel].trimStart().startsWith('@')) classDefRel++;
|
|
280
|
+
if (classDefRel >= lines.length) return fullClassCode;
|
|
281
|
+
|
|
282
|
+
const classIndent = (lines[classDefRel].match(/^\s*/) || [''])[0].length;
|
|
283
|
+
const classSigEndRel = findPythonSignatureEndIdx(lines, classDefRel);
|
|
284
|
+
const out = [];
|
|
285
|
+
for (let i = 0; i <= classSigEndRel; i++) out.push(lines[i]);
|
|
286
|
+
|
|
287
|
+
let bodyIdx = classSigEndRel + 1;
|
|
288
|
+
while (bodyIdx < lines.length && lines[bodyIdx].trim() === '') bodyIdx++;
|
|
289
|
+
if (bodyIdx < lines.length) {
|
|
290
|
+
const t = lines[bodyIdx].trim();
|
|
291
|
+
if (t.startsWith('"""') || t.startsWith("'''")) {
|
|
292
|
+
const q = t.slice(0, 3);
|
|
293
|
+
if (t.length > 3 && t.slice(3).includes(q)) {
|
|
294
|
+
out.push(lines[bodyIdx]);
|
|
295
|
+
bodyIdx++;
|
|
296
|
+
} else {
|
|
297
|
+
let docEnd = bodyIdx;
|
|
298
|
+
for (let j = bodyIdx + 1; j < lines.length; j++) {
|
|
299
|
+
if (lines[j].includes(q)) { docEnd = j; break; }
|
|
300
|
+
}
|
|
301
|
+
if (docEnd - bodyIdx <= 4) {
|
|
302
|
+
for (let j = bodyIdx; j <= docEnd; j++) out.push(lines[j]);
|
|
303
|
+
} else {
|
|
304
|
+
out.push(lines[bodyIdx]);
|
|
305
|
+
out.push(lines[bodyIdx + 1]);
|
|
306
|
+
const indentStr = (lines[bodyIdx].match(/^\s*/) || [' '])[0];
|
|
307
|
+
out.push(indentStr + '... (' + (docEnd - bodyIdx - 1) + ' docstring lines folded)');
|
|
308
|
+
out.push(lines[docEnd]);
|
|
309
|
+
}
|
|
310
|
+
bodyIdx = docEnd + 1;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
let methodIndent = null;
|
|
316
|
+
let memberCount = 0;
|
|
317
|
+
for (let i = bodyIdx; i < lines.length; i++) {
|
|
318
|
+
const raw = lines[i];
|
|
319
|
+
const trimmed = raw.trim();
|
|
320
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
321
|
+
const indent = (raw.match(/^\s*/) || [''])[0].length;
|
|
322
|
+
if (indent <= classIndent) continue;
|
|
323
|
+
|
|
324
|
+
if (trimmed.startsWith('@') && (methodIndent === null || indent === methodIndent)) {
|
|
325
|
+
let k = i + 1;
|
|
326
|
+
while (k < lines.length && lines[k].trimStart().startsWith('@')) k++;
|
|
327
|
+
if (k < lines.length && /^(?:async\s+)?def\s+/.test(lines[k].trim())) {
|
|
328
|
+
if (methodIndent === null) methodIndent = indent;
|
|
329
|
+
for (let d = i; d < k; d++) out.push(lines[d]);
|
|
330
|
+
i = k - 1;
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const dm = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
336
|
+
if (dm && (methodIndent === null || indent === methodIndent)) {
|
|
337
|
+
methodIndent = indent;
|
|
338
|
+
memberCount++;
|
|
339
|
+
const mSigEnd = findPythonSignatureEndIdx(lines, i);
|
|
340
|
+
const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
|
|
341
|
+
const absStart = classStartLine + i;
|
|
342
|
+
const absEnd = classStartLine + mEnd;
|
|
343
|
+
const hit = expandedMethodRanges.find((r) => r.startLine <= absEnd && r.endLine >= absStart);
|
|
344
|
+
for (let s = i; s <= mSigEnd; s++) {
|
|
345
|
+
if (s === mSigEnd) {
|
|
346
|
+
const folded = Math.max(1, mEnd - mSigEnd);
|
|
347
|
+
const note = hit
|
|
348
|
+
? ' # [expanded in <focal symbol="' + hit.name + '"> below]'
|
|
349
|
+
: ' # ... ' + folded + ' lines folded';
|
|
350
|
+
out.push(lines[s] + note);
|
|
351
|
+
} else {
|
|
352
|
+
out.push(lines[s]);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
i = mEnd;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (methodIndent === null || indent <= methodIndent) {
|
|
360
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*\s*(?::[^=]+)?(?:=.*)?$/.test(trimmed)) {
|
|
361
|
+
out.push(raw);
|
|
362
|
+
memberCount++;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (memberCount === 0) {
|
|
368
|
+
return lines.length > 4
|
|
369
|
+
? lines.slice(0, classSigEndRel + 1).join('\n') + '\n # ... ' + (lines.length - classSigEndRel - 1) + ' lines folded'
|
|
370
|
+
: fullClassCode;
|
|
371
|
+
}
|
|
372
|
+
return out.join('\n');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function extractPythonBlocks(lines, lineIdx) {
|
|
376
|
+
const line = lines[lineIdx];
|
|
377
|
+
const m = line.match(/^(async\s+def|def|class)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
|
|
378
|
+
if (!m) return null;
|
|
379
|
+
|
|
380
|
+
const kind = m[1] === 'class' ? 'class' : 'function';
|
|
381
|
+
const name = m[2];
|
|
382
|
+
let startIdx = lineIdx;
|
|
383
|
+
while (startIdx > 0 && /^@[A-Za-z_]/.test(lines[startIdx - 1])) startIdx--;
|
|
384
|
+
const startLine = startIdx + 1;
|
|
385
|
+
const sigEndIdx = findPythonSignatureEndIdx(lines, lineIdx);
|
|
386
|
+
const endIdx = findPythonBlockEndIdx(lines, sigEndIdx, 0);
|
|
387
|
+
const endLine = endIdx + 1;
|
|
388
|
+
const full = lines.slice(startIdx, endIdx + 1).join('\n');
|
|
389
|
+
const results = [];
|
|
390
|
+
|
|
391
|
+
if (kind === 'class') {
|
|
392
|
+
results.push({
|
|
393
|
+
name,
|
|
394
|
+
kind: 'class',
|
|
395
|
+
exported: !name.startsWith('_'),
|
|
396
|
+
startLine,
|
|
397
|
+
endLine,
|
|
398
|
+
full,
|
|
399
|
+
skeleton: buildPythonClassSkeleton(full, startLine)
|
|
400
|
+
});
|
|
401
|
+
let methodIndent = null;
|
|
402
|
+
for (let mIdx = sigEndIdx + 1; mIdx <= endIdx; mIdx++) {
|
|
403
|
+
const mLine = lines[mIdx];
|
|
404
|
+
const mTrimmed = mLine.trim();
|
|
405
|
+
if (!mTrimmed || mTrimmed.startsWith('#')) continue;
|
|
406
|
+
const indent = (mLine.match(/^\s*/) || [''])[0].length;
|
|
407
|
+
if (indent <= 0) continue;
|
|
408
|
+
const dm = mTrimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
409
|
+
if (!dm) continue;
|
|
410
|
+
if (methodIndent === null) methodIndent = indent;
|
|
411
|
+
if (indent !== methodIndent) continue;
|
|
412
|
+
const methodName = dm[1];
|
|
413
|
+
let mStartIdx = mIdx;
|
|
414
|
+
while (
|
|
415
|
+
mStartIdx > sigEndIdx + 1 &&
|
|
416
|
+
lines[mStartIdx - 1].trimStart().startsWith('@') &&
|
|
417
|
+
(lines[mStartIdx - 1].match(/^\s*/) || [''])[0].length === indent
|
|
418
|
+
) {
|
|
419
|
+
mStartIdx--;
|
|
420
|
+
}
|
|
421
|
+
const mSigEnd = findPythonSignatureEndIdx(lines, mIdx);
|
|
422
|
+
const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
|
|
423
|
+
const mFull = lines.slice(mStartIdx, mEnd + 1).join('\n');
|
|
424
|
+
const mFolded = Math.max(1, mEnd - mSigEnd);
|
|
425
|
+
const indentStr = (mLine.match(/^\s*/) || [' '])[0];
|
|
426
|
+
const mSigLines = lines.slice(mStartIdx, mSigEnd + 1).join('\n');
|
|
427
|
+
const mSkel = mEnd - mSigEnd > 2 ? mSigLines + '\n' + indentStr + ' # ... ' + mFolded + ' lines folded' : mFull;
|
|
428
|
+
results.push({
|
|
429
|
+
name: name + '.' + methodName,
|
|
430
|
+
kind: 'method',
|
|
431
|
+
exported: !name.startsWith('_') && !methodName.startsWith('_'),
|
|
432
|
+
startLine: mStartIdx + 1,
|
|
433
|
+
endLine: mEnd + 1,
|
|
434
|
+
full: mFull,
|
|
435
|
+
skeleton: mSkel
|
|
436
|
+
});
|
|
437
|
+
mIdx = mEnd;
|
|
438
|
+
}
|
|
439
|
+
} else {
|
|
440
|
+
const sigLines = lines.slice(startIdx, sigEndIdx + 1).join('\n');
|
|
441
|
+
const skeleton = endIdx - sigEndIdx > 2 ? sigLines + '\n # ... ' + (endIdx - sigEndIdx) + ' lines folded' : full;
|
|
442
|
+
results.push({
|
|
443
|
+
name,
|
|
444
|
+
kind: 'function',
|
|
445
|
+
exported: !name.startsWith('_'),
|
|
446
|
+
startLine,
|
|
447
|
+
endLine,
|
|
448
|
+
full,
|
|
449
|
+
skeleton
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return { blocks: results, endIdx };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function assembleContextSliceXml(opts) {
|
|
456
|
+
const {
|
|
457
|
+
blocks,
|
|
458
|
+
fileEntries,
|
|
459
|
+
fileLineCounts,
|
|
460
|
+
fileHeaders,
|
|
461
|
+
fileFooters,
|
|
462
|
+
rawQuery,
|
|
463
|
+
terms,
|
|
464
|
+
budget,
|
|
465
|
+
maxHops,
|
|
466
|
+
autoExpand,
|
|
467
|
+
rootAttr,
|
|
468
|
+
version,
|
|
469
|
+
subPathTag,
|
|
470
|
+
includeParserAttr,
|
|
471
|
+
controlWords,
|
|
472
|
+
maskFn
|
|
473
|
+
} = opts;
|
|
474
|
+
|
|
475
|
+
if (!String(rawQuery || '').trim()) {
|
|
476
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
477
|
+
return [
|
|
478
|
+
'<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
|
|
479
|
+
' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
|
|
480
|
+
' <repository_file_tree>',
|
|
481
|
+
...treeLines,
|
|
482
|
+
' </repository_file_tree>',
|
|
483
|
+
'</context_slice>'
|
|
484
|
+
].join('\n');
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const roleIntents = getQueryRoleIntents(rawQuery);
|
|
488
|
+
const configWindowByKey = new Map();
|
|
489
|
+
const preparedBlocks = blocks.map((b) => {
|
|
490
|
+
const rel = b.filePath;
|
|
491
|
+
const key = rel + ':' + b.startLine;
|
|
492
|
+
const lineCount = Math.max(1, b.endLine - b.startLine + 1);
|
|
493
|
+
const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
|
|
494
|
+
const isDocExt = DOC_EXT_RE.test(rel);
|
|
495
|
+
let win = null;
|
|
496
|
+
if (b.kind === 'module') {
|
|
497
|
+
if (isConfigFile && lineCount > 200) {
|
|
498
|
+
win = slicePlainTextConfigWindow(b.full, terms);
|
|
499
|
+
} else if (isDocExt && lineCount > 45) {
|
|
500
|
+
win = sliceDocWindow(b.full, terms, 16, 480);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (win) configWindowByKey.set(key, win);
|
|
504
|
+
const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
|
|
505
|
+
const skelTk = isDocExt
|
|
506
|
+
? Math.min(b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton), win ? win.tokens : 480)
|
|
507
|
+
: (b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton));
|
|
508
|
+
return {
|
|
509
|
+
...b,
|
|
510
|
+
filePath: rel,
|
|
511
|
+
lineCount,
|
|
512
|
+
role: classifyFileRole(rel),
|
|
513
|
+
isDocExt,
|
|
514
|
+
rawTk,
|
|
515
|
+
skelTk
|
|
516
|
+
};
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
const totalBlocks = Math.max(1, preparedBlocks.length);
|
|
520
|
+
const termDF = {};
|
|
521
|
+
for (const t of terms) {
|
|
522
|
+
let df = 0;
|
|
523
|
+
for (const b of preparedBlocks) {
|
|
524
|
+
if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
|
|
525
|
+
df++;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
termDF[t] = Math.max(1, df);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const scored = preparedBlocks.map((b) => {
|
|
532
|
+
const nameLower = b.name.toLowerCase();
|
|
533
|
+
const shortLower = nameLower.includes('.') ? nameLower.split('.').pop() : nameLower;
|
|
534
|
+
const relLower = b.filePath.toLowerCase();
|
|
535
|
+
const lowerBody = b.full.toLowerCase();
|
|
536
|
+
let score = 0;
|
|
537
|
+
let matchedTerms = 0;
|
|
538
|
+
|
|
539
|
+
for (const t of terms) {
|
|
540
|
+
const df = termDF[t] || 1;
|
|
541
|
+
const idf = Math.log(1 + (totalBlocks / df));
|
|
542
|
+
const scarcity = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
|
|
543
|
+
let termScore = 0;
|
|
544
|
+
let hit = false;
|
|
545
|
+
if (nameLower === t || shortLower === t) { termScore += 48; hit = true; }
|
|
546
|
+
else if (nameLower.includes(t)) { termScore += 24; hit = true; }
|
|
547
|
+
if (relLower.includes(t)) { termScore += 12; hit = true; }
|
|
548
|
+
const bodyOcc = lowerBody.split(t).length - 1;
|
|
549
|
+
if (bodyOcc > 0) { termScore += Math.min(12, 3 * Math.log1p(bodyOcc)); hit = true; }
|
|
550
|
+
if (hit) matchedTerms++;
|
|
551
|
+
score += termScore * idf * scarcity;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (matchedTerms >= 2) {
|
|
555
|
+
score *= 1 + 0.35 * (matchedTerms - 1);
|
|
556
|
+
}
|
|
557
|
+
if (score > 0 && (b.kind === 'function' || b.kind === 'method')) score *= 1.18;
|
|
558
|
+
else if (score > 0 && (b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' || b.kind === 'struct')) score *= 1.08;
|
|
559
|
+
|
|
560
|
+
if (score > 0) {
|
|
561
|
+
if (b.role === 'doc' && !roleIntents.wantsDocs) score *= 0.10;
|
|
562
|
+
else if (b.role === 'test' && !roleIntents.wantsTests) score *= 0.20;
|
|
563
|
+
else if (b.role === 'source') score *= 1.25;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
return { ...b, score };
|
|
567
|
+
}).sort((a, b) => b.score - a.score);
|
|
568
|
+
|
|
569
|
+
// Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
|
|
570
|
+
const symbolMap = new Map();
|
|
571
|
+
const constSymbolNames = new Set();
|
|
572
|
+
for (let i = 0; i < scored.length; i++) {
|
|
573
|
+
const b = scored[i];
|
|
574
|
+
if (b.name && b.kind !== 'module' && !controlWords.has(b.name)) {
|
|
575
|
+
const rawShort = b.name.includes('.') ? b.name.split('.').pop() : b.name;
|
|
576
|
+
const names = (b.kind === 'const' && rawShort.includes(','))
|
|
577
|
+
? rawShort.split(',').map((s) => s.trim()).filter(Boolean)
|
|
578
|
+
: [rawShort];
|
|
579
|
+
for (const sn of names) {
|
|
580
|
+
if (!sn || /^__.*__$/.test(sn)) continue;
|
|
581
|
+
if (!symbolMap.has(sn)) symbolMap.set(sn, []);
|
|
582
|
+
symbolMap.get(sn).push(i);
|
|
583
|
+
if (b.kind === 'const') constSymbolNames.add(sn);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const callAdj = Array.from({ length: scored.length }, () => new Set());
|
|
589
|
+
const definedNames = Array.from(symbolMap.keys());
|
|
590
|
+
for (let i = 0; i < scored.length; i++) {
|
|
591
|
+
const caller = scored[i];
|
|
592
|
+
const maskedCaller = maskFn(caller.full);
|
|
593
|
+
for (const sym of definedNames) {
|
|
594
|
+
const callerShort = caller.name.includes('.') ? caller.name.split('.').pop() : caller.name;
|
|
595
|
+
if (sym === caller.name || sym === callerShort) continue;
|
|
596
|
+
if (maskedCaller.includes(sym)) {
|
|
597
|
+
const esc = sym.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&');
|
|
598
|
+
const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
|
|
599
|
+
const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
|
|
600
|
+
if (re.test(maskedCaller)) {
|
|
601
|
+
for (const t of (symbolMap.get(sym) || [])) {
|
|
602
|
+
const target = scored[t];
|
|
603
|
+
if (caller.filePath === target.filePath && (
|
|
604
|
+
(caller.kind === 'class' && target.kind === 'method' && target.name.startsWith(caller.name + '.')) ||
|
|
605
|
+
(target.kind === 'class' && caller.kind === 'method' && caller.name.startsWith(target.name + '.'))
|
|
606
|
+
)) continue;
|
|
607
|
+
callAdj[i].add(t);
|
|
608
|
+
callAdj[t].add(i);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Focal selection: strictly prefer source matches over docs/tests + class/method smart deduplication
|
|
616
|
+
const hasSourceMatches = scored.some((b) => b.role === 'source' && b.score > 0);
|
|
617
|
+
const eligibleIndices = [];
|
|
618
|
+
for (let i = 0; i < scored.length; i++) {
|
|
619
|
+
if (scored[i].score <= 0) continue;
|
|
620
|
+
if (hasSourceMatches && scored[i].role !== 'source') continue;
|
|
621
|
+
eligibleIndices.push(i);
|
|
622
|
+
}
|
|
623
|
+
const focalSet = new Set();
|
|
624
|
+
const promotedParentClassSet = new Set();
|
|
625
|
+
if (eligibleIndices.length > 0) {
|
|
626
|
+
const topScore = scored[eligibleIndices[0]].score;
|
|
627
|
+
const candidateIdx = eligibleIndices
|
|
628
|
+
.filter((idx, rank) => (rank < 3 && scored[idx].score >= topScore * 0.3) || scored[idx].score >= topScore * 0.55)
|
|
629
|
+
.slice(0, 5);
|
|
630
|
+
const candidateChosen = new Set();
|
|
631
|
+
for (const idx of candidateIdx) {
|
|
632
|
+
const b = scored[idx];
|
|
633
|
+
if (b.kind === 'class' && b.lineCount > 35) {
|
|
634
|
+
const childIndices = [];
|
|
635
|
+
for (let ci = 0; ci < scored.length; ci++) {
|
|
636
|
+
const c = scored[ci];
|
|
637
|
+
if (c.filePath === b.filePath && c.kind === 'method' && c.name.startsWith(b.name + '.')) {
|
|
638
|
+
const cShort = c.name.split('.').pop().toLowerCase();
|
|
639
|
+
const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
|
|
640
|
+
if (explicitHit || c.score >= b.score * 0.55) {
|
|
641
|
+
childIndices.push(ci);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (childIndices.length > 0) {
|
|
646
|
+
promotedParentClassSet.add(idx);
|
|
647
|
+
for (const ci of childIndices.slice(0, 3)) candidateChosen.add(ci);
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
candidateChosen.add(idx);
|
|
652
|
+
}
|
|
653
|
+
for (const idx of candidateChosen) {
|
|
654
|
+
const b = scored[idx];
|
|
655
|
+
if (b.kind === 'method') {
|
|
656
|
+
const clsName = b.name.split('.')[0];
|
|
657
|
+
const hasFullParent = [...candidateChosen].some((pIdx) => {
|
|
658
|
+
const p = scored[pIdx];
|
|
659
|
+
return p && p.kind === 'class' && p.filePath === b.filePath && p.name === clsName;
|
|
660
|
+
});
|
|
661
|
+
if (hasFullParent) continue;
|
|
662
|
+
}
|
|
663
|
+
focalSet.add(idx);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// BFS from final focalSet
|
|
668
|
+
const hopDistances = new Map();
|
|
669
|
+
const focalFiles = new Set();
|
|
670
|
+
const bfsQ = [...focalSet];
|
|
671
|
+
for (const fi of bfsQ) {
|
|
672
|
+
hopDistances.set(fi, 0);
|
|
673
|
+
focalFiles.add(scored[fi].filePath);
|
|
674
|
+
}
|
|
675
|
+
let qHead = 0;
|
|
676
|
+
while (qHead < bfsQ.length) {
|
|
677
|
+
const curr = bfsQ[qHead++];
|
|
678
|
+
const curHop = hopDistances.get(curr) ?? 0;
|
|
679
|
+
if (curHop >= maxHops) continue;
|
|
680
|
+
for (const nbr of callAdj[curr]) {
|
|
681
|
+
if (!hopDistances.has(nbr)) {
|
|
682
|
+
hopDistances.set(nbr, curHop + 1);
|
|
683
|
+
bfsQ.push(nbr);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, then 1/2-hop source -> test -> doc
|
|
689
|
+
const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
|
|
690
|
+
const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
|
|
691
|
+
const focA = focalSet.has(a) ? 0 : 1;
|
|
692
|
+
const focB = focalSet.has(b) ? 0 : 1;
|
|
693
|
+
if (focA !== focB) return focA - focB;
|
|
694
|
+
const parA = promotedParentClassSet.has(a) ? 0 : 1;
|
|
695
|
+
const parB = promotedParentClassSet.has(b) ? 0 : 1;
|
|
696
|
+
if (parA !== parB) return parA - parB;
|
|
697
|
+
const rrA = roleRank(scored[a].role);
|
|
698
|
+
const rrB = roleRank(scored[b].role);
|
|
699
|
+
if (rrA !== rrB) return rrA - rrB;
|
|
700
|
+
const hopA = hopDistances.get(a) ?? 99;
|
|
701
|
+
const hopB = hopDistances.get(b) ?? 99;
|
|
702
|
+
if (hopA !== hopB) return hopA - hopB;
|
|
703
|
+
return scored[b].score - scored[a].score;
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
let remaining = budget;
|
|
707
|
+
let docBudgetUsed = 0;
|
|
708
|
+
let testBudgetUsed = 0;
|
|
709
|
+
const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
|
|
710
|
+
const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
|
|
711
|
+
const dirBudgetUsed = {};
|
|
712
|
+
const maxDirBudget = budget * 0.72;
|
|
713
|
+
|
|
714
|
+
const includedIds = new Set();
|
|
715
|
+
const includedFiles = [];
|
|
716
|
+
const includedFilesSet = new Set();
|
|
717
|
+
const fullStart1EndLine = new Map();
|
|
718
|
+
const coveredRangesByFile = new Map();
|
|
719
|
+
const partialFiles = new Set();
|
|
720
|
+
const selectedByFile = new Map();
|
|
721
|
+
const fullParentClassesByFile = new Map();
|
|
722
|
+
const skelCandidates = [];
|
|
723
|
+
const candidateItems = [];
|
|
724
|
+
|
|
725
|
+
const addCoveredRange = (fp, s, e) => {
|
|
726
|
+
if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
|
|
727
|
+
coveredRangesByFile.get(fp).push([s, e]);
|
|
728
|
+
};
|
|
729
|
+
const addSelectedBlock = (fp, entry) => {
|
|
730
|
+
if (!includedFilesSet.has(fp)) {
|
|
731
|
+
includedFilesSet.add(fp);
|
|
732
|
+
includedFiles.push(fp);
|
|
733
|
+
}
|
|
734
|
+
if (!selectedByFile.has(fp)) selectedByFile.set(fp, []);
|
|
735
|
+
selectedByFile.get(fp).push(entry);
|
|
736
|
+
};
|
|
737
|
+
const canUseRoleBudget = (role, cost) => {
|
|
738
|
+
if (role === 'doc') return docBudgetUsed + cost <= docBudgetCap;
|
|
739
|
+
if (role === 'test') return testBudgetUsed + cost <= testBudgetCap;
|
|
740
|
+
return true;
|
|
741
|
+
};
|
|
742
|
+
const addRoleBudget = (role, cost) => {
|
|
743
|
+
if (role === 'doc') docBudgetUsed += cost;
|
|
744
|
+
else if (role === 'test') testBudgetUsed += cost;
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
for (const idx of allocOrder) {
|
|
748
|
+
const item = scored[idx];
|
|
749
|
+
if (item.kind === 'method') {
|
|
750
|
+
const clsName = item.name.split('.')[0];
|
|
751
|
+
const fullSet = fullParentClassesByFile.get(item.filePath);
|
|
752
|
+
if (fullSet && fullSet.has(clsName)) continue;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const topDir = item.filePath.split('/')[0] || 'root';
|
|
756
|
+
const curDir = dirBudgetUsed[topDir] || 0;
|
|
757
|
+
const hop = hopDistances.get(idx);
|
|
758
|
+
const isFocal = focalSet.has(idx);
|
|
759
|
+
const isPromotedParent = promotedParentClassSet.has(idx);
|
|
760
|
+
const key = item.filePath + ':' + item.startLine;
|
|
761
|
+
const win = configWindowByKey.get(key);
|
|
762
|
+
|
|
763
|
+
if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
|
|
764
|
+
remaining = Math.max(0, remaining - item.rawTk);
|
|
765
|
+
dirBudgetUsed[topDir] = curDir + item.rawTk;
|
|
766
|
+
addRoleBudget(item.role, item.rawTk);
|
|
767
|
+
includedIds.add(key);
|
|
768
|
+
if (item.kind === 'class') {
|
|
769
|
+
if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, new Set());
|
|
770
|
+
fullParentClassesByFile.get(item.filePath).add(item.name);
|
|
771
|
+
}
|
|
772
|
+
if (win) {
|
|
773
|
+
for (const r of win.ranges) {
|
|
774
|
+
addCoveredRange(item.filePath, r[0], r[1]);
|
|
775
|
+
if (r[0] === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, r[1]));
|
|
776
|
+
}
|
|
777
|
+
} else {
|
|
778
|
+
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
779
|
+
if (item.startLine === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
|
|
780
|
+
}
|
|
781
|
+
addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
|
|
782
|
+
} else if (isPromotedParent && item.skelTk <= remaining) {
|
|
783
|
+
remaining -= item.skelTk;
|
|
784
|
+
dirBudgetUsed[topDir] = curDir + item.skelTk;
|
|
785
|
+
includedIds.add(key);
|
|
786
|
+
partialFiles.add(item.filePath);
|
|
787
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
|
|
788
|
+
} else if (item.skelTk <= remaining && (curDir + item.skelTk <= maxDirBudget || item.role === 'source') && canUseRoleBudget(item.role, item.skelTk)) {
|
|
789
|
+
const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
|
|
790
|
+
const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
|
|
791
|
+
if (linked) {
|
|
792
|
+
remaining -= item.skelTk;
|
|
793
|
+
dirBudgetUsed[topDir] = curDir + item.skelTk;
|
|
794
|
+
addRoleBudget(item.role, item.skelTk);
|
|
795
|
+
includedIds.add(key);
|
|
796
|
+
partialFiles.add(item.filePath);
|
|
797
|
+
if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
798
|
+
if (autoExpand && item.role === 'source' && !isPromotedParent) {
|
|
799
|
+
skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
|
|
800
|
+
} else {
|
|
801
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
|
|
802
|
+
}
|
|
803
|
+
} else {
|
|
804
|
+
partialFiles.add(item.filePath);
|
|
805
|
+
candidateItems.push(item);
|
|
806
|
+
}
|
|
807
|
+
} else {
|
|
808
|
+
partialFiles.add(item.filePath);
|
|
809
|
+
candidateItems.push(item);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const autoExpandedNames = [];
|
|
814
|
+
if (autoExpand && skelCandidates.length > 0) {
|
|
815
|
+
for (const cand of skelCandidates) {
|
|
816
|
+
const it = cand.item;
|
|
817
|
+
const delta = Math.max(0, it.rawTk - it.skelTk);
|
|
818
|
+
const isComplexCluster = (cand.hop !== null || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
|
|
819
|
+
const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
|
|
820
|
+
if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
|
|
821
|
+
remaining -= delta;
|
|
822
|
+
autoExpandedNames.push(it.name);
|
|
823
|
+
if (cand.win) {
|
|
824
|
+
for (const r of cand.win.ranges) {
|
|
825
|
+
addCoveredRange(it.filePath, r[0], r[1]);
|
|
826
|
+
if (r[0] === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, r[1]));
|
|
827
|
+
}
|
|
828
|
+
} else {
|
|
829
|
+
addCoveredRange(it.filePath, it.startLine, it.endLine);
|
|
830
|
+
if (it.startLine === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, it.endLine));
|
|
831
|
+
}
|
|
832
|
+
addSelectedBlock(it.filePath, { tier: 'full', item: it, win: cand.win, autoExpanded: true });
|
|
833
|
+
} else {
|
|
834
|
+
addSelectedBlock(it.filePath, { tier: 'skeleton', item: it, win: cand.win, hop: cand.hop });
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (includedFiles.length === 0) {
|
|
840
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
841
|
+
return [
|
|
842
|
+
'<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
|
|
843
|
+
' <note>WARNING: 0 matches found for query "' + escapeXmlText(rawQuery) + '". Do NOT guess code from this file tree alone—pick valid file paths or symbol names from the tree below and call context_slice again.</note>',
|
|
844
|
+
' <repository_file_tree>',
|
|
845
|
+
...treeLines,
|
|
846
|
+
' </repository_file_tree>',
|
|
847
|
+
'</context_slice>'
|
|
848
|
+
].join('\n');
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
const headerByFile = new Map();
|
|
852
|
+
const headerEndByFile = new Map();
|
|
853
|
+
for (const fp of includedFiles) {
|
|
854
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
855
|
+
const entries = selectedByFile.get(fp) || [];
|
|
856
|
+
const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
|
|
857
|
+
if (hasStart1ModuleSkel) continue;
|
|
858
|
+
const hdr = fileHeaders.get(fp);
|
|
859
|
+
if (!hdr) continue;
|
|
860
|
+
if ((fullStart1EndLine.get(fp) || 0) >= hdr.endLine) continue;
|
|
861
|
+
headerEndByFile.set(fp, hdr.endLine);
|
|
862
|
+
headerByFile.set(fp, hdr);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const footerByFile = new Map();
|
|
866
|
+
for (const fp of includedFiles) {
|
|
867
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
868
|
+
const ftr = fileFooters.get(fp);
|
|
869
|
+
if (!ftr) continue;
|
|
870
|
+
const ranges = coveredRangesByFile.get(fp) || [];
|
|
871
|
+
const totalLines = fileLineCounts.get(fp) || 0;
|
|
872
|
+
const wholeFileCovered = ranges.some((r) => r[0] <= 1 && r[1] >= totalLines);
|
|
873
|
+
if (!partialFiles.has(fp) && wholeFileCovered) continue;
|
|
874
|
+
const hdrEnd = headerEndByFile.get(fp) || 0;
|
|
875
|
+
const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some((r) => c.startLine >= r[0] && c.endLine <= r[1]));
|
|
876
|
+
if (uncovered.length > 0) {
|
|
877
|
+
footerByFile.set(fp, {
|
|
878
|
+
startLine: uncovered[0].startLine,
|
|
879
|
+
endLine: uncovered[uncovered.length - 1].endLine,
|
|
880
|
+
text: uncovered.map((c) => c.text).join('\n'),
|
|
881
|
+
chunks: uncovered
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const used = Math.max(0, budget - remaining);
|
|
887
|
+
const expandAttr = autoExpandedNames.length > 0 ? ' autoExpanded="' + escapeXmlAttr(autoExpandedNames.join(',')) + '"' : '';
|
|
888
|
+
const out = [
|
|
889
|
+
'<context_slice mode="progressive-structural-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + used + '"' + expandAttr + '>'
|
|
890
|
+
];
|
|
891
|
+
|
|
892
|
+
for (const fp of includedFiles) {
|
|
893
|
+
const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
|
|
894
|
+
const presentClassNames = new Set(rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item.name));
|
|
895
|
+
const entries = rawEntries.filter(
|
|
896
|
+
(e) => !(e.tier === 'skeleton' && e.item.kind === 'method' && presentClassNames.has(e.item.name.split('.')[0])),
|
|
897
|
+
);
|
|
898
|
+
const fullEntries = entries.filter((e) => e.tier === 'full');
|
|
899
|
+
const hdr = headerByFile.get(fp);
|
|
900
|
+
const ftr = footerByFile.get(fp);
|
|
901
|
+
const totalLines = fileLineCounts.get(fp) || 0;
|
|
902
|
+
const shownRanges = [];
|
|
903
|
+
if (hdr) shownRanges.push([1, hdr.endLine]);
|
|
904
|
+
for (const ent of entries) {
|
|
905
|
+
if (ent.win) shownRanges.push(...ent.win.ranges);
|
|
906
|
+
else shownRanges.push([ent.item.startLine, ent.item.endLine]);
|
|
907
|
+
}
|
|
908
|
+
if (ftr) {
|
|
909
|
+
for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
|
|
910
|
+
}
|
|
911
|
+
out.push(' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRanges) + '">');
|
|
912
|
+
if (hdr) {
|
|
913
|
+
out.push(' <file_header lines="1-' + hdr.endLine + '">');
|
|
914
|
+
out.push(hdr.header);
|
|
915
|
+
out.push(' </file_header>');
|
|
916
|
+
}
|
|
917
|
+
for (const ent of entries) {
|
|
918
|
+
const it = ent.item;
|
|
919
|
+
if (ent.tier === 'full') {
|
|
920
|
+
const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
|
|
921
|
+
const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
|
|
922
|
+
const autoAttr = ent.autoExpanded ? ' autoExpanded="true"' : '';
|
|
923
|
+
out.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + linesAttr + '"' + parserAttr + autoAttr + '>');
|
|
924
|
+
out.push(ent.win ? ent.win.windowedCode : it.full);
|
|
925
|
+
out.push(' </focal>');
|
|
926
|
+
} else {
|
|
927
|
+
let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
|
|
928
|
+
if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
|
|
929
|
+
const expandedChildRanges = fullEntries
|
|
930
|
+
.filter((fe) => fe.item.kind === 'method' && fe.item.name.startsWith(it.name + '.'))
|
|
931
|
+
.map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
|
|
932
|
+
if (expandedChildRanges.length > 0) {
|
|
933
|
+
skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
const hopAttr = (ent.hop !== null && ent.hop !== undefined) ? ' hop="' + ent.hop + '"' : '';
|
|
937
|
+
const skelLinesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
|
|
938
|
+
out.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + skelLinesAttr + '"' + hopAttr + '>');
|
|
939
|
+
out.push(skelBody);
|
|
940
|
+
out.push(' </skeleton>');
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (ftr) {
|
|
944
|
+
out.push(' <file_footer lines="' + ftr.startLine + '-' + ftr.endLine + '">');
|
|
945
|
+
out.push(ftr.text);
|
|
946
|
+
out.push(' </file_footer>');
|
|
947
|
+
}
|
|
948
|
+
out.push(' </file>');
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
const omitted = candidateItems.filter((it) => it.score > 0 && !includedIds.has(it.filePath + ':' + it.startLine)).slice(0, 3);
|
|
952
|
+
if (omitted.length > 0) {
|
|
953
|
+
out.push(' <omitted_top_matches>');
|
|
954
|
+
for (const o of omitted) {
|
|
955
|
+
out.push(' <!-- Omitted: ' + o.filePath + ':' + o.startLine + ' (' + o.name + ', score: ' + o.score.toFixed(1) + ') — consider expanding -->');
|
|
956
|
+
}
|
|
957
|
+
out.push(' </omitted_top_matches>');
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
out.push('</context_slice>');
|
|
961
|
+
return out.join('\n');
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
|
|
18
965
|
const CJK_RE = /[一-鿿-ゟ゠-ヿ가-]/;
|
|
19
966
|
const CJK_RUN_RE = new RegExp('[一-鿿-ゟ゠-ヿ가-]+', 'g');
|
|
20
967
|
const CJK_WORDS = {
|
|
@@ -362,37 +1309,59 @@ function bilingualLookup(term) {
|
|
|
362
1309
|
return out;
|
|
363
1310
|
}
|
|
364
1311
|
function expandQueryTerms(query) {
|
|
365
|
-
const
|
|
366
|
-
|
|
367
|
-
const
|
|
1312
|
+
const trimmed = String(query || '').trim();
|
|
1313
|
+
if (!trimmed) return [];
|
|
1314
|
+
const q = trimmed.toLowerCase();
|
|
1315
|
+
const terms = new Set();
|
|
1316
|
+
const asciiParts = q.match(/[a-z0-9_]+(?:[.-][a-z0-9_]+)*/g) || [];
|
|
368
1317
|
for (const p of asciiParts) {
|
|
369
|
-
if (p.length >= 2
|
|
370
|
-
|
|
1318
|
+
if (p.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(p)) {
|
|
1319
|
+
terms.add(p);
|
|
1320
|
+
if (/^v\d/.test(p) && p.length >= 3) terms.add(p.slice(1));
|
|
1321
|
+
if (p.includes('.') || p.includes('-')) {
|
|
1322
|
+
for (const sub of p.split(/[.-]/)) {
|
|
1323
|
+
if (sub.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(sub)) terms.add(sub);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
for (const t of bilingualLookup(p)) terms.add(t);
|
|
1327
|
+
}
|
|
371
1328
|
}
|
|
372
|
-
if (containsCJK(
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
for (const
|
|
1329
|
+
if (containsCJK(trimmed)) {
|
|
1330
|
+
const cleanedCjk = trimmed.replace(ZH_CONVERSATIONAL_STOPWORDS_RE, ' ');
|
|
1331
|
+
if (containsCJK(cleanedCjk)) {
|
|
1332
|
+
for (const gram of tokenizeCJK2gram(cleanedCjk)) {
|
|
1333
|
+
terms.add(gram);
|
|
1334
|
+
for (const t of bilingualLookup(gram)) terms.add(t);
|
|
1335
|
+
}
|
|
1336
|
+
for (const run of cleanedCjk.match(CJK_RUN_RE) || []) {
|
|
1337
|
+
terms.add(run);
|
|
1338
|
+
for (const t of bilingualLookup(run)) terms.add(t);
|
|
1339
|
+
}
|
|
376
1340
|
}
|
|
377
|
-
for (const run of q.match(CJK_RUN_RE) || []) terms.add(run);
|
|
378
1341
|
}
|
|
379
|
-
|
|
1342
|
+
const snapshot = [...terms];
|
|
1343
|
+
for (const term of snapshot) {
|
|
1344
|
+
for (const t of bilingualLookup(term)) terms.add(t);
|
|
1345
|
+
}
|
|
1346
|
+
const collected = [...terms].filter(Boolean);
|
|
1347
|
+
const nonSyntax = collected.filter((t) => !SYNTAX_NOISE_WORDS.has(t));
|
|
1348
|
+
return nonSyntax.length > 0 ? nonSyntax : collected;
|
|
380
1349
|
}
|
|
381
1350
|
|
|
382
1351
|
const TOOL_DEF = {
|
|
383
1352
|
name: 'get_context_slice',
|
|
384
|
-
description: 'PRIMARY code-reading tool (v0.
|
|
1353
|
+
description: 'PRIMARY code-reading tool (v0.4.1) with Tree-sitter WASM / State-Machine structural parsing, True Call Graph, TF-IDF & Dual-State File Tree.',
|
|
385
1354
|
annotations: { readOnlyHint: true },
|
|
386
1355
|
inputSchema: {
|
|
387
1356
|
type: 'object',
|
|
388
1357
|
properties: {
|
|
389
|
-
query: { type: 'string', description: 'Task or symbol keywords (Supports CJK multi-language + bilingual
|
|
1358
|
+
query: { type: 'string', description: 'Task or symbol keywords (Supports CJK multi-language + bilingual matching; omit or pass "" to return repository file tree overview)' },
|
|
390
1359
|
projectPath: { type: 'string', description: 'Absolute path to target project folder' },
|
|
391
1360
|
subPath: { type: 'string', description: 'Optional sub-directory path to sandbox/restrict project scanning (e.g. src/auth)' },
|
|
392
1361
|
budget: { type: 'number', description: 'Max token budget (default 32768)' },
|
|
393
1362
|
autoExpand: { type: 'boolean', description: 'Auto-expand high-complexity skeleton clusters (default true)' }
|
|
394
1363
|
},
|
|
395
|
-
required: [
|
|
1364
|
+
required: []
|
|
396
1365
|
}
|
|
397
1366
|
};
|
|
398
1367
|
|
|
@@ -418,7 +1387,7 @@ const IGNORE_DIRS = new Set([
|
|
|
418
1387
|
]);
|
|
419
1388
|
|
|
420
1389
|
const BINARY_EXT_RE = /\.(png|jpe?g|gif|webp|bmp|ico|icns|tiff?|svg|mp4|mov|avi|mkv|webm|wmv|flv|mp3|wav|ogg|flac|aac|m4a|wma|zip|rar|7z|tar|gz|bz2|xz|tgz|iso|dmg|exe|dll|so|dylib|bin|o|a|obj|lib|wasm|class|jar|war|pyc|pyo|ttf|otf|woff2?|eot|pdf|docx?|xlsx?|pptx?|odt|ods|odp|rtf|db|sqlite3?|mdb|psd|ai|sketch|fig|xd|blend|fbx|glb|gltf)$/i;
|
|
421
|
-
const NOISE_FILE_RE = /(^|\/)(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;
|
|
1390
|
+
const NOISE_FILE_RE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|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;
|
|
422
1391
|
const CONTROL_WORDS = new Set(['if', 'else', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'typeof', 'do', 'try']);
|
|
423
1392
|
|
|
424
1393
|
// Pure in-memory mtime cache: Map<filePath, { mtime: number, parserMode: string, items: Array<...> }>
|
|
@@ -582,24 +1551,49 @@ async function extractBlocksWithTreeSitter(code, ext, fileName) {
|
|
|
582
1551
|
if (!bodyCap || !nameCap) continue;
|
|
583
1552
|
const startLine = bodyCap.node.startPosition.row + 1;
|
|
584
1553
|
const endLine = bodyCap.node.endPosition.row + 1;
|
|
585
|
-
const
|
|
586
|
-
|
|
587
|
-
if (!name || seen.has(key)) continue;
|
|
588
|
-
seen.add(key);
|
|
1554
|
+
const rawName = String(nameCap.node.text || '').trim();
|
|
1555
|
+
if (!rawName) continue;
|
|
589
1556
|
|
|
590
1557
|
const nodeType = bodyCap.node.type || 'function';
|
|
591
|
-
|
|
1558
|
+
let name = rawName;
|
|
1559
|
+
let kind = nodeType.includes('class') ? 'class'
|
|
592
1560
|
: nodeType.includes('interface') ? 'interface'
|
|
593
1561
|
: nodeType.includes('struct') ? 'struct'
|
|
594
1562
|
: nodeType.includes('impl') ? 'impl'
|
|
595
1563
|
: nodeType.includes('method') ? 'method'
|
|
596
1564
|
: 'function';
|
|
597
1565
|
|
|
1566
|
+
if (langName === 'python' && nodeType === 'function_definition') {
|
|
1567
|
+
let p = bodyCap.node.parent;
|
|
1568
|
+
while (p) {
|
|
1569
|
+
if (p.type === 'class_definition') {
|
|
1570
|
+
const clsNameNode = p.childForFieldName ? p.childForFieldName('name') : null;
|
|
1571
|
+
const clsName = clsNameNode ? String(clsNameNode.text || '').trim() : '';
|
|
1572
|
+
if (clsName) {
|
|
1573
|
+
name = `${clsName}.${rawName}`;
|
|
1574
|
+
kind = 'method';
|
|
1575
|
+
}
|
|
1576
|
+
break;
|
|
1577
|
+
}
|
|
1578
|
+
p = p.parent;
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
const key = name + '@' + startLine + '-' + endLine;
|
|
1583
|
+
if (seen.has(key)) continue;
|
|
1584
|
+
seen.add(key);
|
|
1585
|
+
|
|
598
1586
|
const full = lines.slice(startLine - 1, endLine).join('\n');
|
|
599
1587
|
let skeleton = full;
|
|
600
|
-
if (
|
|
1588
|
+
if (langName === 'python' && kind === 'class') {
|
|
1589
|
+
skeleton = buildPythonClassSkeleton(full, startLine);
|
|
1590
|
+
} else if (endLine - startLine >= 3) {
|
|
601
1591
|
if (langName === 'python') {
|
|
602
|
-
|
|
1592
|
+
const sigEndIdx = findPythonSignatureEndIdx(lines, startLine - 1);
|
|
1593
|
+
const indentStr = (lines[startLine - 1].match(/^\s*/) || [''])[0];
|
|
1594
|
+
const sigText = lines.slice(startLine - 1, sigEndIdx + 1).join('\n');
|
|
1595
|
+
const foldedLines = Math.max(1, endLine - (sigEndIdx + 1));
|
|
1596
|
+
skeleton = foldedLines > 2 ? `${sigText}\n${indentStr} # ... ${foldedLines} lines folded` : full;
|
|
603
1597
|
} else {
|
|
604
1598
|
const sigIdx = full.indexOf('{');
|
|
605
1599
|
if (sigIdx !== -1 && kind !== 'interface') {
|
|
@@ -666,20 +1660,10 @@ function extractBlocks(code, ext, fileName) {
|
|
|
666
1660
|
let m = null;
|
|
667
1661
|
|
|
668
1662
|
if (e === '.py' || e === '.pyw') {
|
|
669
|
-
|
|
670
|
-
if (
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
let end = i;
|
|
674
|
-
for (let j = i + 1; j < lines.length; j++) {
|
|
675
|
-
if (lines[j].trim() === '' || /^\s+/.test(lines[j])) end = j;
|
|
676
|
-
else break;
|
|
677
|
-
}
|
|
678
|
-
while (end > i && lines[end].trim() === '') end--;
|
|
679
|
-
const full = lines.slice(i, end + 1).join('\n');
|
|
680
|
-
const skeleton = end - i > 2 ? `${lines[i]}\n # ... ${end - i} lines folded` : full;
|
|
681
|
-
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
682
|
-
i = end;
|
|
1663
|
+
const pyRes = extractPythonBlocks(lines, i);
|
|
1664
|
+
if (pyRes) {
|
|
1665
|
+
blocks.push(...pyRes.blocks);
|
|
1666
|
+
i = pyRes.endIdx;
|
|
683
1667
|
continue;
|
|
684
1668
|
}
|
|
685
1669
|
}
|
|
@@ -1167,6 +2151,31 @@ function extractFileFooter(content, tailLines = 20) {
|
|
|
1167
2151
|
}
|
|
1168
2152
|
|
|
1169
2153
|
|
|
2154
|
+
function collectFileOverview(root, scanRoot) {
|
|
2155
|
+
const files = [];
|
|
2156
|
+
const walk = (d) => {
|
|
2157
|
+
if (!fs.existsSync(d)) return;
|
|
2158
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
2159
|
+
if (IGNORE_DIRS.has(e.name)) continue;
|
|
2160
|
+
const full = path.join(d, e.name);
|
|
2161
|
+
if (e.isDirectory()) walk(full);
|
|
2162
|
+
else if (isAcceptedFile(full.replace(/\\/g, '/'))) files.push(full);
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
walk(scanRoot);
|
|
2166
|
+
const fileEntries = [];
|
|
2167
|
+
for (const f of files) {
|
|
2168
|
+
try {
|
|
2169
|
+
const buf = fs.readFileSync(f);
|
|
2170
|
+
if (isBinaryBuffer(buf)) continue;
|
|
2171
|
+
const relPath = path.relative(root, f).replace(/\\/g, '/');
|
|
2172
|
+
const lineCount = buf.toString('utf8').replace(/\r\n/g, '\n').split('\n').length;
|
|
2173
|
+
fileEntries.push({ relPath, lineCount });
|
|
2174
|
+
} catch {}
|
|
2175
|
+
}
|
|
2176
|
+
return fileEntries;
|
|
2177
|
+
}
|
|
2178
|
+
|
|
1170
2179
|
async function collectProjectBlocks(root, scanRoot) {
|
|
1171
2180
|
const files = [];
|
|
1172
2181
|
const walk = (d) => {
|
|
@@ -1175,7 +2184,7 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
1175
2184
|
if (IGNORE_DIRS.has(e.name)) continue;
|
|
1176
2185
|
const full = path.join(d, e.name);
|
|
1177
2186
|
if (e.isDirectory()) walk(full);
|
|
1178
|
-
else if (isAcceptedFile(
|
|
2187
|
+
else if (isAcceptedFile(full.replace(/\\/g, '/'))) files.push(full);
|
|
1179
2188
|
}
|
|
1180
2189
|
};
|
|
1181
2190
|
walk(scanRoot);
|
|
@@ -1190,8 +2199,9 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
1190
2199
|
const headerMap = new Map();
|
|
1191
2200
|
const footerMap = new Map();
|
|
1192
2201
|
const lineCountMap = new Map();
|
|
2202
|
+
const fileEntries = [];
|
|
1193
2203
|
for (const f of files) {
|
|
1194
|
-
const rel = path.relative(root, f);
|
|
2204
|
+
const rel = path.relative(root, f).replace(/\\/g, '/');
|
|
1195
2205
|
let stat;
|
|
1196
2206
|
try {
|
|
1197
2207
|
stat = fs.statSync(f);
|
|
@@ -1206,47 +2216,54 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
1206
2216
|
let fileHeader = null;
|
|
1207
2217
|
let fileFooter = null;
|
|
1208
2218
|
let fileLines = 0;
|
|
2219
|
+
const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rel) || DOC_EXT_RE.test(rel);
|
|
1209
2220
|
if (cached && cached.mtime === mtime) {
|
|
1210
2221
|
items = cached.items;
|
|
1211
2222
|
parserMode = cached.parserMode || 'regex';
|
|
1212
|
-
fileHeader = cached.header ?? null;
|
|
1213
|
-
fileFooter = cached.footer ?? null;
|
|
2223
|
+
fileHeader = skipHdrFtr ? null : (cached.header ?? null);
|
|
2224
|
+
fileFooter = skipHdrFtr ? null : (cached.footer ?? null);
|
|
1214
2225
|
fileLines = cached.lineCount || 0;
|
|
1215
2226
|
} else {
|
|
1216
2227
|
const rawBuf = fs.readFileSync(f);
|
|
1217
2228
|
if (isBinaryBuffer(rawBuf)) continue;
|
|
1218
2229
|
const raw = rawBuf.toString('utf8');
|
|
1219
|
-
fileLines = raw.split('\n').length;
|
|
1220
|
-
fileHeader = extractFileHeader(raw);
|
|
1221
|
-
fileFooter = extractFileFooter(raw);
|
|
2230
|
+
fileLines = raw.replace(/\r\n/g, '\n').split('\n').length;
|
|
2231
|
+
fileHeader = skipHdrFtr ? null : extractFileHeader(raw);
|
|
2232
|
+
fileFooter = skipHdrFtr ? null : extractFileFooter(raw);
|
|
1222
2233
|
const ext = path.extname(f);
|
|
1223
|
-
const tsBlocks = await extractBlocksWithTreeSitter(raw, ext, rel);
|
|
2234
|
+
const tsBlocks = skipHdrFtr ? null : await extractBlocksWithTreeSitter(raw, ext, rel);
|
|
1224
2235
|
if (tsBlocks && tsBlocks.length > 0) {
|
|
1225
2236
|
const extraConsts = extractTopLevelConstants(raw, ext, tsBlocks);
|
|
1226
2237
|
items = extraConsts.length > 0 ? [...tsBlocks, ...extraConsts].sort((a, b) => a.startLine - b.startLine) : tsBlocks;
|
|
1227
2238
|
parserMode = 'tree-sitter-wasm';
|
|
1228
2239
|
} else {
|
|
1229
2240
|
items = extractBlocks(raw, ext, rel);
|
|
1230
|
-
parserMode =
|
|
2241
|
+
parserMode = PLAIN_TEXT_CONFIG_EXT_RE.test(rel)
|
|
2242
|
+
? 'plain-text-config'
|
|
2243
|
+
: DOC_EXT_RE.test(rel)
|
|
2244
|
+
? 'markdown-doc'
|
|
2245
|
+
: 'state-machine-regex';
|
|
1231
2246
|
}
|
|
1232
2247
|
FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
|
|
1233
2248
|
}
|
|
1234
2249
|
if (fileHeader) headerMap.set(rel, fileHeader);
|
|
1235
2250
|
if (fileFooter) footerMap.set(rel, fileFooter);
|
|
1236
2251
|
lineCountMap.set(rel, fileLines);
|
|
2252
|
+
fileEntries.push({ relPath: rel, lineCount: fileLines });
|
|
1237
2253
|
|
|
1238
2254
|
for (const b of items) {
|
|
1239
2255
|
allBlocks.push({
|
|
1240
2256
|
...b,
|
|
2257
|
+
filePath: rel,
|
|
1241
2258
|
rel,
|
|
1242
2259
|
parserMode,
|
|
1243
2260
|
lineCount: Math.max(1, b.endLine - b.startLine + 1),
|
|
1244
|
-
rawTk:
|
|
1245
|
-
skelTk:
|
|
2261
|
+
rawTk: estimateTokens(b.full),
|
|
2262
|
+
skelTk: estimateTokens(b.skeleton)
|
|
1246
2263
|
});
|
|
1247
2264
|
}
|
|
1248
2265
|
}
|
|
1249
|
-
return { blocks: allBlocks, headerMap, footerMap, lineCountMap };
|
|
2266
|
+
return { blocks: allBlocks, headerMap, footerMap, lineCountMap, fileEntries };
|
|
1250
2267
|
}
|
|
1251
2268
|
|
|
1252
2269
|
function resolveScanRoot(projectPath, subPath) {
|
|
@@ -1272,48 +2289,69 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
|
|
|
1272
2289
|
const wanted = new Set((symbols || []).map((s) => String(s).toLowerCase()));
|
|
1273
2290
|
const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
|
|
1274
2291
|
let used = 0;
|
|
1275
|
-
const
|
|
1276
|
-
const
|
|
2292
|
+
const expandedFiles = [];
|
|
2293
|
+
const expandedFilesSet = new Set();
|
|
2294
|
+
const expandedByFile = new Map();
|
|
1277
2295
|
const fullStart1EndLine = new Map();
|
|
1278
2296
|
const coveredRangesByFile = new Map();
|
|
2297
|
+
let expandedCount = 0;
|
|
1279
2298
|
for (const b of blocks) {
|
|
1280
2299
|
const match = wanted.has(b.name.toLowerCase()) || [...wanted].some((w) => b.name.toLowerCase().includes(w) || b.rel.toLowerCase().includes(w));
|
|
1281
2300
|
if (match && used + b.rawTk <= budget) {
|
|
1282
2301
|
used += b.rawTk;
|
|
1283
|
-
|
|
2302
|
+
expandedCount++;
|
|
2303
|
+
if (!expandedFilesSet.has(b.rel)) {
|
|
2304
|
+
expandedFilesSet.add(b.rel);
|
|
2305
|
+
expandedFiles.push(b.rel);
|
|
2306
|
+
}
|
|
2307
|
+
if (!expandedByFile.has(b.rel)) expandedByFile.set(b.rel, []);
|
|
2308
|
+
expandedByFile.get(b.rel).push(b);
|
|
1284
2309
|
if (!coveredRangesByFile.has(b.rel)) coveredRangesByFile.set(b.rel, []);
|
|
1285
2310
|
coveredRangesByFile.get(b.rel).push([b.startLine, b.endLine]);
|
|
1286
2311
|
if (b.startLine === 1) {
|
|
1287
2312
|
fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
|
|
1288
2313
|
}
|
|
1289
|
-
expanded.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [MCP: expand_skeleton_cluster]\n${b.full}`);
|
|
1290
2314
|
}
|
|
1291
2315
|
}
|
|
1292
|
-
|
|
1293
|
-
const
|
|
2316
|
+
|
|
2317
|
+
const sections = [];
|
|
1294
2318
|
for (const rel of expandedFiles) {
|
|
1295
2319
|
const hdr = headerMap.get(rel);
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
headerEndByFile.set(rel, hdr.endLine);
|
|
1299
|
-
headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
|
|
1300
|
-
}
|
|
1301
|
-
const footerChunks = [];
|
|
1302
|
-
for (const rel of expandedFiles) {
|
|
2320
|
+
const showHdr = hdr && (fullStart1EndLine.get(rel) || 0) < hdr.endLine;
|
|
2321
|
+
const hdrEnd = showHdr ? hdr.endLine : 0;
|
|
1303
2322
|
const ftr = footerMap.get(rel);
|
|
1304
|
-
if (!ftr) continue;
|
|
1305
2323
|
const ranges = coveredRangesByFile.get(rel) || [];
|
|
1306
2324
|
const totalLines = lineCountMap.get(rel) || 0;
|
|
1307
|
-
|
|
1308
|
-
const
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
2325
|
+
const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
|
|
2326
|
+
const uncoveredFooter = (!wholeFileCovered && ftr)
|
|
2327
|
+
? ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e))
|
|
2328
|
+
: [];
|
|
2329
|
+
const shownRanges = [];
|
|
2330
|
+
if (showHdr) shownRanges.push([1, hdr.endLine]);
|
|
2331
|
+
const items = (expandedByFile.get(rel) || []).slice().sort((a, b) => a.startLine - b.startLine);
|
|
2332
|
+
for (const it of items) shownRanges.push([it.startLine, it.endLine]);
|
|
2333
|
+
for (const c of uncoveredFooter) shownRanges.push([c.startLine, c.endLine]);
|
|
2334
|
+
|
|
2335
|
+
sections.push(` <file path="${escapeXmlAttr(rel)}" total_lines="${totalLines}" shown_lines="${formatShownLines(shownRanges)}">`);
|
|
2336
|
+
if (showHdr) {
|
|
2337
|
+
sections.push(` <file_header lines="1-${hdr.endLine}">`);
|
|
2338
|
+
sections.push(hdr.header);
|
|
2339
|
+
sections.push(' </file_header>');
|
|
2340
|
+
}
|
|
2341
|
+
for (const it of items) {
|
|
2342
|
+
sections.push(` <focal symbol="${escapeXmlAttr(it.name)}" lines="${it.startLine}-${it.endLine}" source="expand_skeleton_cluster">`);
|
|
2343
|
+
sections.push(it.full);
|
|
2344
|
+
sections.push(' </focal>');
|
|
1312
2345
|
}
|
|
2346
|
+
if (uncoveredFooter.length > 0) {
|
|
2347
|
+
sections.push(` <file_footer lines="${uncoveredFooter[0].startLine}-${uncoveredFooter[uncoveredFooter.length - 1].endLine}">`);
|
|
2348
|
+
sections.push(uncoveredFooter.map((c) => c.text).join('\n'));
|
|
2349
|
+
sections.push(' </file_footer>');
|
|
2350
|
+
}
|
|
2351
|
+
sections.push(' </file>');
|
|
1313
2352
|
}
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
return `<skeleton_expansion root="${root}" subPath="${subPath || ''}" expanded="${expanded.length}" used="${used}">${hdrTag}\n${expanded.join('\n\n')}${ftrTag}\n</skeleton_expansion>`;
|
|
2353
|
+
|
|
2354
|
+
return `<skeleton_expansion root="${escapeXmlAttr(root)}" subPath="${escapeXmlAttr(subPath || '')}" expanded="${expandedCount}" used="${used}">\n${sections.join('\n')}\n</skeleton_expansion>`;
|
|
1317
2355
|
} catch (err) {
|
|
1318
2356
|
return `Error: ${err.message}`;
|
|
1319
2357
|
}
|
|
@@ -1322,217 +2360,52 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
|
|
|
1322
2360
|
async function sliceProject(query, projectPath, budget = 32768, autoExpand = true, subPath) {
|
|
1323
2361
|
try {
|
|
1324
2362
|
const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
|
|
1325
|
-
const
|
|
1326
|
-
const
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
const bodyOcc = lower.split(t).length - 1;
|
|
1350
|
-
const bodyScore = Math.min(12, 2.5 * Math.log1p(bodyOcc));
|
|
1351
|
-
score += (nameMatch + pathMatch + bodyScore) * idf * scarcityMultiplier;
|
|
1352
|
-
}
|
|
1353
|
-
return { ...b, score };
|
|
1354
|
-
}).sort((a, b) => b.score - a.score);
|
|
1355
|
-
|
|
1356
|
-
// 構建專案 SymbolMap 與真實依賴圖 (True Call Graph + Constants)
|
|
1357
|
-
const symbolMap = new Map();
|
|
1358
|
-
const constSymbolNames = new Set();
|
|
1359
|
-
for (let idx = 0; idx < allBlocks.length; idx++) {
|
|
1360
|
-
const b = allBlocks[idx];
|
|
1361
|
-
if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
|
|
1362
|
-
const names = (b.kind === 'const' && b.name.includes(','))
|
|
1363
|
-
? b.name.split(',').map((s) => s.trim()).filter(Boolean)
|
|
1364
|
-
: [b.name];
|
|
1365
|
-
for (const sn of names) {
|
|
1366
|
-
if (!symbolMap.has(sn)) symbolMap.set(sn, []);
|
|
1367
|
-
symbolMap.get(sn).push(idx);
|
|
1368
|
-
if (b.kind === 'const') constSymbolNames.add(sn);
|
|
1369
|
-
}
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
const callAdj = Array.from({ length: allBlocks.length }, () => new Set());
|
|
1374
|
-
const definedNames = Array.from(symbolMap.keys());
|
|
1375
|
-
for (let i = 0; i < allBlocks.length; i++) {
|
|
1376
|
-
const caller = allBlocks[i];
|
|
1377
|
-
const maskedCaller = maskCommentsAndStrings(caller.full);
|
|
1378
|
-
for (const sym of definedNames) {
|
|
1379
|
-
if (sym === caller.name) continue;
|
|
1380
|
-
if (maskedCaller.includes(sym)) {
|
|
1381
|
-
const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1382
|
-
const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
|
|
1383
|
-
const callRe = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
|
|
1384
|
-
if (callRe.test(maskedCaller)) {
|
|
1385
|
-
for (const t of (symbolMap.get(sym) || [])) {
|
|
1386
|
-
callAdj[i].add(t);
|
|
1387
|
-
callAdj[t].add(i);
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1394
|
-
// 計算自頂部修改重點 (Focal) 出發的 1 層 (1-hop) 與 2 層 (2-hop) 關聯距離
|
|
1395
|
-
const focalIndices = [];
|
|
1396
|
-
const focalFiles = new Set();
|
|
1397
|
-
const hopDistances = new Map();
|
|
1398
|
-
for (let i = 0; i < allBlocks.length; i++) {
|
|
1399
|
-
if (allBlocks[i].score > 0 && focalIndices.length < 3) {
|
|
1400
|
-
focalIndices.push(i);
|
|
1401
|
-
hopDistances.set(i, 0);
|
|
1402
|
-
focalFiles.add(allBlocks[i].rel);
|
|
1403
|
-
}
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
|
-
const bfsQ = [...focalIndices];
|
|
1407
|
-
let qHead = 0;
|
|
1408
|
-
while (qHead < bfsQ.length) {
|
|
1409
|
-
const curr = bfsQ[qHead++];
|
|
1410
|
-
const curHop = hopDistances.get(curr) ?? 0;
|
|
1411
|
-
if (curHop >= 2) continue;
|
|
1412
|
-
for (const nbr of callAdj[curr]) {
|
|
1413
|
-
if (!hopDistances.has(nbr)) {
|
|
1414
|
-
hopDistances.set(nbr, curHop + 1);
|
|
1415
|
-
bfsQ.push(nbr);
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
let used = 0;
|
|
1421
|
-
const fullChunks = [];
|
|
1422
|
-
const skelCandidates = [];
|
|
1423
|
-
const focalNames = new Set();
|
|
1424
|
-
const includedIds = new Set();
|
|
1425
|
-
const includedFiles = new Set();
|
|
1426
|
-
const partialFiles = new Set();
|
|
1427
|
-
const fullStart1EndLine = new Map();
|
|
1428
|
-
const coveredRangesByFile = new Map();
|
|
1429
|
-
const addCoveredRange = (rel, s, e) => {
|
|
1430
|
-
if (!coveredRangesByFile.has(rel)) coveredRangesByFile.set(rel, []);
|
|
1431
|
-
coveredRangesByFile.get(rel).push([s, e]);
|
|
1432
|
-
};
|
|
1433
|
-
const candidateItems = [];
|
|
1434
|
-
const dirBudgetUsed = {};
|
|
1435
|
-
const maxDirBudget = budget * 0.65;
|
|
1436
|
-
|
|
1437
|
-
for (let i = 0; i < allBlocks.length; i++) {
|
|
1438
|
-
const b = allBlocks[i];
|
|
1439
|
-
const topDir = b.rel.split(path.sep)[0] || 'root';
|
|
1440
|
-
const curDir = dirBudgetUsed[topDir] || 0;
|
|
1441
|
-
const hop = hopDistances.get(i);
|
|
1442
|
-
const isFocal = (hop === 0 || (i < 3 && b.score > 0));
|
|
1443
|
-
|
|
1444
|
-
if (isFocal && used + b.rawTk <= budget && curDir + b.rawTk <= maxDirBudget) {
|
|
1445
|
-
used += b.rawTk;
|
|
1446
|
-
dirBudgetUsed[topDir] = curDir + b.rawTk;
|
|
1447
|
-
focalNames.add(b.name);
|
|
1448
|
-
includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
|
|
1449
|
-
includedFiles.add(b.rel);
|
|
1450
|
-
addCoveredRange(b.rel, b.startLine, b.endLine);
|
|
1451
|
-
if (b.startLine === 1) {
|
|
1452
|
-
fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
|
|
1453
|
-
}
|
|
1454
|
-
fullChunks.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [${b.parserMode}]\n${b.full}`);
|
|
1455
|
-
} else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
|
|
1456
|
-
const sameFileConst = b.kind === 'const' && (b.exported || /^[A-Z][A-Z0-9_]+$/.test(b.name)) && b.lineCount <= 25 && focalFiles.has(b.rel);
|
|
1457
|
-
const linked = (hop !== undefined && hop <= 2) || b.score > 0 || sameFileConst;
|
|
1458
|
-
if (linked || i < 12) {
|
|
1459
|
-
used += b.skelTk;
|
|
1460
|
-
dirBudgetUsed[topDir] = curDir + b.skelTk;
|
|
1461
|
-
skelCandidates.push({ ...b, linked, hop: hop ?? null });
|
|
1462
|
-
includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
|
|
1463
|
-
includedFiles.add(b.rel);
|
|
1464
|
-
partialFiles.add(b.rel);
|
|
1465
|
-
if (b.skeleton === b.full) {
|
|
1466
|
-
addCoveredRange(b.rel, b.startLine, b.endLine);
|
|
1467
|
-
}
|
|
1468
|
-
} else {
|
|
1469
|
-
partialFiles.add(b.rel);
|
|
1470
|
-
candidateItems.push(b);
|
|
1471
|
-
}
|
|
1472
|
-
} else {
|
|
1473
|
-
partialFiles.add(b.rel);
|
|
1474
|
-
candidateItems.push(b);
|
|
1475
|
-
}
|
|
1476
|
-
}
|
|
1477
|
-
|
|
1478
|
-
const autoExpandedNames = [];
|
|
1479
|
-
const finalSkelChunks = [];
|
|
1480
|
-
for (const item of skelCandidates) {
|
|
1481
|
-
const delta = Math.max(0, item.rawTk - item.skelTk);
|
|
1482
|
-
const isComplexCluster = (item.linked || item.score > 0) && (item.lineCount >= 16 || delta >= 45);
|
|
1483
|
-
const topDir = item.rel.split(path.sep)[0] || 'root';
|
|
1484
|
-
const curDir = dirBudgetUsed[topDir] || 0;
|
|
1485
|
-
|
|
1486
|
-
if (autoExpand && isComplexCluster && autoExpandedNames.length < 4 && used + delta <= budget && curDir + delta <= maxDirBudget) {
|
|
1487
|
-
used += delta;
|
|
1488
|
-
dirBudgetUsed[topDir] = curDir + delta;
|
|
1489
|
-
autoExpandedNames.push(item.name);
|
|
1490
|
-
addCoveredRange(item.rel, item.startLine, item.endLine);
|
|
1491
|
-
if (item.startLine === 1) {
|
|
1492
|
-
fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, item.endLine));
|
|
1493
|
-
}
|
|
1494
|
-
fullChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] [MCP auto-expanded: ${item.lineCount} lines]\n${item.full}`);
|
|
1495
|
-
} else {
|
|
1496
|
-
const hopNote = item.hop ? ` | ${item.hop}-hop` : '';
|
|
1497
|
-
finalSkelChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] (skeleton${hopNote})\n${item.skeleton}`);
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
|
|
1501
|
-
const headerChunks = [];
|
|
1502
|
-
const headerEndByFile = new Map();
|
|
1503
|
-
for (const rel of includedFiles) {
|
|
1504
|
-
const hdr = headerMap.get(rel);
|
|
1505
|
-
if (!hdr) continue;
|
|
1506
|
-
if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
|
|
1507
|
-
headerEndByFile.set(rel, hdr.endLine);
|
|
1508
|
-
headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
|
|
1509
|
-
}
|
|
1510
|
-
const headerTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
|
|
1511
|
-
|
|
1512
|
-
const footerChunks = [];
|
|
1513
|
-
for (const rel of includedFiles) {
|
|
1514
|
-
const ftr = footerMap.get(rel);
|
|
1515
|
-
if (!ftr) continue;
|
|
1516
|
-
const ranges = coveredRangesByFile.get(rel) || [];
|
|
1517
|
-
const totalLines = lineCountMap.get(rel) || 0;
|
|
1518
|
-
const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
|
|
1519
|
-
if (!partialFiles.has(rel) && wholeFileCovered) continue;
|
|
1520
|
-
const hdrEnd = headerEndByFile.get(rel) || 0;
|
|
1521
|
-
const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
|
|
1522
|
-
if (uncovered.length > 0) {
|
|
1523
|
-
footerChunks.push(`// [${rel}:${uncovered[0].startLine}-${uncovered[uncovered.length - 1].endLine}] (file footer)\n${uncovered.map((c) => c.text).join('\n')}`);
|
|
1524
|
-
}
|
|
2363
|
+
const rawQuery = String(query ?? '');
|
|
2364
|
+
const subPathTag = subPath ? ` subPath="${escapeXmlAttr(subPath)}"` : '';
|
|
2365
|
+
|
|
2366
|
+
// State A: Empty query -> return repository file tree overview (~1K-2K tokens)
|
|
2367
|
+
if (!rawQuery.trim()) {
|
|
2368
|
+
const fileEntries = collectFileOverview(root, scanRoot);
|
|
2369
|
+
return assembleContextSliceXml({
|
|
2370
|
+
blocks: [],
|
|
2371
|
+
fileEntries,
|
|
2372
|
+
fileLineCounts: new Map(),
|
|
2373
|
+
fileHeaders: new Map(),
|
|
2374
|
+
fileFooters: new Map(),
|
|
2375
|
+
rawQuery,
|
|
2376
|
+
terms: [],
|
|
2377
|
+
budget,
|
|
2378
|
+
maxHops: 2,
|
|
2379
|
+
autoExpand,
|
|
2380
|
+
rootAttr: root,
|
|
2381
|
+
version: '0.4.1',
|
|
2382
|
+
subPathTag,
|
|
2383
|
+
includeParserAttr: true,
|
|
2384
|
+
controlWords: CONTROL_WORDS,
|
|
2385
|
+
maskFn: maskCommentsAndStrings
|
|
2386
|
+
});
|
|
1525
2387
|
}
|
|
1526
|
-
const footerTag = footerChunks.length > 0 ? `\n<file_footers>\n${footerChunks.join('\n\n')}\n</file_footers>` : '';
|
|
1527
2388
|
|
|
1528
|
-
const
|
|
1529
|
-
const
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
2389
|
+
const terms = expandQueryTerms(rawQuery);
|
|
2390
|
+
const { blocks, headerMap, footerMap, lineCountMap, fileEntries } = await collectProjectBlocks(root, scanRoot);
|
|
2391
|
+
return assembleContextSliceXml({
|
|
2392
|
+
blocks,
|
|
2393
|
+
fileEntries,
|
|
2394
|
+
fileLineCounts: lineCountMap,
|
|
2395
|
+
fileHeaders: headerMap,
|
|
2396
|
+
fileFooters: footerMap,
|
|
2397
|
+
rawQuery,
|
|
2398
|
+
terms,
|
|
2399
|
+
budget,
|
|
2400
|
+
maxHops: 2,
|
|
2401
|
+
autoExpand,
|
|
2402
|
+
rootAttr: root,
|
|
2403
|
+
version: '0.4.1',
|
|
2404
|
+
subPathTag,
|
|
2405
|
+
includeParserAttr: true,
|
|
2406
|
+
controlWords: CONTROL_WORDS,
|
|
2407
|
+
maskFn: maskCommentsAndStrings
|
|
2408
|
+
});
|
|
1536
2409
|
} catch (err) {
|
|
1537
2410
|
return `Error: ${err.message}`;
|
|
1538
2411
|
}
|
|
@@ -1551,7 +2424,7 @@ rl.on('line', async (line) => {
|
|
|
1551
2424
|
return send({
|
|
1552
2425
|
protocolVersion: req.params?.protocolVersion || '2024-11-05',
|
|
1553
2426
|
capabilities: { tools: {} },
|
|
1554
|
-
serverInfo: { name: 'ctxslice-thin', version: '0.
|
|
2427
|
+
serverInfo: { name: 'ctxslice-thin', version: '0.4.1' }
|
|
1555
2428
|
});
|
|
1556
2429
|
}
|
|
1557
2430
|
if (req.method === 'ping') return send({});
|