@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.mjs
CHANGED
|
@@ -1,11 +1,958 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* ctxslice.mjs — Zero-Config Multi-Language Local
|
|
4
|
-
* Features: Multi-Language
|
|
3
|
+
* ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.1)
|
|
4
|
+
* Features: Multi-Language Structural Extractors, State-Machine Brace Matcher, True Call Graph (BFS), TF-IDF, Dual-State File Tree
|
|
5
5
|
*/
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
|
|
9
|
+
|
|
10
|
+
const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
|
|
11
|
+
const EN_CONVERSATIONAL_STOPWORDS = new Set([
|
|
12
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
|
|
13
|
+
'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
|
|
14
|
+
'how', 'why', 'what', 'when', 'where', 'who', 'which', 'whom', 'whose',
|
|
15
|
+
'can', 'could', 'would', 'should', 'will', 'shall', 'may', 'might', 'must',
|
|
16
|
+
'do', 'does', 'did', 'done', 'doing', 'have', 'has', 'had', 'having',
|
|
17
|
+
'please', 'pls', 'help', 'me', 'my', 'we', 'our', 'you', 'your', 'they', 'their',
|
|
18
|
+
'it', 'its', 'this', 'that', 'these', 'those', 'there', 'here',
|
|
19
|
+
'and', 'or', 'but', 'so', 'than', 'too', 'very', 'just', 'only', 'also',
|
|
20
|
+
'fix', 'modify', 'want', 'need', 'tell'
|
|
21
|
+
]);
|
|
22
|
+
const ZH_CONVERSATIONAL_STOPWORDS_RE = /為什麼|为什么|怎麼樣|怎么样|怎麼|怎么|如何|請幫我|请帮我|幫我|帮我|請問|请问|修改|更改|調整|调整|一下|什麼|什么|這個|这个|那個|那个|哪裡|哪里|[的了嗎呢啊吧著着過把被給跟與及]/g;
|
|
23
|
+
|
|
24
|
+
function estimateTokens(str) {
|
|
25
|
+
if (!str) return 0;
|
|
26
|
+
let cjk = 0;
|
|
27
|
+
for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
|
|
28
|
+
return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function escapeXmlAttr(value) {
|
|
32
|
+
return String(value || '')
|
|
33
|
+
.replace(/&/g, '&')
|
|
34
|
+
.replace(/"/g, '"')
|
|
35
|
+
.replace(/</g, '<')
|
|
36
|
+
.replace(/>/g, '>');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function escapeXmlText(value) {
|
|
40
|
+
return String(value || '')
|
|
41
|
+
.replace(/&/g, '&')
|
|
42
|
+
.replace(/</g, '<')
|
|
43
|
+
.replace(/>/g, '>');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function mergeLineRanges(ranges) {
|
|
47
|
+
if (!ranges || ranges.length === 0) return [];
|
|
48
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
49
|
+
const merged = [];
|
|
50
|
+
for (const r of sorted) {
|
|
51
|
+
const s = Math.max(1, r[0]);
|
|
52
|
+
const e = Math.max(s, r[1]);
|
|
53
|
+
if (merged.length === 0) {
|
|
54
|
+
merged.push([s, e]);
|
|
55
|
+
} else {
|
|
56
|
+
const prev = merged[merged.length - 1];
|
|
57
|
+
if (s <= prev[1] + 1) prev[1] = Math.max(prev[1], e);
|
|
58
|
+
else merged.push([s, e]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return merged;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function formatShownLines(ranges) {
|
|
65
|
+
const merged = mergeLineRanges(ranges);
|
|
66
|
+
if (merged.length === 0) return 'none';
|
|
67
|
+
return merged.map((r) => (r[0] === r[1] ? String(r[0]) : r[0] + '-' + r[1])).join(', ');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function slicePlainTextConfigWindow(content, queryTerms) {
|
|
71
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
72
|
+
if (lines.length <= 200) return null;
|
|
73
|
+
|
|
74
|
+
const matchedLines = [];
|
|
75
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
76
|
+
for (let i = 0; i < lines.length; i++) {
|
|
77
|
+
const lower = lines[i].toLowerCase();
|
|
78
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
79
|
+
matchedLines.push(i + 1);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const rawRanges = matchedLines.length > 0
|
|
85
|
+
? matchedLines.map((ln) => [Math.max(1, ln - 40), Math.min(lines.length, ln + 40)])
|
|
86
|
+
: [[1, Math.min(lines.length, 81)]];
|
|
87
|
+
|
|
88
|
+
const merged = mergeLineRanges(rawRanges);
|
|
89
|
+
const parts = [];
|
|
90
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
91
|
+
const s = merged[idx][0];
|
|
92
|
+
const e = merged[idx][1];
|
|
93
|
+
if (idx > 0) {
|
|
94
|
+
const prevEnd = merged[idx - 1][1];
|
|
95
|
+
parts.push('// ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ...');
|
|
96
|
+
}
|
|
97
|
+
parts.push(lines.slice(s - 1, e).join('\n'));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const windowedCode = parts.join('\n');
|
|
101
|
+
return {
|
|
102
|
+
windowedCode,
|
|
103
|
+
ranges: merged,
|
|
104
|
+
tokens: estimateTokens(windowedCode)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
|
|
109
|
+
const sorted = [...fileEntries].sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
110
|
+
const out = [];
|
|
111
|
+
let usedTokens = 0;
|
|
112
|
+
let omittedCount = 0;
|
|
113
|
+
for (const f of sorted) {
|
|
114
|
+
const line = ' ' + f.relPath + ' (' + f.lineCount + ' lines)';
|
|
115
|
+
const tk = estimateTokens(line);
|
|
116
|
+
if (usedTokens + tk > maxTokens && out.length > 0) {
|
|
117
|
+
omittedCount++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
usedTokens += tk;
|
|
121
|
+
out.push(line);
|
|
122
|
+
}
|
|
123
|
+
if (omittedCount > 0) {
|
|
124
|
+
out.push(' ... (' + omittedCount + ' more files omitted to keep overview within ~1.8K tokens)');
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
const DOC_EXT_RE = /\.(md|mdx|rst|adoc|asciidoc)$/i;
|
|
129
|
+
const DOC_PATH_RE = /(^|\/)(docs?|documentation|wiki|guides?)\/|(^|\/)(README|CHANGELOG|HISTORY|CONTRIBUTING|CHANGES|RELEASES|MIGRATION|UPGRADING|AUTHORS|NOTICE|LICENSE)([^/]*)$/i;
|
|
130
|
+
const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|specs|testing|fixtures?|benchmarks?|examples?|samples?)\/|(\.|_)(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.[^/]+$/i;
|
|
131
|
+
const SYNTAX_NOISE_WORDS = new Set([
|
|
132
|
+
'class', 'def', 'function', 'func', 'fn', 'struct', 'interface', 'type', 'enum',
|
|
133
|
+
'const', 'let', 'var', 'async', 'await', 'import', 'export', 'return',
|
|
134
|
+
'public', 'private', 'protected', 'static'
|
|
135
|
+
]);
|
|
136
|
+
|
|
137
|
+
function classifyFileRole(filePath) {
|
|
138
|
+
const norm = String(filePath || '').replace(/\\/g, '/');
|
|
139
|
+
if (DOC_EXT_RE.test(norm) || DOC_PATH_RE.test(norm)) return 'doc';
|
|
140
|
+
if (TEST_PATH_RE.test(norm)) return 'test';
|
|
141
|
+
return 'source';
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function getQueryRoleIntents(query) {
|
|
145
|
+
const q = String(query || '').toLowerCase();
|
|
146
|
+
return {
|
|
147
|
+
wantsDocs: /\b(readme|changelog|docs|documentation|markdown|guide)\b|\.md\b|文件|說明/.test(q),
|
|
148
|
+
wantsTests: /\b(tests?|specs?|pytest|unittest|jest|vitest)\b|測試/.test(q)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
|
|
153
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
154
|
+
if (lines.length <= 45) {
|
|
155
|
+
return {
|
|
156
|
+
windowedCode: content,
|
|
157
|
+
ranges: [[1, Math.max(1, lines.length)]],
|
|
158
|
+
tokens: estimateTokens(content)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const matchedLines = [];
|
|
162
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
163
|
+
for (let i = 0; i < lines.length; i++) {
|
|
164
|
+
const lower = lines[i].toLowerCase();
|
|
165
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
166
|
+
matchedLines.push(i + 1);
|
|
167
|
+
if (matchedLines.length >= 3) break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const rawRanges = matchedLines.length > 0
|
|
172
|
+
? matchedLines.slice(0, 2).map((ln) => [Math.max(1, ln - radius), Math.min(lines.length, ln + radius)])
|
|
173
|
+
: [[1, Math.min(lines.length, 24)]];
|
|
174
|
+
const merged = mergeLineRanges(rawRanges);
|
|
175
|
+
const parts = [];
|
|
176
|
+
const usedRanges = [];
|
|
177
|
+
let accTokens = 0;
|
|
178
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
179
|
+
const s = merged[idx][0];
|
|
180
|
+
const e = merged[idx][1];
|
|
181
|
+
const sliceLines = [];
|
|
182
|
+
let endWritten = s - 1;
|
|
183
|
+
for (let ln = s; ln <= e; ln++) {
|
|
184
|
+
const candidate = lines[ln - 1];
|
|
185
|
+
const tk = estimateTokens(candidate);
|
|
186
|
+
if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
|
|
187
|
+
sliceLines.push(candidate);
|
|
188
|
+
accTokens += tk;
|
|
189
|
+
endWritten = ln;
|
|
190
|
+
}
|
|
191
|
+
if (sliceLines.length === 0) break;
|
|
192
|
+
if (idx > 0 && usedRanges.length > 0) {
|
|
193
|
+
const prevEnd = usedRanges[usedRanges.length - 1][1];
|
|
194
|
+
if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
|
|
195
|
+
}
|
|
196
|
+
parts.push(sliceLines.join('\n'));
|
|
197
|
+
usedRanges.push([s, endWritten]);
|
|
198
|
+
if (accTokens >= maxTokens) break;
|
|
199
|
+
}
|
|
200
|
+
if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < lines.length) {
|
|
201
|
+
parts.push('<!-- ... ' + (lines.length - usedRanges[usedRanges.length - 1][1]) + ' remaining doc lines omitted ... -->');
|
|
202
|
+
}
|
|
203
|
+
const windowedCode = parts.join('\n');
|
|
204
|
+
return {
|
|
205
|
+
windowedCode,
|
|
206
|
+
ranges: usedRanges.length > 0 ? usedRanges : [[1, Math.min(lines.length, 20)]],
|
|
207
|
+
tokens: estimateTokens(windowedCode)
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function findPythonSignatureEndIdx(lines, startIdx) {
|
|
212
|
+
let paren = 0, bracket = 0, brace = 0;
|
|
213
|
+
const maxScan = Math.min(lines.length - 1, startIdx + 25);
|
|
214
|
+
for (let j = startIdx; j <= maxScan; j++) {
|
|
215
|
+
const raw = lines[j];
|
|
216
|
+
let k = 0;
|
|
217
|
+
while (k < raw.length) {
|
|
218
|
+
const ch = raw[k];
|
|
219
|
+
if (ch === '#') break;
|
|
220
|
+
if (ch === '"' || ch === "'") {
|
|
221
|
+
const quote = ch;
|
|
222
|
+
k++;
|
|
223
|
+
while (k < raw.length) {
|
|
224
|
+
if (raw[k] === '\\') { k += 2; continue; }
|
|
225
|
+
if (raw[k] === quote) { k++; break; }
|
|
226
|
+
k++;
|
|
227
|
+
}
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (ch === '(') paren++;
|
|
231
|
+
else if (ch === ')') paren = Math.max(0, paren - 1);
|
|
232
|
+
else if (ch === '[') bracket++;
|
|
233
|
+
else if (ch === ']') bracket = Math.max(0, bracket - 1);
|
|
234
|
+
else if (ch === '{') brace++;
|
|
235
|
+
else if (ch === '}') brace = Math.max(0, brace - 1);
|
|
236
|
+
k++;
|
|
237
|
+
}
|
|
238
|
+
const noComment = raw.replace(/#.*$/, '').trimEnd();
|
|
239
|
+
if (paren <= 0 && bracket <= 0 && brace <= 0 && noComment.endsWith(':')) return j;
|
|
240
|
+
}
|
|
241
|
+
return startIdx;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function findPythonBlockEndIdx(lines, sigEndIdx, baseIndent) {
|
|
245
|
+
let end = sigEndIdx;
|
|
246
|
+
let inTriple = null;
|
|
247
|
+
for (let j = sigEndIdx + 1; j < lines.length; j++) {
|
|
248
|
+
const raw = lines[j];
|
|
249
|
+
const trimmed = raw.trim();
|
|
250
|
+
if (inTriple) {
|
|
251
|
+
end = j;
|
|
252
|
+
if ((raw.split(inTriple).length - 1) % 2 === 1) inTriple = null;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (trimmed === '') { end = j; continue; }
|
|
256
|
+
const indent = (raw.match(/^\s*/) || [''])[0].length;
|
|
257
|
+
if (indent <= baseIndent) break;
|
|
258
|
+
end = j;
|
|
259
|
+
const tm = trimmed.match(/^("""|''')/);
|
|
260
|
+
if (tm && (trimmed.split(tm[1]).length - 1) % 2 === 1) inTriple = tm[1];
|
|
261
|
+
}
|
|
262
|
+
while (end > sigEndIdx && lines[end].trim() === '') end--;
|
|
263
|
+
return end;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function buildPythonClassSkeleton(fullClassCode, classStartLine = 1, expandedMethodRanges = []) {
|
|
267
|
+
const lines = String(fullClassCode || '').split('\n');
|
|
268
|
+
if (lines.length <= 4) return fullClassCode;
|
|
269
|
+
let classDefRel = 0;
|
|
270
|
+
while (classDefRel < lines.length && lines[classDefRel].trimStart().startsWith('@')) classDefRel++;
|
|
271
|
+
if (classDefRel >= lines.length) return fullClassCode;
|
|
272
|
+
|
|
273
|
+
const classIndent = (lines[classDefRel].match(/^\s*/) || [''])[0].length;
|
|
274
|
+
const classSigEndRel = findPythonSignatureEndIdx(lines, classDefRel);
|
|
275
|
+
const out = [];
|
|
276
|
+
for (let i = 0; i <= classSigEndRel; i++) out.push(lines[i]);
|
|
277
|
+
|
|
278
|
+
let bodyIdx = classSigEndRel + 1;
|
|
279
|
+
while (bodyIdx < lines.length && lines[bodyIdx].trim() === '') bodyIdx++;
|
|
280
|
+
if (bodyIdx < lines.length) {
|
|
281
|
+
const t = lines[bodyIdx].trim();
|
|
282
|
+
if (t.startsWith('"""') || t.startsWith("'''")) {
|
|
283
|
+
const q = t.slice(0, 3);
|
|
284
|
+
if (t.length > 3 && t.slice(3).includes(q)) {
|
|
285
|
+
out.push(lines[bodyIdx]);
|
|
286
|
+
bodyIdx++;
|
|
287
|
+
} else {
|
|
288
|
+
let docEnd = bodyIdx;
|
|
289
|
+
for (let j = bodyIdx + 1; j < lines.length; j++) {
|
|
290
|
+
if (lines[j].includes(q)) { docEnd = j; break; }
|
|
291
|
+
}
|
|
292
|
+
if (docEnd - bodyIdx <= 4) {
|
|
293
|
+
for (let j = bodyIdx; j <= docEnd; j++) out.push(lines[j]);
|
|
294
|
+
} else {
|
|
295
|
+
out.push(lines[bodyIdx]);
|
|
296
|
+
out.push(lines[bodyIdx + 1]);
|
|
297
|
+
const indentStr = (lines[bodyIdx].match(/^\s*/) || [' '])[0];
|
|
298
|
+
out.push(indentStr + '... (' + (docEnd - bodyIdx - 1) + ' docstring lines folded)');
|
|
299
|
+
out.push(lines[docEnd]);
|
|
300
|
+
}
|
|
301
|
+
bodyIdx = docEnd + 1;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
let methodIndent = null;
|
|
307
|
+
let memberCount = 0;
|
|
308
|
+
for (let i = bodyIdx; i < lines.length; i++) {
|
|
309
|
+
const raw = lines[i];
|
|
310
|
+
const trimmed = raw.trim();
|
|
311
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
312
|
+
const indent = (raw.match(/^\s*/) || [''])[0].length;
|
|
313
|
+
if (indent <= classIndent) continue;
|
|
314
|
+
|
|
315
|
+
if (trimmed.startsWith('@') && (methodIndent === null || indent === methodIndent)) {
|
|
316
|
+
let k = i + 1;
|
|
317
|
+
while (k < lines.length && lines[k].trimStart().startsWith('@')) k++;
|
|
318
|
+
if (k < lines.length && /^(?:async\s+)?def\s+/.test(lines[k].trim())) {
|
|
319
|
+
if (methodIndent === null) methodIndent = indent;
|
|
320
|
+
for (let d = i; d < k; d++) out.push(lines[d]);
|
|
321
|
+
i = k - 1;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const dm = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
327
|
+
if (dm && (methodIndent === null || indent === methodIndent)) {
|
|
328
|
+
methodIndent = indent;
|
|
329
|
+
memberCount++;
|
|
330
|
+
const mSigEnd = findPythonSignatureEndIdx(lines, i);
|
|
331
|
+
const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
|
|
332
|
+
const absStart = classStartLine + i;
|
|
333
|
+
const absEnd = classStartLine + mEnd;
|
|
334
|
+
const hit = expandedMethodRanges.find((r) => r.startLine <= absEnd && r.endLine >= absStart);
|
|
335
|
+
for (let s = i; s <= mSigEnd; s++) {
|
|
336
|
+
if (s === mSigEnd) {
|
|
337
|
+
const folded = Math.max(1, mEnd - mSigEnd);
|
|
338
|
+
const note = hit
|
|
339
|
+
? ' # [expanded in <focal symbol="' + hit.name + '"> below]'
|
|
340
|
+
: ' # ... ' + folded + ' lines folded';
|
|
341
|
+
out.push(lines[s] + note);
|
|
342
|
+
} else {
|
|
343
|
+
out.push(lines[s]);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
i = mEnd;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (methodIndent === null || indent <= methodIndent) {
|
|
351
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*\s*(?::[^=]+)?(?:=.*)?$/.test(trimmed)) {
|
|
352
|
+
out.push(raw);
|
|
353
|
+
memberCount++;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (memberCount === 0) {
|
|
359
|
+
return lines.length > 4
|
|
360
|
+
? lines.slice(0, classSigEndRel + 1).join('\n') + '\n # ... ' + (lines.length - classSigEndRel - 1) + ' lines folded'
|
|
361
|
+
: fullClassCode;
|
|
362
|
+
}
|
|
363
|
+
return out.join('\n');
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function extractPythonBlocks(lines, lineIdx) {
|
|
367
|
+
const line = lines[lineIdx];
|
|
368
|
+
const m = line.match(/^(async\s+def|def|class)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
|
|
369
|
+
if (!m) return null;
|
|
370
|
+
|
|
371
|
+
const kind = m[1] === 'class' ? 'class' : 'function';
|
|
372
|
+
const name = m[2];
|
|
373
|
+
let startIdx = lineIdx;
|
|
374
|
+
while (startIdx > 0 && /^@[A-Za-z_]/.test(lines[startIdx - 1])) startIdx--;
|
|
375
|
+
const startLine = startIdx + 1;
|
|
376
|
+
const sigEndIdx = findPythonSignatureEndIdx(lines, lineIdx);
|
|
377
|
+
const endIdx = findPythonBlockEndIdx(lines, sigEndIdx, 0);
|
|
378
|
+
const endLine = endIdx + 1;
|
|
379
|
+
const full = lines.slice(startIdx, endIdx + 1).join('\n');
|
|
380
|
+
const results = [];
|
|
381
|
+
|
|
382
|
+
if (kind === 'class') {
|
|
383
|
+
results.push({
|
|
384
|
+
name,
|
|
385
|
+
kind: 'class',
|
|
386
|
+
exported: !name.startsWith('_'),
|
|
387
|
+
startLine,
|
|
388
|
+
endLine,
|
|
389
|
+
full,
|
|
390
|
+
skeleton: buildPythonClassSkeleton(full, startLine)
|
|
391
|
+
});
|
|
392
|
+
let methodIndent = null;
|
|
393
|
+
for (let mIdx = sigEndIdx + 1; mIdx <= endIdx; mIdx++) {
|
|
394
|
+
const mLine = lines[mIdx];
|
|
395
|
+
const mTrimmed = mLine.trim();
|
|
396
|
+
if (!mTrimmed || mTrimmed.startsWith('#')) continue;
|
|
397
|
+
const indent = (mLine.match(/^\s*/) || [''])[0].length;
|
|
398
|
+
if (indent <= 0) continue;
|
|
399
|
+
const dm = mTrimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
400
|
+
if (!dm) continue;
|
|
401
|
+
if (methodIndent === null) methodIndent = indent;
|
|
402
|
+
if (indent !== methodIndent) continue;
|
|
403
|
+
const methodName = dm[1];
|
|
404
|
+
let mStartIdx = mIdx;
|
|
405
|
+
while (
|
|
406
|
+
mStartIdx > sigEndIdx + 1 &&
|
|
407
|
+
lines[mStartIdx - 1].trimStart().startsWith('@') &&
|
|
408
|
+
(lines[mStartIdx - 1].match(/^\s*/) || [''])[0].length === indent
|
|
409
|
+
) {
|
|
410
|
+
mStartIdx--;
|
|
411
|
+
}
|
|
412
|
+
const mSigEnd = findPythonSignatureEndIdx(lines, mIdx);
|
|
413
|
+
const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
|
|
414
|
+
const mFull = lines.slice(mStartIdx, mEnd + 1).join('\n');
|
|
415
|
+
const mFolded = Math.max(1, mEnd - mSigEnd);
|
|
416
|
+
const indentStr = (mLine.match(/^\s*/) || [' '])[0];
|
|
417
|
+
const mSigLines = lines.slice(mStartIdx, mSigEnd + 1).join('\n');
|
|
418
|
+
const mSkel = mEnd - mSigEnd > 2 ? mSigLines + '\n' + indentStr + ' # ... ' + mFolded + ' lines folded' : mFull;
|
|
419
|
+
results.push({
|
|
420
|
+
name: name + '.' + methodName,
|
|
421
|
+
kind: 'method',
|
|
422
|
+
exported: !name.startsWith('_') && !methodName.startsWith('_'),
|
|
423
|
+
startLine: mStartIdx + 1,
|
|
424
|
+
endLine: mEnd + 1,
|
|
425
|
+
full: mFull,
|
|
426
|
+
skeleton: mSkel
|
|
427
|
+
});
|
|
428
|
+
mIdx = mEnd;
|
|
429
|
+
}
|
|
430
|
+
} else {
|
|
431
|
+
const sigLines = lines.slice(startIdx, sigEndIdx + 1).join('\n');
|
|
432
|
+
const skeleton = endIdx - sigEndIdx > 2 ? sigLines + '\n # ... ' + (endIdx - sigEndIdx) + ' lines folded' : full;
|
|
433
|
+
results.push({
|
|
434
|
+
name,
|
|
435
|
+
kind: 'function',
|
|
436
|
+
exported: !name.startsWith('_'),
|
|
437
|
+
startLine,
|
|
438
|
+
endLine,
|
|
439
|
+
full,
|
|
440
|
+
skeleton
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
return { blocks: results, endIdx };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function assembleContextSliceXml(opts) {
|
|
447
|
+
const {
|
|
448
|
+
blocks,
|
|
449
|
+
fileEntries,
|
|
450
|
+
fileLineCounts,
|
|
451
|
+
fileHeaders,
|
|
452
|
+
fileFooters,
|
|
453
|
+
rawQuery,
|
|
454
|
+
terms,
|
|
455
|
+
budget,
|
|
456
|
+
maxHops,
|
|
457
|
+
autoExpand,
|
|
458
|
+
rootAttr,
|
|
459
|
+
version,
|
|
460
|
+
subPathTag,
|
|
461
|
+
includeParserAttr,
|
|
462
|
+
controlWords,
|
|
463
|
+
maskFn
|
|
464
|
+
} = opts;
|
|
465
|
+
|
|
466
|
+
if (!String(rawQuery || '').trim()) {
|
|
467
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
468
|
+
return [
|
|
469
|
+
'<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
|
|
470
|
+
' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
|
|
471
|
+
' <repository_file_tree>',
|
|
472
|
+
...treeLines,
|
|
473
|
+
' </repository_file_tree>',
|
|
474
|
+
'</context_slice>'
|
|
475
|
+
].join('\n');
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const roleIntents = getQueryRoleIntents(rawQuery);
|
|
479
|
+
const configWindowByKey = new Map();
|
|
480
|
+
const preparedBlocks = blocks.map((b) => {
|
|
481
|
+
const rel = b.filePath;
|
|
482
|
+
const key = rel + ':' + b.startLine;
|
|
483
|
+
const lineCount = Math.max(1, b.endLine - b.startLine + 1);
|
|
484
|
+
const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
|
|
485
|
+
const isDocExt = DOC_EXT_RE.test(rel);
|
|
486
|
+
let win = null;
|
|
487
|
+
if (b.kind === 'module') {
|
|
488
|
+
if (isConfigFile && lineCount > 200) {
|
|
489
|
+
win = slicePlainTextConfigWindow(b.full, terms);
|
|
490
|
+
} else if (isDocExt && lineCount > 45) {
|
|
491
|
+
win = sliceDocWindow(b.full, terms, 16, 480);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (win) configWindowByKey.set(key, win);
|
|
495
|
+
const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
|
|
496
|
+
const skelTk = isDocExt
|
|
497
|
+
? Math.min(b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton), win ? win.tokens : 480)
|
|
498
|
+
: (b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton));
|
|
499
|
+
return {
|
|
500
|
+
...b,
|
|
501
|
+
filePath: rel,
|
|
502
|
+
lineCount,
|
|
503
|
+
role: classifyFileRole(rel),
|
|
504
|
+
isDocExt,
|
|
505
|
+
rawTk,
|
|
506
|
+
skelTk
|
|
507
|
+
};
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
const totalBlocks = Math.max(1, preparedBlocks.length);
|
|
511
|
+
const termDF = {};
|
|
512
|
+
for (const t of terms) {
|
|
513
|
+
let df = 0;
|
|
514
|
+
for (const b of preparedBlocks) {
|
|
515
|
+
if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
|
|
516
|
+
df++;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
termDF[t] = Math.max(1, df);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const scored = preparedBlocks.map((b) => {
|
|
523
|
+
const nameLower = b.name.toLowerCase();
|
|
524
|
+
const shortLower = nameLower.includes('.') ? nameLower.split('.').pop() : nameLower;
|
|
525
|
+
const relLower = b.filePath.toLowerCase();
|
|
526
|
+
const lowerBody = b.full.toLowerCase();
|
|
527
|
+
let score = 0;
|
|
528
|
+
let matchedTerms = 0;
|
|
529
|
+
|
|
530
|
+
for (const t of terms) {
|
|
531
|
+
const df = termDF[t] || 1;
|
|
532
|
+
const idf = Math.log(1 + (totalBlocks / df));
|
|
533
|
+
const scarcity = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
|
|
534
|
+
let termScore = 0;
|
|
535
|
+
let hit = false;
|
|
536
|
+
if (nameLower === t || shortLower === t) { termScore += 48; hit = true; }
|
|
537
|
+
else if (nameLower.includes(t)) { termScore += 24; hit = true; }
|
|
538
|
+
if (relLower.includes(t)) { termScore += 12; hit = true; }
|
|
539
|
+
const bodyOcc = lowerBody.split(t).length - 1;
|
|
540
|
+
if (bodyOcc > 0) { termScore += Math.min(12, 3 * Math.log1p(bodyOcc)); hit = true; }
|
|
541
|
+
if (hit) matchedTerms++;
|
|
542
|
+
score += termScore * idf * scarcity;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (matchedTerms >= 2) {
|
|
546
|
+
score *= 1 + 0.35 * (matchedTerms - 1);
|
|
547
|
+
}
|
|
548
|
+
if (score > 0 && (b.kind === 'function' || b.kind === 'method')) score *= 1.18;
|
|
549
|
+
else if (score > 0 && (b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' || b.kind === 'struct')) score *= 1.08;
|
|
550
|
+
|
|
551
|
+
if (score > 0) {
|
|
552
|
+
if (b.role === 'doc' && !roleIntents.wantsDocs) score *= 0.10;
|
|
553
|
+
else if (b.role === 'test' && !roleIntents.wantsTests) score *= 0.20;
|
|
554
|
+
else if (b.role === 'source') score *= 1.25;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
return { ...b, score };
|
|
558
|
+
}).sort((a, b) => b.score - a.score);
|
|
559
|
+
|
|
560
|
+
// Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
|
|
561
|
+
const symbolMap = new Map();
|
|
562
|
+
const constSymbolNames = new Set();
|
|
563
|
+
for (let i = 0; i < scored.length; i++) {
|
|
564
|
+
const b = scored[i];
|
|
565
|
+
if (b.name && b.kind !== 'module' && !controlWords.has(b.name)) {
|
|
566
|
+
const rawShort = b.name.includes('.') ? b.name.split('.').pop() : b.name;
|
|
567
|
+
const names = (b.kind === 'const' && rawShort.includes(','))
|
|
568
|
+
? rawShort.split(',').map((s) => s.trim()).filter(Boolean)
|
|
569
|
+
: [rawShort];
|
|
570
|
+
for (const sn of names) {
|
|
571
|
+
if (!sn || /^__.*__$/.test(sn)) continue;
|
|
572
|
+
if (!symbolMap.has(sn)) symbolMap.set(sn, []);
|
|
573
|
+
symbolMap.get(sn).push(i);
|
|
574
|
+
if (b.kind === 'const') constSymbolNames.add(sn);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const callAdj = Array.from({ length: scored.length }, () => new Set());
|
|
580
|
+
const definedNames = Array.from(symbolMap.keys());
|
|
581
|
+
for (let i = 0; i < scored.length; i++) {
|
|
582
|
+
const caller = scored[i];
|
|
583
|
+
const maskedCaller = maskFn(caller.full);
|
|
584
|
+
for (const sym of definedNames) {
|
|
585
|
+
const callerShort = caller.name.includes('.') ? caller.name.split('.').pop() : caller.name;
|
|
586
|
+
if (sym === caller.name || sym === callerShort) continue;
|
|
587
|
+
if (maskedCaller.includes(sym)) {
|
|
588
|
+
const esc = sym.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&');
|
|
589
|
+
const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
|
|
590
|
+
const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
|
|
591
|
+
if (re.test(maskedCaller)) {
|
|
592
|
+
for (const t of (symbolMap.get(sym) || [])) {
|
|
593
|
+
const target = scored[t];
|
|
594
|
+
if (caller.filePath === target.filePath && (
|
|
595
|
+
(caller.kind === 'class' && target.kind === 'method' && target.name.startsWith(caller.name + '.')) ||
|
|
596
|
+
(target.kind === 'class' && caller.kind === 'method' && caller.name.startsWith(target.name + '.'))
|
|
597
|
+
)) continue;
|
|
598
|
+
callAdj[i].add(t);
|
|
599
|
+
callAdj[t].add(i);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// Focal selection: strictly prefer source matches over docs/tests + class/method smart deduplication
|
|
607
|
+
const hasSourceMatches = scored.some((b) => b.role === 'source' && b.score > 0);
|
|
608
|
+
const eligibleIndices = [];
|
|
609
|
+
for (let i = 0; i < scored.length; i++) {
|
|
610
|
+
if (scored[i].score <= 0) continue;
|
|
611
|
+
if (hasSourceMatches && scored[i].role !== 'source') continue;
|
|
612
|
+
eligibleIndices.push(i);
|
|
613
|
+
}
|
|
614
|
+
const focalSet = new Set();
|
|
615
|
+
const promotedParentClassSet = new Set();
|
|
616
|
+
if (eligibleIndices.length > 0) {
|
|
617
|
+
const topScore = scored[eligibleIndices[0]].score;
|
|
618
|
+
const candidateIdx = eligibleIndices
|
|
619
|
+
.filter((idx, rank) => (rank < 3 && scored[idx].score >= topScore * 0.3) || scored[idx].score >= topScore * 0.55)
|
|
620
|
+
.slice(0, 5);
|
|
621
|
+
const candidateChosen = new Set();
|
|
622
|
+
for (const idx of candidateIdx) {
|
|
623
|
+
const b = scored[idx];
|
|
624
|
+
if (b.kind === 'class' && b.lineCount > 35) {
|
|
625
|
+
const childIndices = [];
|
|
626
|
+
for (let ci = 0; ci < scored.length; ci++) {
|
|
627
|
+
const c = scored[ci];
|
|
628
|
+
if (c.filePath === b.filePath && c.kind === 'method' && c.name.startsWith(b.name + '.')) {
|
|
629
|
+
const cShort = c.name.split('.').pop().toLowerCase();
|
|
630
|
+
const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
|
|
631
|
+
if (explicitHit || c.score >= b.score * 0.55) {
|
|
632
|
+
childIndices.push(ci);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (childIndices.length > 0) {
|
|
637
|
+
promotedParentClassSet.add(idx);
|
|
638
|
+
for (const ci of childIndices.slice(0, 3)) candidateChosen.add(ci);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
candidateChosen.add(idx);
|
|
643
|
+
}
|
|
644
|
+
for (const idx of candidateChosen) {
|
|
645
|
+
const b = scored[idx];
|
|
646
|
+
if (b.kind === 'method') {
|
|
647
|
+
const clsName = b.name.split('.')[0];
|
|
648
|
+
const hasFullParent = [...candidateChosen].some((pIdx) => {
|
|
649
|
+
const p = scored[pIdx];
|
|
650
|
+
return p && p.kind === 'class' && p.filePath === b.filePath && p.name === clsName;
|
|
651
|
+
});
|
|
652
|
+
if (hasFullParent) continue;
|
|
653
|
+
}
|
|
654
|
+
focalSet.add(idx);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// BFS from final focalSet
|
|
659
|
+
const hopDistances = new Map();
|
|
660
|
+
const focalFiles = new Set();
|
|
661
|
+
const bfsQ = [...focalSet];
|
|
662
|
+
for (const fi of bfsQ) {
|
|
663
|
+
hopDistances.set(fi, 0);
|
|
664
|
+
focalFiles.add(scored[fi].filePath);
|
|
665
|
+
}
|
|
666
|
+
let qHead = 0;
|
|
667
|
+
while (qHead < bfsQ.length) {
|
|
668
|
+
const curr = bfsQ[qHead++];
|
|
669
|
+
const curHop = hopDistances.get(curr) ?? 0;
|
|
670
|
+
if (curHop >= maxHops) continue;
|
|
671
|
+
for (const nbr of callAdj[curr]) {
|
|
672
|
+
if (!hopDistances.has(nbr)) {
|
|
673
|
+
hopDistances.set(nbr, curHop + 1);
|
|
674
|
+
bfsQ.push(nbr);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, then 1/2-hop source -> test -> doc
|
|
680
|
+
const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
|
|
681
|
+
const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
|
|
682
|
+
const focA = focalSet.has(a) ? 0 : 1;
|
|
683
|
+
const focB = focalSet.has(b) ? 0 : 1;
|
|
684
|
+
if (focA !== focB) return focA - focB;
|
|
685
|
+
const parA = promotedParentClassSet.has(a) ? 0 : 1;
|
|
686
|
+
const parB = promotedParentClassSet.has(b) ? 0 : 1;
|
|
687
|
+
if (parA !== parB) return parA - parB;
|
|
688
|
+
const rrA = roleRank(scored[a].role);
|
|
689
|
+
const rrB = roleRank(scored[b].role);
|
|
690
|
+
if (rrA !== rrB) return rrA - rrB;
|
|
691
|
+
const hopA = hopDistances.get(a) ?? 99;
|
|
692
|
+
const hopB = hopDistances.get(b) ?? 99;
|
|
693
|
+
if (hopA !== hopB) return hopA - hopB;
|
|
694
|
+
return scored[b].score - scored[a].score;
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
let remaining = budget;
|
|
698
|
+
let docBudgetUsed = 0;
|
|
699
|
+
let testBudgetUsed = 0;
|
|
700
|
+
const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
|
|
701
|
+
const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
|
|
702
|
+
const dirBudgetUsed = {};
|
|
703
|
+
const maxDirBudget = budget * 0.72;
|
|
704
|
+
|
|
705
|
+
const includedIds = new Set();
|
|
706
|
+
const includedFiles = [];
|
|
707
|
+
const includedFilesSet = new Set();
|
|
708
|
+
const fullStart1EndLine = new Map();
|
|
709
|
+
const coveredRangesByFile = new Map();
|
|
710
|
+
const partialFiles = new Set();
|
|
711
|
+
const selectedByFile = new Map();
|
|
712
|
+
const fullParentClassesByFile = new Map();
|
|
713
|
+
const skelCandidates = [];
|
|
714
|
+
const candidateItems = [];
|
|
715
|
+
|
|
716
|
+
const addCoveredRange = (fp, s, e) => {
|
|
717
|
+
if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
|
|
718
|
+
coveredRangesByFile.get(fp).push([s, e]);
|
|
719
|
+
};
|
|
720
|
+
const addSelectedBlock = (fp, entry) => {
|
|
721
|
+
if (!includedFilesSet.has(fp)) {
|
|
722
|
+
includedFilesSet.add(fp);
|
|
723
|
+
includedFiles.push(fp);
|
|
724
|
+
}
|
|
725
|
+
if (!selectedByFile.has(fp)) selectedByFile.set(fp, []);
|
|
726
|
+
selectedByFile.get(fp).push(entry);
|
|
727
|
+
};
|
|
728
|
+
const canUseRoleBudget = (role, cost) => {
|
|
729
|
+
if (role === 'doc') return docBudgetUsed + cost <= docBudgetCap;
|
|
730
|
+
if (role === 'test') return testBudgetUsed + cost <= testBudgetCap;
|
|
731
|
+
return true;
|
|
732
|
+
};
|
|
733
|
+
const addRoleBudget = (role, cost) => {
|
|
734
|
+
if (role === 'doc') docBudgetUsed += cost;
|
|
735
|
+
else if (role === 'test') testBudgetUsed += cost;
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
for (const idx of allocOrder) {
|
|
739
|
+
const item = scored[idx];
|
|
740
|
+
if (item.kind === 'method') {
|
|
741
|
+
const clsName = item.name.split('.')[0];
|
|
742
|
+
const fullSet = fullParentClassesByFile.get(item.filePath);
|
|
743
|
+
if (fullSet && fullSet.has(clsName)) continue;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const topDir = item.filePath.split('/')[0] || 'root';
|
|
747
|
+
const curDir = dirBudgetUsed[topDir] || 0;
|
|
748
|
+
const hop = hopDistances.get(idx);
|
|
749
|
+
const isFocal = focalSet.has(idx);
|
|
750
|
+
const isPromotedParent = promotedParentClassSet.has(idx);
|
|
751
|
+
const key = item.filePath + ':' + item.startLine;
|
|
752
|
+
const win = configWindowByKey.get(key);
|
|
753
|
+
|
|
754
|
+
if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
|
|
755
|
+
remaining = Math.max(0, remaining - item.rawTk);
|
|
756
|
+
dirBudgetUsed[topDir] = curDir + item.rawTk;
|
|
757
|
+
addRoleBudget(item.role, item.rawTk);
|
|
758
|
+
includedIds.add(key);
|
|
759
|
+
if (item.kind === 'class') {
|
|
760
|
+
if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, new Set());
|
|
761
|
+
fullParentClassesByFile.get(item.filePath).add(item.name);
|
|
762
|
+
}
|
|
763
|
+
if (win) {
|
|
764
|
+
for (const r of win.ranges) {
|
|
765
|
+
addCoveredRange(item.filePath, r[0], r[1]);
|
|
766
|
+
if (r[0] === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, r[1]));
|
|
767
|
+
}
|
|
768
|
+
} else {
|
|
769
|
+
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
770
|
+
if (item.startLine === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
|
|
771
|
+
}
|
|
772
|
+
addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
|
|
773
|
+
} else if (isPromotedParent && item.skelTk <= remaining) {
|
|
774
|
+
remaining -= item.skelTk;
|
|
775
|
+
dirBudgetUsed[topDir] = curDir + item.skelTk;
|
|
776
|
+
includedIds.add(key);
|
|
777
|
+
partialFiles.add(item.filePath);
|
|
778
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
|
|
779
|
+
} else if (item.skelTk <= remaining && (curDir + item.skelTk <= maxDirBudget || item.role === 'source') && canUseRoleBudget(item.role, item.skelTk)) {
|
|
780
|
+
const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
|
|
781
|
+
const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
|
|
782
|
+
if (linked) {
|
|
783
|
+
remaining -= item.skelTk;
|
|
784
|
+
dirBudgetUsed[topDir] = curDir + item.skelTk;
|
|
785
|
+
addRoleBudget(item.role, item.skelTk);
|
|
786
|
+
includedIds.add(key);
|
|
787
|
+
partialFiles.add(item.filePath);
|
|
788
|
+
if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
789
|
+
if (autoExpand && item.role === 'source' && !isPromotedParent) {
|
|
790
|
+
skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
|
|
791
|
+
} else {
|
|
792
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
|
|
793
|
+
}
|
|
794
|
+
} else {
|
|
795
|
+
partialFiles.add(item.filePath);
|
|
796
|
+
candidateItems.push(item);
|
|
797
|
+
}
|
|
798
|
+
} else {
|
|
799
|
+
partialFiles.add(item.filePath);
|
|
800
|
+
candidateItems.push(item);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
const autoExpandedNames = [];
|
|
805
|
+
if (autoExpand && skelCandidates.length > 0) {
|
|
806
|
+
for (const cand of skelCandidates) {
|
|
807
|
+
const it = cand.item;
|
|
808
|
+
const delta = Math.max(0, it.rawTk - it.skelTk);
|
|
809
|
+
const isComplexCluster = (cand.hop !== null || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
|
|
810
|
+
const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
|
|
811
|
+
if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
|
|
812
|
+
remaining -= delta;
|
|
813
|
+
autoExpandedNames.push(it.name);
|
|
814
|
+
if (cand.win) {
|
|
815
|
+
for (const r of cand.win.ranges) {
|
|
816
|
+
addCoveredRange(it.filePath, r[0], r[1]);
|
|
817
|
+
if (r[0] === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, r[1]));
|
|
818
|
+
}
|
|
819
|
+
} else {
|
|
820
|
+
addCoveredRange(it.filePath, it.startLine, it.endLine);
|
|
821
|
+
if (it.startLine === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, it.endLine));
|
|
822
|
+
}
|
|
823
|
+
addSelectedBlock(it.filePath, { tier: 'full', item: it, win: cand.win, autoExpanded: true });
|
|
824
|
+
} else {
|
|
825
|
+
addSelectedBlock(it.filePath, { tier: 'skeleton', item: it, win: cand.win, hop: cand.hop });
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
if (includedFiles.length === 0) {
|
|
831
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
832
|
+
return [
|
|
833
|
+
'<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
|
|
834
|
+
' <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>',
|
|
835
|
+
' <repository_file_tree>',
|
|
836
|
+
...treeLines,
|
|
837
|
+
' </repository_file_tree>',
|
|
838
|
+
'</context_slice>'
|
|
839
|
+
].join('\n');
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const headerByFile = new Map();
|
|
843
|
+
const headerEndByFile = new Map();
|
|
844
|
+
for (const fp of includedFiles) {
|
|
845
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
846
|
+
const entries = selectedByFile.get(fp) || [];
|
|
847
|
+
const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
|
|
848
|
+
if (hasStart1ModuleSkel) continue;
|
|
849
|
+
const hdr = fileHeaders.get(fp);
|
|
850
|
+
if (!hdr) continue;
|
|
851
|
+
if ((fullStart1EndLine.get(fp) || 0) >= hdr.endLine) continue;
|
|
852
|
+
headerEndByFile.set(fp, hdr.endLine);
|
|
853
|
+
headerByFile.set(fp, hdr);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
const footerByFile = new Map();
|
|
857
|
+
for (const fp of includedFiles) {
|
|
858
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
859
|
+
const ftr = fileFooters.get(fp);
|
|
860
|
+
if (!ftr) continue;
|
|
861
|
+
const ranges = coveredRangesByFile.get(fp) || [];
|
|
862
|
+
const totalLines = fileLineCounts.get(fp) || 0;
|
|
863
|
+
const wholeFileCovered = ranges.some((r) => r[0] <= 1 && r[1] >= totalLines);
|
|
864
|
+
if (!partialFiles.has(fp) && wholeFileCovered) continue;
|
|
865
|
+
const hdrEnd = headerEndByFile.get(fp) || 0;
|
|
866
|
+
const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some((r) => c.startLine >= r[0] && c.endLine <= r[1]));
|
|
867
|
+
if (uncovered.length > 0) {
|
|
868
|
+
footerByFile.set(fp, {
|
|
869
|
+
startLine: uncovered[0].startLine,
|
|
870
|
+
endLine: uncovered[uncovered.length - 1].endLine,
|
|
871
|
+
text: uncovered.map((c) => c.text).join('\n'),
|
|
872
|
+
chunks: uncovered
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const used = Math.max(0, budget - remaining);
|
|
878
|
+
const expandAttr = autoExpandedNames.length > 0 ? ' autoExpanded="' + escapeXmlAttr(autoExpandedNames.join(',')) + '"' : '';
|
|
879
|
+
const out = [
|
|
880
|
+
'<context_slice mode="progressive-structural-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + used + '"' + expandAttr + '>'
|
|
881
|
+
];
|
|
882
|
+
|
|
883
|
+
for (const fp of includedFiles) {
|
|
884
|
+
const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
|
|
885
|
+
const presentClassNames = new Set(rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item.name));
|
|
886
|
+
const entries = rawEntries.filter(
|
|
887
|
+
(e) => !(e.tier === 'skeleton' && e.item.kind === 'method' && presentClassNames.has(e.item.name.split('.')[0])),
|
|
888
|
+
);
|
|
889
|
+
const fullEntries = entries.filter((e) => e.tier === 'full');
|
|
890
|
+
const hdr = headerByFile.get(fp);
|
|
891
|
+
const ftr = footerByFile.get(fp);
|
|
892
|
+
const totalLines = fileLineCounts.get(fp) || 0;
|
|
893
|
+
const shownRanges = [];
|
|
894
|
+
if (hdr) shownRanges.push([1, hdr.endLine]);
|
|
895
|
+
for (const ent of entries) {
|
|
896
|
+
if (ent.win) shownRanges.push(...ent.win.ranges);
|
|
897
|
+
else shownRanges.push([ent.item.startLine, ent.item.endLine]);
|
|
898
|
+
}
|
|
899
|
+
if (ftr) {
|
|
900
|
+
for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
|
|
901
|
+
}
|
|
902
|
+
out.push(' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRanges) + '">');
|
|
903
|
+
if (hdr) {
|
|
904
|
+
out.push(' <file_header lines="1-' + hdr.endLine + '">');
|
|
905
|
+
out.push(hdr.header);
|
|
906
|
+
out.push(' </file_header>');
|
|
907
|
+
}
|
|
908
|
+
for (const ent of entries) {
|
|
909
|
+
const it = ent.item;
|
|
910
|
+
if (ent.tier === 'full') {
|
|
911
|
+
const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
|
|
912
|
+
const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
|
|
913
|
+
const autoAttr = ent.autoExpanded ? ' autoExpanded="true"' : '';
|
|
914
|
+
out.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + linesAttr + '"' + parserAttr + autoAttr + '>');
|
|
915
|
+
out.push(ent.win ? ent.win.windowedCode : it.full);
|
|
916
|
+
out.push(' </focal>');
|
|
917
|
+
} else {
|
|
918
|
+
let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
|
|
919
|
+
if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
|
|
920
|
+
const expandedChildRanges = fullEntries
|
|
921
|
+
.filter((fe) => fe.item.kind === 'method' && fe.item.name.startsWith(it.name + '.'))
|
|
922
|
+
.map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
|
|
923
|
+
if (expandedChildRanges.length > 0) {
|
|
924
|
+
skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
const hopAttr = (ent.hop !== null && ent.hop !== undefined) ? ' hop="' + ent.hop + '"' : '';
|
|
928
|
+
const skelLinesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
|
|
929
|
+
out.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + skelLinesAttr + '"' + hopAttr + '>');
|
|
930
|
+
out.push(skelBody);
|
|
931
|
+
out.push(' </skeleton>');
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
if (ftr) {
|
|
935
|
+
out.push(' <file_footer lines="' + ftr.startLine + '-' + ftr.endLine + '">');
|
|
936
|
+
out.push(ftr.text);
|
|
937
|
+
out.push(' </file_footer>');
|
|
938
|
+
}
|
|
939
|
+
out.push(' </file>');
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
const omitted = candidateItems.filter((it) => it.score > 0 && !includedIds.has(it.filePath + ':' + it.startLine)).slice(0, 3);
|
|
943
|
+
if (omitted.length > 0) {
|
|
944
|
+
out.push(' <omitted_top_matches>');
|
|
945
|
+
for (const o of omitted) {
|
|
946
|
+
out.push(' <!-- Omitted: ' + o.filePath + ':' + o.startLine + ' (' + o.name + ', score: ' + o.score.toFixed(1) + ') — consider expanding -->');
|
|
947
|
+
}
|
|
948
|
+
out.push(' </omitted_top_matches>');
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
out.push('</context_slice>');
|
|
952
|
+
return out.join('\n');
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
|
|
9
956
|
const CJK_RE = /[一-鿿-ゟ゠-ヿ가-]/;
|
|
10
957
|
const CJK_RUN_RE = new RegExp('[一-鿿-ゟ゠-ヿ가-]+', 'g');
|
|
11
958
|
const CJK_WORDS = {
|
|
@@ -353,31 +1300,54 @@ function bilingualLookup(term) {
|
|
|
353
1300
|
return out;
|
|
354
1301
|
}
|
|
355
1302
|
function expandQueryTerms(query) {
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
const
|
|
1303
|
+
const trimmed = String(query || '').trim();
|
|
1304
|
+
if (!trimmed) return [];
|
|
1305
|
+
const q = trimmed.toLowerCase();
|
|
1306
|
+
const terms = new Set();
|
|
1307
|
+
const asciiParts = q.match(/[a-z0-9_]+(?:[.-][a-z0-9_]+)*/g) || [];
|
|
359
1308
|
for (const p of asciiParts) {
|
|
360
|
-
if (p.length >= 2
|
|
361
|
-
|
|
1309
|
+
if (p.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(p)) {
|
|
1310
|
+
terms.add(p);
|
|
1311
|
+
if (/^v\d/.test(p) && p.length >= 3) terms.add(p.slice(1));
|
|
1312
|
+
if (p.includes('.') || p.includes('-')) {
|
|
1313
|
+
for (const sub of p.split(/[.-]/)) {
|
|
1314
|
+
if (sub.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(sub)) terms.add(sub);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
for (const t of bilingualLookup(p)) terms.add(t);
|
|
1318
|
+
}
|
|
362
1319
|
}
|
|
363
|
-
if (containsCJK(
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
for (const
|
|
1320
|
+
if (containsCJK(trimmed)) {
|
|
1321
|
+
const cleanedCjk = trimmed.replace(ZH_CONVERSATIONAL_STOPWORDS_RE, ' ');
|
|
1322
|
+
if (containsCJK(cleanedCjk)) {
|
|
1323
|
+
for (const gram of tokenizeCJK2gram(cleanedCjk)) {
|
|
1324
|
+
terms.add(gram);
|
|
1325
|
+
for (const t of bilingualLookup(gram)) terms.add(t);
|
|
1326
|
+
}
|
|
1327
|
+
for (const run of cleanedCjk.match(CJK_RUN_RE) || []) {
|
|
1328
|
+
terms.add(run);
|
|
1329
|
+
for (const t of bilingualLookup(run)) terms.add(t);
|
|
1330
|
+
}
|
|
367
1331
|
}
|
|
368
|
-
for (const run of q.match(CJK_RUN_RE) || []) terms.add(run);
|
|
369
1332
|
}
|
|
370
|
-
|
|
1333
|
+
const snapshot = [...terms];
|
|
1334
|
+
for (const term of snapshot) {
|
|
1335
|
+
for (const t of bilingualLookup(term)) terms.add(t);
|
|
1336
|
+
}
|
|
1337
|
+
// Filter pure syntax keywords (class, def, function...) whenever non-syntax identifiers exist
|
|
1338
|
+
const collected = [...terms].filter(Boolean);
|
|
1339
|
+
const nonSyntax = collected.filter((t) => !SYNTAX_NOISE_WORDS.has(t));
|
|
1340
|
+
return nonSyntax.length > 0 ? nonSyntax : collected;
|
|
371
1341
|
}
|
|
372
1342
|
|
|
373
1343
|
const args = process.argv.slice(2);
|
|
374
1344
|
if (args.includes('--version') || args.includes('-v')) {
|
|
375
|
-
process.stdout.write('ctxslice v0.
|
|
1345
|
+
process.stdout.write('ctxslice v0.4.1\n');
|
|
376
1346
|
process.exit(0);
|
|
377
1347
|
}
|
|
378
1348
|
if (args.includes('--help') || args.includes('-h')) {
|
|
379
1349
|
process.stdout.write(
|
|
380
|
-
'ContextSlice CLI v0.
|
|
1350
|
+
'ContextSlice CLI v0.4.1 — Zero-Config Multi-Language Structural Code Slicer\n\n' +
|
|
381
1351
|
'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
|
|
382
1352
|
'Options:\n --root <dir> Target repository path (default: current directory)\n' +
|
|
383
1353
|
' --budget <num> Max token budget (default: 32768)\n' +
|
|
@@ -390,8 +1360,11 @@ const rootFlag = args.indexOf('--root');
|
|
|
390
1360
|
const targetRoot = rootFlag !== -1 && args[rootFlag + 1] ? path.resolve(args[rootFlag + 1]) : process.cwd();
|
|
391
1361
|
const budgetFlag = args.indexOf('--budget');
|
|
392
1362
|
const budget = budgetFlag !== -1 ? Number(args[budgetFlag + 1]) : 32768;
|
|
393
|
-
const skipIdx = new Set(
|
|
394
|
-
|
|
1363
|
+
const skipIdx = new Set();
|
|
1364
|
+
if (rootFlag !== -1) { skipIdx.add(rootFlag); skipIdx.add(rootFlag + 1); }
|
|
1365
|
+
if (budgetFlag !== -1) { skipIdx.add(budgetFlag); skipIdx.add(budgetFlag + 1); }
|
|
1366
|
+
const queryArg = args.find((a, idx) => !skipIdx.has(idx) && !a.startsWith('--'));
|
|
1367
|
+
const query = queryArg !== undefined ? queryArg : '';
|
|
395
1368
|
const IGNORE = new Set([
|
|
396
1369
|
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
397
1370
|
'venv', '.venv', '__pycache__', 'vendor', 'target', '.build', '.swiftpm', 'DerivedData', 'Pods', 'bin', 'obj'
|
|
@@ -405,7 +1378,7 @@ const BINARY_EXT = new Set([
|
|
|
405
1378
|
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods', '.odp', '.rtf',
|
|
406
1379
|
'.db', '.sqlite', '.sqlite3', '.mdb', '.psd', '.ai', '.sketch', '.fig', '.xd', '.blend'
|
|
407
1380
|
]);
|
|
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;
|
|
1381
|
+
const NOISE_FILE = /(^|\/)(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;
|
|
409
1382
|
const CONTROL_WORDS = new Set(['if', 'else', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'typeof', 'do', 'try']);
|
|
410
1383
|
|
|
411
1384
|
function isTextCandidate(full) {
|
|
@@ -436,13 +1409,6 @@ function walk(dir, acc = []) {
|
|
|
436
1409
|
return acc;
|
|
437
1410
|
}
|
|
438
1411
|
|
|
439
|
-
function estimateTokens(str) {
|
|
440
|
-
if (!str) return 0;
|
|
441
|
-
let cjk = 0;
|
|
442
|
-
for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
|
|
443
|
-
return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
|
|
444
|
-
}
|
|
445
|
-
|
|
446
1412
|
|
|
447
1413
|
function maskCommentsAndStrings(code) {
|
|
448
1414
|
return code
|
|
@@ -486,20 +1452,10 @@ function extractBlocks(code, ext, fileName) {
|
|
|
486
1452
|
let m = null;
|
|
487
1453
|
|
|
488
1454
|
if (e === '.py' || e === '.pyw') {
|
|
489
|
-
|
|
490
|
-
if (
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
let end = i;
|
|
494
|
-
for (let j = i + 1; j < lines.length; j++) {
|
|
495
|
-
if (lines[j].trim() === '' || /^\s+/.test(lines[j])) end = j;
|
|
496
|
-
else break;
|
|
497
|
-
}
|
|
498
|
-
while (end > i && lines[end].trim() === '') end--;
|
|
499
|
-
const full = lines.slice(i, end + 1).join('\n');
|
|
500
|
-
const skeleton = end - i > 2 ? `${lines[i]}\n # ... ${end - i} lines folded` : full;
|
|
501
|
-
blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
502
|
-
i = end;
|
|
1455
|
+
const pyRes = extractPythonBlocks(lines, i);
|
|
1456
|
+
if (pyRes) {
|
|
1457
|
+
blocks.push(...pyRes.blocks);
|
|
1458
|
+
i = pyRes.endIdx;
|
|
503
1459
|
continue;
|
|
504
1460
|
}
|
|
505
1461
|
}
|
|
@@ -965,222 +1921,59 @@ function extractFileFooter(content, tailLines = 20) {
|
|
|
965
1921
|
|
|
966
1922
|
|
|
967
1923
|
const files = walk(targetRoot);
|
|
968
|
-
const terms = expandQueryTerms(query);
|
|
969
|
-
const allRawBlocks = [];
|
|
970
|
-
const fileHeaders = new Map();
|
|
971
|
-
const fileFooters = new Map();
|
|
972
1924
|
const fileLineCounts = new Map();
|
|
1925
|
+
const fileEntries = [];
|
|
1926
|
+
const textRecords = [];
|
|
973
1927
|
for (const filePath of files) {
|
|
974
1928
|
try {
|
|
975
1929
|
const buf = fs.readFileSync(filePath);
|
|
976
1930
|
if (isBinaryBuffer(buf)) continue;
|
|
977
1931
|
const content = buf.toString('utf8');
|
|
978
|
-
const relPath = path.relative(targetRoot, filePath);
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
if (ftr) fileFooters.set(relPath, ftr);
|
|
984
|
-
const items = extractBlocks(content, path.extname(filePath), relPath);
|
|
985
|
-
for (const b of items) {
|
|
986
|
-
allRawBlocks.push({
|
|
987
|
-
...b,
|
|
988
|
-
filePath: relPath,
|
|
989
|
-
rawTokens: estimateTokens(b.full),
|
|
990
|
-
skelTokens: estimateTokens(b.skeleton),
|
|
991
|
-
});
|
|
992
|
-
}
|
|
1932
|
+
const relPath = path.relative(targetRoot, filePath).replace(/\\/g, '/');
|
|
1933
|
+
const lineCount = content.replace(/\r\n/g, '\n').split('\n').length;
|
|
1934
|
+
fileLineCounts.set(relPath, lineCount);
|
|
1935
|
+
fileEntries.push({ relPath, lineCount });
|
|
1936
|
+
textRecords.push({ filePath, relPath, content });
|
|
993
1937
|
} catch {}
|
|
994
1938
|
}
|
|
995
1939
|
|
|
996
|
-
const
|
|
997
|
-
const
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
for (const b of allRawBlocks) {
|
|
1001
|
-
if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
|
|
1002
|
-
df++;
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
termDF[t] = Math.max(1, df);
|
|
1006
|
-
}
|
|
1940
|
+
const terms = expandQueryTerms(query);
|
|
1941
|
+
const allRawBlocks = [];
|
|
1942
|
+
const fileHeaders = new Map();
|
|
1943
|
+
const fileFooters = new Map();
|
|
1007
1944
|
|
|
1008
|
-
|
|
1009
|
-
const
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
const nameMatch = b.name.toLowerCase().includes(t) ? 35 : 0;
|
|
1017
|
-
const pathMatch = relLower.includes(t) ? 25 : 0;
|
|
1018
|
-
const bodyOcc = lower.split(t).length - 1;
|
|
1019
|
-
const bodyScore = Math.min(15, 3 * Math.log1p(bodyOcc));
|
|
1020
|
-
score += (nameMatch + pathMatch + bodyScore) * idf * scarcityMultiplier;
|
|
1021
|
-
}
|
|
1022
|
-
return { ...b, score };
|
|
1023
|
-
}).sort((a, b) => b.score - a.score);
|
|
1024
|
-
|
|
1025
|
-
// True Call Graph (SymbolMap + Word-Boundary Call/Constant Matching + BFS maxHops)
|
|
1026
|
-
const symbolMap = new Map();
|
|
1027
|
-
const constSymbolNames = new Set();
|
|
1028
|
-
for (let i = 0; i < scored.length; i++) {
|
|
1029
|
-
const b = scored[i];
|
|
1030
|
-
if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
|
|
1031
|
-
const names = (b.kind === 'const' && b.name.includes(','))
|
|
1032
|
-
? b.name.split(',').map((s) => s.trim()).filter(Boolean)
|
|
1033
|
-
: [b.name];
|
|
1034
|
-
for (const sn of names) {
|
|
1035
|
-
if (!symbolMap.has(sn)) symbolMap.set(sn, []);
|
|
1036
|
-
symbolMap.get(sn).push(i);
|
|
1037
|
-
if (b.kind === 'const') constSymbolNames.add(sn);
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
const callAdj = Array.from({ length: scored.length }, () => new Set());
|
|
1042
|
-
const definedNames = Array.from(symbolMap.keys());
|
|
1043
|
-
for (let i = 0; i < scored.length; i++) {
|
|
1044
|
-
const caller = scored[i];
|
|
1045
|
-
const maskedCaller = maskCommentsAndStrings(caller.full);
|
|
1046
|
-
for (const sym of definedNames) {
|
|
1047
|
-
if (sym === caller.name) continue;
|
|
1048
|
-
if (maskedCaller.includes(sym)) {
|
|
1049
|
-
const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1050
|
-
const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
|
|
1051
|
-
const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
|
|
1052
|
-
if (re.test(maskedCaller)) {
|
|
1053
|
-
for (const t of (symbolMap.get(sym) || [])) {
|
|
1054
|
-
callAdj[i].add(t);
|
|
1055
|
-
callAdj[t].add(i);
|
|
1056
|
-
}
|
|
1057
|
-
}
|
|
1945
|
+
if (query.trim()) {
|
|
1946
|
+
for (const rec of textRecords) {
|
|
1947
|
+
const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rec.relPath) || DOC_EXT_RE.test(rec.relPath);
|
|
1948
|
+
if (!skipHdrFtr) {
|
|
1949
|
+
const hdr = extractFileHeader(rec.content);
|
|
1950
|
+
if (hdr) fileHeaders.set(rec.relPath, hdr);
|
|
1951
|
+
const ftr = extractFileFooter(rec.content);
|
|
1952
|
+
if (ftr) fileFooters.set(rec.relPath, ftr);
|
|
1058
1953
|
}
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
const focalFiles = new Set();
|
|
1063
|
-
const bfsQ = [];
|
|
1064
|
-
for (let i = 0; i < scored.length; i++) {
|
|
1065
|
-
if (scored[i].score > 0 && bfsQ.length < 3) {
|
|
1066
|
-
bfsQ.push(i);
|
|
1067
|
-
hopDistances.set(i, 0);
|
|
1068
|
-
focalFiles.add(scored[i].filePath);
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
let qHead = 0;
|
|
1072
|
-
while (qHead < bfsQ.length) {
|
|
1073
|
-
const curr = bfsQ[qHead++];
|
|
1074
|
-
const curHop = hopDistances.get(curr) ?? 0;
|
|
1075
|
-
if (curHop >= 2) continue;
|
|
1076
|
-
for (const nbr of callAdj[curr]) {
|
|
1077
|
-
if (!hopDistances.has(nbr)) {
|
|
1078
|
-
hopDistances.set(nbr, curHop + 1);
|
|
1079
|
-
bfsQ.push(nbr);
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
let remaining = budget;
|
|
1085
|
-
const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.5" budget="' + budget + '">'];
|
|
1086
|
-
const includedIds = new Set();
|
|
1087
|
-
const includedFiles = new Set();
|
|
1088
|
-
const fullStart1EndLine = new Map();
|
|
1089
|
-
const coveredRangesByFile = new Map();
|
|
1090
|
-
const partialFiles = new Set();
|
|
1091
|
-
const addCoveredRange = (fp, s, e) => {
|
|
1092
|
-
if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
|
|
1093
|
-
coveredRangesByFile.get(fp).push([s, e]);
|
|
1094
|
-
};
|
|
1095
|
-
const dirBudgetUsed = {};
|
|
1096
|
-
const maxDirBudget = budget * 0.65;
|
|
1097
|
-
|
|
1098
|
-
const candidateItems = [];
|
|
1099
|
-
for (let i = 0; i < scored.length; i++) {
|
|
1100
|
-
const item = scored[i];
|
|
1101
|
-
const topDir = item.filePath.split(path.sep)[0] || 'root';
|
|
1102
|
-
const curDir = dirBudgetUsed[topDir] || 0;
|
|
1103
|
-
const hop = hopDistances.get(i);
|
|
1104
|
-
const isFocal = hop === 0 || (i < 2 && item.score > 0);
|
|
1105
|
-
const key = item.filePath + ':' + item.startLine;
|
|
1106
|
-
|
|
1107
|
-
if (isFocal && item.rawTokens <= remaining && curDir + item.rawTokens <= maxDirBudget) {
|
|
1108
|
-
remaining -= item.rawTokens;
|
|
1109
|
-
dirBudgetUsed[topDir] = curDir + item.rawTokens;
|
|
1110
|
-
includedIds.add(key);
|
|
1111
|
-
includedFiles.add(item.filePath);
|
|
1112
|
-
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
1113
|
-
if (item.startLine === 1) {
|
|
1114
|
-
fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
|
|
1115
|
-
}
|
|
1116
|
-
out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
|
|
1117
|
-
out.push(item.full);
|
|
1118
|
-
} else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
|
|
1119
|
-
const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && (item.endLine - item.startLine + 1) <= 25 && focalFiles.has(item.filePath);
|
|
1120
|
-
const linked = (hop !== undefined && hop <= 2) || item.score > 0 || sameFileConst;
|
|
1121
|
-
if (linked || i < 12) {
|
|
1122
|
-
remaining -= item.skelTokens;
|
|
1123
|
-
dirBudgetUsed[topDir] = curDir + item.skelTokens;
|
|
1124
|
-
includedIds.add(key);
|
|
1125
|
-
includedFiles.add(item.filePath);
|
|
1126
|
-
partialFiles.add(item.filePath);
|
|
1127
|
-
if (item.skeleton === item.full) {
|
|
1128
|
-
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
1129
|
-
}
|
|
1130
|
-
out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
|
|
1131
|
-
out.push(item.skeleton);
|
|
1132
|
-
} else {
|
|
1133
|
-
partialFiles.add(item.filePath);
|
|
1134
|
-
candidateItems.push(item);
|
|
1954
|
+
const items = extractBlocks(rec.content, path.extname(rec.filePath), rec.relPath);
|
|
1955
|
+
for (const b of items) {
|
|
1956
|
+
allRawBlocks.push({ ...b, filePath: rec.relPath });
|
|
1135
1957
|
}
|
|
1136
|
-
} else {
|
|
1137
|
-
partialFiles.add(item.filePath);
|
|
1138
|
-
candidateItems.push(item);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
const headerChunks = [];
|
|
1143
|
-
const headerEndByFile = new Map();
|
|
1144
|
-
for (const fp of includedFiles) {
|
|
1145
|
-
const hdr = fileHeaders.get(fp);
|
|
1146
|
-
if (!hdr) continue;
|
|
1147
|
-
const coveredEnd = fullStart1EndLine.get(fp) || 0;
|
|
1148
|
-
if (coveredEnd >= hdr.endLine) continue;
|
|
1149
|
-
headerEndByFile.set(fp, hdr.endLine);
|
|
1150
|
-
headerChunks.push(` <!-- FILE_HEADER: ${fp}:1-${hdr.endLine} -->`);
|
|
1151
|
-
headerChunks.push(hdr.header);
|
|
1152
|
-
}
|
|
1153
|
-
if (headerChunks.length > 0) {
|
|
1154
|
-
out.splice(1, 0, '<file_headers>', ...headerChunks, '</file_headers>');
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
const footerChunks = [];
|
|
1158
|
-
for (const fp of includedFiles) {
|
|
1159
|
-
const ftr = fileFooters.get(fp);
|
|
1160
|
-
if (!ftr) continue;
|
|
1161
|
-
const ranges = coveredRangesByFile.get(fp) || [];
|
|
1162
|
-
const totalLines = fileLineCounts.get(fp) || 0;
|
|
1163
|
-
const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
|
|
1164
|
-
if (!partialFiles.has(fp) && wholeFileCovered) continue;
|
|
1165
|
-
const hdrEnd = headerEndByFile.get(fp) || 0;
|
|
1166
|
-
const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
|
|
1167
|
-
if (uncovered.length > 0) {
|
|
1168
|
-
footerChunks.push(` <!-- FILE_FOOTER: ${fp}:${uncovered[0].startLine}-${uncovered[uncovered.length - 1].endLine} -->`);
|
|
1169
|
-
footerChunks.push(uncovered.map((c) => c.text).join('\n'));
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
if (footerChunks.length > 0) {
|
|
1173
|
-
out.push('<file_footers>', ...footerChunks, '</file_footers>');
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
|
|
1177
|
-
if (omitted.length > 0) {
|
|
1178
|
-
out.push('<omitted_top_matches>');
|
|
1179
|
-
for (const o of omitted) {
|
|
1180
|
-
out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
|
|
1181
1958
|
}
|
|
1182
|
-
out.push('</omitted_top_matches>');
|
|
1183
1959
|
}
|
|
1184
1960
|
|
|
1185
|
-
|
|
1186
|
-
|
|
1961
|
+
const outputXml = assembleContextSliceXml({
|
|
1962
|
+
blocks: allRawBlocks,
|
|
1963
|
+
fileEntries,
|
|
1964
|
+
fileLineCounts,
|
|
1965
|
+
fileHeaders,
|
|
1966
|
+
fileFooters,
|
|
1967
|
+
rawQuery: query,
|
|
1968
|
+
terms,
|
|
1969
|
+
budget,
|
|
1970
|
+
maxHops: 2,
|
|
1971
|
+
autoExpand: false,
|
|
1972
|
+
rootAttr: path.basename(targetRoot),
|
|
1973
|
+
version: '0.4.1',
|
|
1974
|
+
subPathTag: '',
|
|
1975
|
+
includeParserAttr: false,
|
|
1976
|
+
controlWords: CONTROL_WORDS,
|
|
1977
|
+
maskFn: maskCommentsAndStrings
|
|
1978
|
+
});
|
|
1979
|
+
process.stdout.write(outputXml + '\n');
|