@grundy40/contextslice 0.4.1 → 0.4.3
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 +2 -2
- package/bin/ctxslice-mcp.mjs +974 -79
- package/bin/ctxslice.mjs +869 -67
- package/package.json +1 -1
package/bin/ctxslice.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.
|
|
3
|
+
* ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.3)
|
|
4
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';
|
|
@@ -8,6 +8,7 @@ import path from 'node:path';
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
|
|
11
|
+
const HTML_EXT_RE = /\.(html?|xhtml)$/i;
|
|
11
12
|
const EN_CONVERSATIONAL_STOPWORDS = new Set([
|
|
12
13
|
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
|
|
13
14
|
'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
|
|
@@ -208,6 +209,373 @@ function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
|
|
|
208
209
|
};
|
|
209
210
|
}
|
|
210
211
|
|
|
212
|
+
function dedentHtmlInnerLines(rawLines) {
|
|
213
|
+
let minIndent = Infinity;
|
|
214
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
215
|
+
const l = rawLines[i];
|
|
216
|
+
if (!l.trim()) continue;
|
|
217
|
+
const indent = (l.match(/^[ \t]*/) || [''])[0].length;
|
|
218
|
+
if (indent < minIndent) minIndent = indent;
|
|
219
|
+
}
|
|
220
|
+
if (!Number.isFinite(minIndent) || minIndent <= 0) return rawLines.join('\n');
|
|
221
|
+
return rawLines.map((l) => (l.length >= minIndent ? l.slice(minIndent) : l.trimStart())).join('\n');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function findHtmlTagCloseIdx(lines, startIdx, tag) {
|
|
225
|
+
if (tag === 'script' || tag === 'style') {
|
|
226
|
+
const closeRawRe = new RegExp('</' + tag + '\\s*>', 'i');
|
|
227
|
+
const firstLine = lines[startIdx] || '';
|
|
228
|
+
const gtIdx = firstLine.indexOf('>');
|
|
229
|
+
if (gtIdx !== -1 && closeRawRe.test(firstLine.slice(gtIdx + 1))) {
|
|
230
|
+
return startIdx;
|
|
231
|
+
}
|
|
232
|
+
for (let i = startIdx + 1; i < lines.length; i++) {
|
|
233
|
+
if (closeRawRe.test(lines[i])) return i;
|
|
234
|
+
}
|
|
235
|
+
return lines.length - 1;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const openTagRe = new RegExp('<' + tag + '(?:\\s|>)', 'gi');
|
|
239
|
+
const closeTagRe = new RegExp('</' + tag + '\\s*>', 'gi');
|
|
240
|
+
const selfCloseRe = new RegExp('<' + tag + '\\b[^>]*/>', 'gi');
|
|
241
|
+
let depth = 0;
|
|
242
|
+
let inRawTag = null;
|
|
243
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
244
|
+
const line = lines[i];
|
|
245
|
+
if (inRawTag) {
|
|
246
|
+
if (new RegExp('</' + inRawTag + '\\s*>', 'i').test(line)) {
|
|
247
|
+
inRawTag = null;
|
|
248
|
+
}
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const rawOpen = line.match(/<(script|style)(?:\s|>)/i);
|
|
252
|
+
if (rawOpen && i > startIdx) {
|
|
253
|
+
const rTag = rawOpen[1].toLowerCase();
|
|
254
|
+
if (!new RegExp('</' + rTag + '\\s*>', 'i').test(line)) {
|
|
255
|
+
inRawTag = rTag;
|
|
256
|
+
}
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const opens = (line.match(openTagRe) || []).length - (line.match(selfCloseRe) || []).length;
|
|
260
|
+
const closes = (line.match(closeTagRe) || []).length;
|
|
261
|
+
depth += opens - closes;
|
|
262
|
+
if (depth <= 0 && i >= startIdx) {
|
|
263
|
+
return i;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return lines.length - 1;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function buildHtmlSectionSkeleton(lines, startIdx, endIdx, tag) {
|
|
270
|
+
const full = lines.slice(startIdx, endIdx + 1).join('\n');
|
|
271
|
+
const lineCount = endIdx - startIdx + 1;
|
|
272
|
+
if (lineCount <= 10) return full;
|
|
273
|
+
const openLine = lines[startIdx];
|
|
274
|
+
const previewLine = lines[startIdx + 1] !== undefined ? lines[startIdx + 1] : '';
|
|
275
|
+
const closeLine = lines[endIdx] || ('</' + tag + '>');
|
|
276
|
+
const folded = Math.max(1, lineCount - 3);
|
|
277
|
+
const comment = tag === 'style'
|
|
278
|
+
? ' /* ... ' + folded + ' lines folded */'
|
|
279
|
+
: ' <!-- ... ' + folded + ' lines folded -->';
|
|
280
|
+
return openLine + (previewLine ? '\n' + previewLine : '') + '\n' + comment + '\n' + closeLine;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function extractHtmlBlocks(code, fileName, extractJsBlocksFn) {
|
|
284
|
+
const lines = String(code || '').replace(/\r\n/g, '\n').split('\n');
|
|
285
|
+
if (lines.length === 0) return [];
|
|
286
|
+
const blocks = [];
|
|
287
|
+
const rawTagRanges = [];
|
|
288
|
+
const isInRanges = (ranges, ln) => ranges.some((r) => ln >= r[0] && ln <= r[1]);
|
|
289
|
+
|
|
290
|
+
// Pass 1: Extract <style> and inline <script> blocks (and nested JS symbols inside <script>)
|
|
291
|
+
const rawOpenRe = /^([ \t]*)<(script|style)(?:\s+([^>]*))?>/i;
|
|
292
|
+
for (let i = 0; i < lines.length; i++) {
|
|
293
|
+
const startLine = i + 1;
|
|
294
|
+
if (isInRanges(rawTagRanges, startLine)) continue;
|
|
295
|
+
const m = lines[i].match(rawOpenRe);
|
|
296
|
+
if (!m) continue;
|
|
297
|
+
const tag = m[2].toLowerCase();
|
|
298
|
+
const attrs = m[3] || '';
|
|
299
|
+
if (tag === 'script' && /\bsrc\s*=/i.test(attrs)) continue;
|
|
300
|
+
|
|
301
|
+
const endIdx = findHtmlTagCloseIdx(lines, i, tag);
|
|
302
|
+
const endLine = endIdx + 1;
|
|
303
|
+
const lineCount = endLine - startLine + 1;
|
|
304
|
+
if (lineCount < 2) continue;
|
|
305
|
+
|
|
306
|
+
rawTagRanges.push([startLine, endLine]);
|
|
307
|
+
|
|
308
|
+
if (tag === 'style') {
|
|
309
|
+
const full = lines.slice(i, endLine).join('\n');
|
|
310
|
+
blocks.push({
|
|
311
|
+
name: '<style>',
|
|
312
|
+
kind: 'type',
|
|
313
|
+
exported: true,
|
|
314
|
+
startLine,
|
|
315
|
+
endLine,
|
|
316
|
+
full,
|
|
317
|
+
skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, 'style')
|
|
318
|
+
});
|
|
319
|
+
i = endIdx;
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Inline <script>: extract JS symbols and shift line numbers back to HTML lines
|
|
324
|
+
const innerStartIdx = i + 1;
|
|
325
|
+
const innerEndIdx = endIdx; // exclusive in lines.slice (endIdx is closing </script> line)
|
|
326
|
+
let parsedInner = false;
|
|
327
|
+
if (innerEndIdx > innerStartIdx && typeof extractJsBlocksFn === 'function') {
|
|
328
|
+
const innerRawLines = lines.slice(innerStartIdx, innerEndIdx);
|
|
329
|
+
const dedented = dedentHtmlInnerLines(innerRawLines);
|
|
330
|
+
if (dedented.trim()) {
|
|
331
|
+
const jsBlocks = extractJsBlocksFn(dedented) || [];
|
|
332
|
+
const realJs = jsBlocks.filter((b) => b.kind !== 'module');
|
|
333
|
+
if (realJs.length > 0) {
|
|
334
|
+
parsedInner = true;
|
|
335
|
+
const coveredInner = [];
|
|
336
|
+
for (const jb of realJs) {
|
|
337
|
+
const realStart = jb.startLine + innerStartIdx;
|
|
338
|
+
const realEnd = Math.min(endLine - 1, jb.endLine + innerStartIdx);
|
|
339
|
+
const realFull = lines.slice(realStart - 1, realEnd).join('\n');
|
|
340
|
+
const realLinesCount = Math.max(1, realEnd - realStart + 1);
|
|
341
|
+
let realSkel = jb.skeleton;
|
|
342
|
+
if (realLinesCount <= 4) {
|
|
343
|
+
realSkel = realFull;
|
|
344
|
+
}
|
|
345
|
+
coveredInner.push([realStart, realEnd]);
|
|
346
|
+
blocks.push({
|
|
347
|
+
...jb,
|
|
348
|
+
startLine: realStart,
|
|
349
|
+
endLine: realEnd,
|
|
350
|
+
full: realFull,
|
|
351
|
+
skeleton: realSkel
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Preserve substantial top-level script chunks outside functions (e.g. DOM bindings/init)
|
|
356
|
+
let chunkStart = -1;
|
|
357
|
+
let nonEmptyCount = 0;
|
|
358
|
+
const flushTopChunk = (endLn) => {
|
|
359
|
+
if (chunkStart !== -1 && nonEmptyCount >= 6) {
|
|
360
|
+
let cStart = chunkStart;
|
|
361
|
+
let cEnd = endLn;
|
|
362
|
+
while (cStart <= cEnd && !lines[cStart - 1].trim()) cStart++;
|
|
363
|
+
while (cEnd >= cStart && !lines[cEnd - 1].trim()) cEnd--;
|
|
364
|
+
if (cEnd - cStart + 1 >= 5) {
|
|
365
|
+
const cFull = lines.slice(cStart - 1, cEnd).join('\n');
|
|
366
|
+
const cCount = cEnd - cStart + 1;
|
|
367
|
+
const cSkel = cCount > 10
|
|
368
|
+
? lines[cStart - 1] + '\n' + (lines[cStart] || '') + '\n /* ... ' + (cCount - 3) + ' script lines folded */\n' + lines[cEnd - 1]
|
|
369
|
+
: cFull;
|
|
370
|
+
blocks.push({
|
|
371
|
+
name: '<script#top@' + cStart + '>',
|
|
372
|
+
kind: 'const',
|
|
373
|
+
exported: false,
|
|
374
|
+
startLine: cStart,
|
|
375
|
+
endLine: cEnd,
|
|
376
|
+
full: cFull,
|
|
377
|
+
skeleton: cSkel
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
chunkStart = -1;
|
|
382
|
+
nonEmptyCount = 0;
|
|
383
|
+
};
|
|
384
|
+
for (let ln = innerStartIdx + 1; ln <= endLine - 1; ln++) {
|
|
385
|
+
if (isInRanges(coveredInner, ln)) {
|
|
386
|
+
flushTopChunk(ln - 1);
|
|
387
|
+
} else {
|
|
388
|
+
if (chunkStart === -1) chunkStart = ln;
|
|
389
|
+
if (lines[ln - 1] && lines[ln - 1].trim()) nonEmptyCount++;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
flushTopChunk(endLine - 1);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (!parsedInner) {
|
|
398
|
+
const full = lines.slice(i, endLine).join('\n');
|
|
399
|
+
blocks.push({
|
|
400
|
+
name: '<script>',
|
|
401
|
+
kind: 'module',
|
|
402
|
+
exported: true,
|
|
403
|
+
startLine,
|
|
404
|
+
endLine,
|
|
405
|
+
full,
|
|
406
|
+
skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, 'script')
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
i = endIdx;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Pass 2: Extract HTML structural landmark sections without overlapping <script>/<style>
|
|
413
|
+
const landmarkRanges = [];
|
|
414
|
+
const landmarkRe = /^([ \t]*)<(head|header|nav|main|section|article|form|template|footer|div)(?:\s+([^>]*))?>/i;
|
|
415
|
+
for (let i = 0; i < lines.length; i++) {
|
|
416
|
+
const startLine = i + 1;
|
|
417
|
+
if (isInRanges(rawTagRanges, startLine) || isInRanges(landmarkRanges, startLine)) continue;
|
|
418
|
+
const m = lines[i].match(landmarkRe);
|
|
419
|
+
if (!m) continue;
|
|
420
|
+
|
|
421
|
+
const tag = m[2].toLowerCase();
|
|
422
|
+
const attrs = m[3] || '';
|
|
423
|
+
const idMatch = attrs.match(/\bid=["']([^"']+)["']/i);
|
|
424
|
+
const classMatch = attrs.match(/\bclass=["']([^"'\s]+)/i);
|
|
425
|
+
if (tag === 'div' && !idMatch) continue;
|
|
426
|
+
|
|
427
|
+
let endIdx = findHtmlTagCloseIdx(lines, i, tag);
|
|
428
|
+
let endLine = endIdx + 1;
|
|
429
|
+
if (endLine - startLine + 1 < 2) continue;
|
|
430
|
+
|
|
431
|
+
// Avoid enclosing child <script> or <style> inside outer container blocks (<head>, <main>, <div#app>)
|
|
432
|
+
const overlapsRaw = rawTagRanges.filter((r) => r[0] > startLine && r[0] <= endLine);
|
|
433
|
+
if (overlapsRaw.length > 0) {
|
|
434
|
+
const firstRawStart = Math.min(...overlapsRaw.map((r) => r[0]));
|
|
435
|
+
if (firstRawStart - startLine >= 3) {
|
|
436
|
+
endLine = firstRawStart - 1;
|
|
437
|
+
endIdx = endLine - 1;
|
|
438
|
+
} else {
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (tag === 'main' || tag === 'div') {
|
|
444
|
+
const hasChildSection = lines
|
|
445
|
+
.slice(i + 1, Math.max(i + 1, endLine - 1))
|
|
446
|
+
.some((l) => /^\s*<(section|article|form|template)(?:\s|>)/i.test(l));
|
|
447
|
+
if (hasChildSection) continue;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
landmarkRanges.push([startLine, endLine]);
|
|
451
|
+
const suffix = idMatch ? '#' + idMatch[1] : (classMatch ? '.' + classMatch[1] : '');
|
|
452
|
+
const name = '<' + tag + suffix + '>';
|
|
453
|
+
const full = lines.slice(i, endLine).join('\n');
|
|
454
|
+
blocks.push({
|
|
455
|
+
name,
|
|
456
|
+
kind: tag === 'template' ? 'class' : 'type',
|
|
457
|
+
exported: true,
|
|
458
|
+
startLine,
|
|
459
|
+
endLine,
|
|
460
|
+
full,
|
|
461
|
+
skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, tag)
|
|
462
|
+
});
|
|
463
|
+
i = endIdx;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
blocks.sort((a, b) => a.startLine - b.startLine);
|
|
467
|
+
return blocks;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function sliceSingleFileWindow(content, maxTokens) {
|
|
471
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
472
|
+
if (lines.length === 0) return { windowedCode: '', ranges: [[1, 1]], tokens: 0 };
|
|
473
|
+
const headBudget = Math.max(120, Math.floor(maxTokens * 0.7));
|
|
474
|
+
const tailBudget = Math.max(60, maxTokens - headBudget - 15);
|
|
475
|
+
const headLines = [];
|
|
476
|
+
let headTk = 0;
|
|
477
|
+
let headEnd = 0;
|
|
478
|
+
for (let i = 0; i < lines.length; i++) {
|
|
479
|
+
const tk = estimateTokens(lines[i]);
|
|
480
|
+
if (headTk + tk > headBudget && headLines.length > 0) break;
|
|
481
|
+
headLines.push(lines[i]);
|
|
482
|
+
headTk += tk;
|
|
483
|
+
headEnd = i + 1;
|
|
484
|
+
}
|
|
485
|
+
const tailLinesRev = [];
|
|
486
|
+
let tailTk = 0;
|
|
487
|
+
let tailStart = lines.length + 1;
|
|
488
|
+
for (let i = lines.length - 1; i >= headEnd; i--) {
|
|
489
|
+
const tk = estimateTokens(lines[i]);
|
|
490
|
+
if (tailTk + tk > tailBudget && tailLinesRev.length > 0) break;
|
|
491
|
+
tailLinesRev.push(lines[i]);
|
|
492
|
+
tailTk += tk;
|
|
493
|
+
tailStart = i + 1;
|
|
494
|
+
}
|
|
495
|
+
const tailLines = tailLinesRev.reverse();
|
|
496
|
+
const parts = [];
|
|
497
|
+
const ranges = [];
|
|
498
|
+
if (headLines.length > 0) {
|
|
499
|
+
parts.push(headLines.join('\n'));
|
|
500
|
+
ranges.push([1, headEnd]);
|
|
501
|
+
}
|
|
502
|
+
if (tailLines.length > 0 && tailStart > headEnd + 1) {
|
|
503
|
+
parts.push('<!-- ... lines ' + (headEnd + 1) + '-' + (tailStart - 1) + ' omitted to fit budget ... -->');
|
|
504
|
+
parts.push(tailLines.join('\n'));
|
|
505
|
+
ranges.push([tailStart, lines.length]);
|
|
506
|
+
} else if (tailLines.length > 0) {
|
|
507
|
+
parts.push(tailLines.join('\n'));
|
|
508
|
+
ranges.push([tailStart, lines.length]);
|
|
509
|
+
}
|
|
510
|
+
const windowedCode = parts.join('\n');
|
|
511
|
+
return {
|
|
512
|
+
windowedCode,
|
|
513
|
+
ranges: mergeLineRanges(ranges),
|
|
514
|
+
tokens: estimateTokens(windowedCode)
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function sliceHtmlSectionWindow(sectionContent, sectionStartLine, queryTerms, radius = 30, maxTokens = 1800) {
|
|
519
|
+
const lines = String(sectionContent || '').replace(/\r\n/g, '\n').split('\n');
|
|
520
|
+
if (lines.length <= 120) return null;
|
|
521
|
+
|
|
522
|
+
const matchedRel = [];
|
|
523
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
524
|
+
for (let i = 0; i < lines.length; i++) {
|
|
525
|
+
const lower = lines[i].toLowerCase();
|
|
526
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
527
|
+
matchedRel.push(i + 1);
|
|
528
|
+
if (matchedRel.length >= 4) break;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const rawAbsRanges = matchedRel.length > 0
|
|
534
|
+
? matchedRel.map((relLn) => [
|
|
535
|
+
sectionStartLine + Math.max(0, relLn - 1 - radius),
|
|
536
|
+
sectionStartLine + Math.min(lines.length - 1, relLn - 1 + radius)
|
|
537
|
+
])
|
|
538
|
+
: [[sectionStartLine, sectionStartLine + Math.min(lines.length - 1, 59)]];
|
|
539
|
+
|
|
540
|
+
const merged = mergeLineRanges(rawAbsRanges);
|
|
541
|
+
const parts = [];
|
|
542
|
+
const usedRanges = [];
|
|
543
|
+
let accTokens = 0;
|
|
544
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
545
|
+
const s = merged[idx][0];
|
|
546
|
+
const e = merged[idx][1];
|
|
547
|
+
const sliceLines = [];
|
|
548
|
+
let endWritten = s - 1;
|
|
549
|
+
for (let absLn = s; absLn <= e; absLn++) {
|
|
550
|
+
const candidate = lines[absLn - sectionStartLine];
|
|
551
|
+
if (candidate === undefined) break;
|
|
552
|
+
const tk = estimateTokens(candidate);
|
|
553
|
+
if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
|
|
554
|
+
sliceLines.push(candidate);
|
|
555
|
+
accTokens += tk;
|
|
556
|
+
endWritten = absLn;
|
|
557
|
+
}
|
|
558
|
+
if (sliceLines.length === 0) break;
|
|
559
|
+
if (idx > 0 && usedRanges.length > 0) {
|
|
560
|
+
const prevEnd = usedRanges[usedRanges.length - 1][1];
|
|
561
|
+
if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
|
|
562
|
+
}
|
|
563
|
+
parts.push(sliceLines.join('\n'));
|
|
564
|
+
usedRanges.push([s, endWritten]);
|
|
565
|
+
if (accTokens >= maxTokens) break;
|
|
566
|
+
}
|
|
567
|
+
const sectionEndLine = sectionStartLine + lines.length - 1;
|
|
568
|
+
if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < sectionEndLine) {
|
|
569
|
+
parts.push('<!-- ... lines ' + (usedRanges[usedRanges.length - 1][1] + 1) + '-' + sectionEndLine + ' omitted ... -->');
|
|
570
|
+
}
|
|
571
|
+
const windowedCode = parts.join('\n');
|
|
572
|
+
return {
|
|
573
|
+
windowedCode,
|
|
574
|
+
ranges: usedRanges.length > 0 ? usedRanges : [[sectionStartLine, Math.min(sectionEndLine, sectionStartLine + 40)]],
|
|
575
|
+
tokens: estimateTokens(windowedCode)
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
211
579
|
function findPythonSignatureEndIdx(lines, startIdx) {
|
|
212
580
|
let paren = 0, bracket = 0, brace = 0;
|
|
213
581
|
const maxScan = Math.min(lines.length - 1, startIdx + 25);
|
|
@@ -443,6 +811,133 @@ function extractPythonBlocks(lines, lineIdx) {
|
|
|
443
811
|
return { blocks: results, endIdx };
|
|
444
812
|
}
|
|
445
813
|
|
|
814
|
+
function extractTsClassMembers(lines, classStartIdx, classEndIdx, exported, maskFn, findBraceEndFn, findStmtEndFn) {
|
|
815
|
+
const members = [];
|
|
816
|
+
const classSlice = lines.slice(classStartIdx, classEndIdx + 1).join('\n');
|
|
817
|
+
const maskedClassLines = maskFn(classSlice).split('\n');
|
|
818
|
+
let depth = 0;
|
|
819
|
+
let opened = false;
|
|
820
|
+
let relIdx = 0;
|
|
821
|
+
|
|
822
|
+
while (relIdx < maskedClassLines.length) {
|
|
823
|
+
const absIdx = classStartIdx + relIdx;
|
|
824
|
+
const rawLine = lines[absIdx] || '';
|
|
825
|
+
const trimmed = rawLine.trim();
|
|
826
|
+
const mLine = maskedClassLines[relIdx] || '';
|
|
827
|
+
|
|
828
|
+
if (depth === 1 && trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*') && !trimmed.startsWith('*') && absIdx < classEndIdx) {
|
|
829
|
+
// 1) Standard class method: 'async text(...) { ... }'
|
|
830
|
+
const methodMatch = rawLine.match(/^\s{1,8}(?:(?:public|private|protected|async|static|override|abstract|get|set)\s+)*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(/);
|
|
831
|
+
if (methodMatch && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodMatch[1])) {
|
|
832
|
+
const mName = methodMatch[1];
|
|
833
|
+
let braceRelLine = relIdx;
|
|
834
|
+
while (braceRelLine < maskedClassLines.length && braceRelLine - relIdx < 8 && !maskedClassLines[braceRelLine].includes('{')) {
|
|
835
|
+
braceRelLine++;
|
|
836
|
+
}
|
|
837
|
+
if (braceRelLine < maskedClassLines.length && maskedClassLines[braceRelLine].includes('{')) {
|
|
838
|
+
const mEnd = Math.min(classEndIdx - 1, findBraceEndFn(lines, absIdx));
|
|
839
|
+
if (mEnd >= absIdx + 1 && mEnd < classEndIdx) {
|
|
840
|
+
const mFull = lines.slice(absIdx, mEnd + 1).join('\n');
|
|
841
|
+
const sigIdx = mFull.indexOf('{');
|
|
842
|
+
const mSkel = (sigIdx === -1 || mEnd - absIdx < 3)
|
|
843
|
+
? mFull
|
|
844
|
+
: mFull.slice(0, sigIdx).trim() + ' { /* ... ' + (mEnd - absIdx - 1) + ' lines folded */ }';
|
|
845
|
+
members.push({
|
|
846
|
+
name: mName,
|
|
847
|
+
kind: 'method',
|
|
848
|
+
exported,
|
|
849
|
+
startLine: absIdx + 1,
|
|
850
|
+
endLine: mEnd + 1,
|
|
851
|
+
full: mFull,
|
|
852
|
+
skeleton: mSkel
|
|
853
|
+
});
|
|
854
|
+
// Advance depth tracking past method lines cleanly
|
|
855
|
+
for (let k = relIdx; k <= mEnd - classStartIdx && k < maskedClassLines.length; k++) {
|
|
856
|
+
for (const ch of maskedClassLines[k]) {
|
|
857
|
+
if (ch === '{') { depth++; opened = true; }
|
|
858
|
+
else if (ch === '}') depth--;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
relIdx = (mEnd - classStartIdx) + 1;
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// 2) Class field arrow function / function expression: 'text: TextRespond = (...) => { ... }'
|
|
868
|
+
const fieldMatch = rawLine.match(/^\s{1,8}(?:(?:public|private|protected|readonly|static|override|abstract|declare|async)\s+)*([A-Za-z_$#][A-Za-z0-9_$]*)\s*[?!]?\s*(?::[^=]*)?(?:=|$)/);
|
|
869
|
+
if (fieldMatch && !['if', 'for', 'while', 'switch', 'catch', 'return'].includes(fieldMatch[1])) {
|
|
870
|
+
const fName = fieldMatch[1].replace(/^#/, '');
|
|
871
|
+
const lookSlice = maskedClassLines.slice(relIdx, Math.min(maskedClassLines.length, relIdx + 8)).join('\n');
|
|
872
|
+
const eqIdx = lookSlice.indexOf('=');
|
|
873
|
+
if (eqIdx !== -1) {
|
|
874
|
+
const afterEq = lookSlice.slice(eqIdx + 1);
|
|
875
|
+
const arrowRel = afterEq.indexOf('=>');
|
|
876
|
+
const fnMatch = afterEq.match(/\bfunction\b/);
|
|
877
|
+
const fnRel = fnMatch && fnMatch.index !== undefined ? fnMatch.index : -1;
|
|
878
|
+
const fnPosInLook = (arrowRel !== -1 && (fnRel === -1 || arrowRel < fnRel))
|
|
879
|
+
? eqIdx + 1 + arrowRel
|
|
880
|
+
: (fnRel !== -1 ? eqIdx + 1 + fnRel : -1);
|
|
881
|
+
if (fnPosInLook !== -1) {
|
|
882
|
+
const lineOffsetToFn = lookSlice.slice(0, fnPosInLook).split('\n').length - 1;
|
|
883
|
+
const fnLineAbs = absIdx + lineOffsetToFn;
|
|
884
|
+
let bodyBraceLineAbs = -1;
|
|
885
|
+
for (let scan = fnLineAbs; scan <= Math.min(classEndIdx - 1, fnLineAbs + 5); scan++) {
|
|
886
|
+
const sMask = maskedClassLines[scan - classStartIdx] || '';
|
|
887
|
+
if (sMask.includes('{')) { bodyBraceLineAbs = scan; break; }
|
|
888
|
+
if (sMask.trim().endsWith(';')) break;
|
|
889
|
+
}
|
|
890
|
+
const mEnd = bodyBraceLineAbs !== -1
|
|
891
|
+
? Math.min(classEndIdx - 1, findBraceEndFn(lines, bodyBraceLineAbs))
|
|
892
|
+
: Math.min(classEndIdx - 1, findStmtEndFn(lines, absIdx, 'ts'));
|
|
893
|
+
if (mEnd >= absIdx && mEnd < classEndIdx) {
|
|
894
|
+
const mFull = lines.slice(absIdx, mEnd + 1).join('\n');
|
|
895
|
+
let mSkel = mFull;
|
|
896
|
+
if (bodyBraceLineAbs !== -1 && mEnd - absIdx >= 3) {
|
|
897
|
+
const preBodyLines = lines.slice(absIdx, bodyBraceLineAbs + 1);
|
|
898
|
+
const lastPre = preBodyLines[preBodyLines.length - 1];
|
|
899
|
+
const lastMask = maskedClassLines[bodyBraceLineAbs - classStartIdx] || '';
|
|
900
|
+
const bCol = lastMask.indexOf('{');
|
|
901
|
+
if (bCol !== -1) {
|
|
902
|
+
preBodyLines[preBodyLines.length - 1] = lastPre.slice(0, bCol);
|
|
903
|
+
const sigText = preBodyLines.join('\n').trim();
|
|
904
|
+
const folded = Math.max(1, mEnd - bodyBraceLineAbs - 1);
|
|
905
|
+
mSkel = sigText + ' { /* ... ' + folded + ' lines folded */ }';
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
members.push({
|
|
909
|
+
name: fName,
|
|
910
|
+
kind: 'method',
|
|
911
|
+
exported,
|
|
912
|
+
startLine: absIdx + 1,
|
|
913
|
+
endLine: mEnd + 1,
|
|
914
|
+
full: mFull,
|
|
915
|
+
skeleton: mSkel
|
|
916
|
+
});
|
|
917
|
+
for (let k = relIdx; k <= mEnd - classStartIdx && k < maskedClassLines.length; k++) {
|
|
918
|
+
for (const ch of maskedClassLines[k]) {
|
|
919
|
+
if (ch === '{') { depth++; opened = true; }
|
|
920
|
+
else if (ch === '}') depth--;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
relIdx = (mEnd - classStartIdx) + 1;
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
for (const ch of mLine) {
|
|
932
|
+
if (ch === '{') { depth++; opened = true; }
|
|
933
|
+
else if (ch === '}') depth--;
|
|
934
|
+
}
|
|
935
|
+
if (opened && depth <= 0) break;
|
|
936
|
+
relIdx++;
|
|
937
|
+
}
|
|
938
|
+
return members;
|
|
939
|
+
}
|
|
940
|
+
|
|
446
941
|
function assembleContextSliceXml(opts) {
|
|
447
942
|
const {
|
|
448
943
|
blocks,
|
|
@@ -459,20 +954,172 @@ function assembleContextSliceXml(opts) {
|
|
|
459
954
|
version,
|
|
460
955
|
subPathTag,
|
|
461
956
|
includeParserAttr,
|
|
957
|
+
isSingleFile = false,
|
|
958
|
+
rawContentByFile = null,
|
|
462
959
|
controlWords,
|
|
463
960
|
maskFn
|
|
464
961
|
} = opts;
|
|
465
962
|
|
|
466
963
|
if (!String(rawQuery || '').trim()) {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
964
|
+
if (!isSingleFile) {
|
|
965
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
966
|
+
return [
|
|
967
|
+
'<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
|
|
968
|
+
' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
|
|
969
|
+
' <repository_file_tree>',
|
|
970
|
+
...treeLines,
|
|
971
|
+
' </repository_file_tree>',
|
|
972
|
+
'</context_slice>'
|
|
973
|
+
].join('\n');
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
// Direct Single-File Slice Within Budget (Empty Query on a Single-File Target)
|
|
977
|
+
const fp = (fileEntries[0] && fileEntries[0].relPath) || (blocks[0] && blocks[0].filePath) || '';
|
|
978
|
+
const totalLines = fileLineCounts.get(fp) || (rawContentByFile && rawContentByFile.get(fp) ? rawContentByFile.get(fp).replace(/\r\n/g, '\n').split('\n').length : 0);
|
|
979
|
+
const rawContent = rawContentByFile ? rawContentByFile.get(fp) : null;
|
|
980
|
+
const rawFileTk = rawContent !== null && rawContent !== undefined
|
|
981
|
+
? estimateTokens(rawContent)
|
|
982
|
+
: blocks.reduce((acc, b) => acc + (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full)), 0);
|
|
983
|
+
|
|
984
|
+
if (rawContent !== null && rawContent !== undefined && rawFileTk <= budget) {
|
|
985
|
+
const fileLabel = fp.split('/').pop() || fp || 'file';
|
|
986
|
+
const parserAttr = includeParserAttr && blocks[0] && blocks[0].parserMode ? ' parser="' + escapeXmlAttr(blocks[0].parserMode) + '"' : '';
|
|
987
|
+
return [
|
|
988
|
+
'<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + rawFileTk + '">',
|
|
989
|
+
' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + (totalLines > 0 ? '1-' + totalLines : '1') + '">',
|
|
990
|
+
' <focal symbol="' + escapeXmlAttr(fileLabel) + '" lines="1-' + Math.max(1, totalLines) + '"' + parserAttr + '>',
|
|
991
|
+
rawContent,
|
|
992
|
+
' </focal>',
|
|
993
|
+
' </file>',
|
|
994
|
+
'</context_slice>'
|
|
995
|
+
].join('\n');
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// Oversized single file: assemble priority sections + skeletons strictly within budget
|
|
999
|
+
let remainingSf = budget;
|
|
1000
|
+
const sfBlocks = blocks.map((b) => {
|
|
1001
|
+
const rTk = b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full);
|
|
1002
|
+
const sTk = b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton);
|
|
1003
|
+
return { ...b, rawTk: rTk, skelTk: sTk };
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
const sfPriority = (b) => {
|
|
1007
|
+
if (b.kind === 'function' || b.kind === 'method' || b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' && !String(b.name || '').startsWith('<style')) {
|
|
1008
|
+
if (String(b.name || '').startsWith('<')) return 1;
|
|
1009
|
+
return 0;
|
|
1010
|
+
}
|
|
1011
|
+
if (String(b.name || '').startsWith('<style')) return 3;
|
|
1012
|
+
if (b.kind === 'module') return 3;
|
|
1013
|
+
return 1;
|
|
1014
|
+
};
|
|
1015
|
+
|
|
1016
|
+
const sortedByPriority = sfBlocks
|
|
1017
|
+
.slice()
|
|
1018
|
+
.sort((a, b) => sfPriority(a) - sfPriority(b) || a.startLine - b.startLine);
|
|
1019
|
+
|
|
1020
|
+
const skipHdrSf = PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp);
|
|
1021
|
+
const hdrSf = !skipHdrSf ? fileHeaders.get(fp) : null;
|
|
1022
|
+
let showHdrSf = false;
|
|
1023
|
+
if (hdrSf && hdrSf.header) {
|
|
1024
|
+
const hdrCost = estimateTokens(hdrSf.header) + 12;
|
|
1025
|
+
if (hdrCost <= remainingSf) {
|
|
1026
|
+
remainingSf -= hdrCost;
|
|
1027
|
+
showHdrSf = true;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const pickedMap = new Map();
|
|
1032
|
+
const isNestedMethodCovered = (b) =>
|
|
1033
|
+
b.kind === 'method' &&
|
|
1034
|
+
sfBlocks.some((p) => p.kind === 'class' && p.startLine < b.startLine && p.endLine >= b.endLine && pickedMap.has(p.startLine + ':' + p.name) && pickedMap.get(p.startLine + ':' + p.name).tier === 'full');
|
|
1035
|
+
|
|
1036
|
+
// First reserve compact skeletons across all top sections/symbols
|
|
1037
|
+
for (const b of sortedByPriority) {
|
|
1038
|
+
const key = b.startLine + ':' + b.name;
|
|
1039
|
+
if (pickedMap.has(key)) continue;
|
|
1040
|
+
if (b.kind === 'module' && sfBlocks.length === 1) continue;
|
|
1041
|
+
if (b.skelTk <= remainingSf) {
|
|
1042
|
+
remainingSf -= b.skelTk;
|
|
1043
|
+
pickedMap.set(key, { tier: 'skeleton', item: b, win: null });
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// Upgrade highest-priority blocks to full while budget allows
|
|
1048
|
+
for (const b of sortedByPriority) {
|
|
1049
|
+
const key = b.startLine + ':' + b.name;
|
|
1050
|
+
if (isNestedMethodCovered(b)) {
|
|
1051
|
+
const cur = pickedMap.get(key);
|
|
1052
|
+
if (cur && cur.tier === 'skeleton') {
|
|
1053
|
+
remainingSf += b.skelTk;
|
|
1054
|
+
pickedMap.delete(key);
|
|
1055
|
+
}
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
const existing = pickedMap.get(key);
|
|
1059
|
+
if (existing) {
|
|
1060
|
+
const delta = Math.max(0, b.rawTk - b.skelTk);
|
|
1061
|
+
if (delta <= remainingSf) {
|
|
1062
|
+
remainingSf -= delta;
|
|
1063
|
+
existing.tier = 'full';
|
|
1064
|
+
}
|
|
1065
|
+
} else if (b.rawTk <= remainingSf && !(b.kind === 'module' && b.rawTk > budget)) {
|
|
1066
|
+
remainingSf -= b.rawTk;
|
|
1067
|
+
pickedMap.set(key, { tier: 'full', item: b, win: null });
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const selectedSf = Array.from(pickedMap.values()).sort((a, b) => a.item.startLine - b.item.startLine);
|
|
1072
|
+
// Fallback window if single giant module or no blocks fit in full
|
|
1073
|
+
if (selectedSf.length === 0 && (rawContent || (sfBlocks[0] && sfBlocks[0].full))) {
|
|
1074
|
+
const srcText = rawContent || sfBlocks[0].full;
|
|
1075
|
+
const win = sliceSingleFileWindow(srcText, Math.max(200, budget - 40));
|
|
1076
|
+
const usedSf = Math.min(budget, win.tokens);
|
|
1077
|
+
const shownStr = formatShownLines(win.ranges);
|
|
1078
|
+
const fileLabel = fp.split('/').pop() || fp || 'file';
|
|
1079
|
+
return [
|
|
1080
|
+
'<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + usedSf + '">',
|
|
1081
|
+
' <note>File exceeds ' + budget + ' token budget (' + rawFileTk + ' tokens total); returning windowed structural slice within budget.</note>',
|
|
1082
|
+
' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + shownStr + '">',
|
|
1083
|
+
' <focal symbol="' + escapeXmlAttr(fileLabel) + '" lines="' + shownStr + '">',
|
|
1084
|
+
win.windowedCode,
|
|
1085
|
+
' </focal>',
|
|
1086
|
+
' </file>',
|
|
1087
|
+
'</context_slice>'
|
|
1088
|
+
].join('\n');
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const shownRangesSf = [];
|
|
1092
|
+
if (showHdrSf) shownRangesSf.push([1, hdrSf.endLine]);
|
|
1093
|
+
for (const ent of selectedSf) {
|
|
1094
|
+
shownRangesSf.push([ent.item.startLine, ent.item.endLine]);
|
|
1095
|
+
}
|
|
1096
|
+
const usedSf = Math.max(0, budget - remainingSf);
|
|
1097
|
+
const outSf = [
|
|
1098
|
+
'<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + usedSf + '">',
|
|
1099
|
+
' <note>File exceeds ' + budget + ' token budget (' + rawFileTk + ' tokens total); returning prioritized sections/symbols and folded skeletons within budget.</note>',
|
|
1100
|
+
' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRangesSf) + '">'
|
|
1101
|
+
];
|
|
1102
|
+
if (showHdrSf) {
|
|
1103
|
+
outSf.push(' <file_header lines="1-' + hdrSf.endLine + '">');
|
|
1104
|
+
outSf.push(hdrSf.header);
|
|
1105
|
+
outSf.push(' </file_header>');
|
|
1106
|
+
}
|
|
1107
|
+
for (const ent of selectedSf) {
|
|
1108
|
+
const it = ent.item;
|
|
1109
|
+
if (ent.tier === 'full') {
|
|
1110
|
+
const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
|
|
1111
|
+
outSf.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + it.startLine + '-' + it.endLine + '"' + parserAttr + '>');
|
|
1112
|
+
outSf.push(it.full);
|
|
1113
|
+
outSf.push(' </focal>');
|
|
1114
|
+
} else {
|
|
1115
|
+
outSf.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + it.startLine + '-' + it.endLine + '">');
|
|
1116
|
+
outSf.push(it.skeleton);
|
|
1117
|
+
outSf.push(' </skeleton>');
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
outSf.push(' </file>');
|
|
1121
|
+
outSf.push('</context_slice>');
|
|
1122
|
+
return outSf.join('\n');
|
|
476
1123
|
}
|
|
477
1124
|
|
|
478
1125
|
const roleIntents = getQueryRoleIntents(rawQuery);
|
|
@@ -483,13 +1130,18 @@ function assembleContextSliceXml(opts) {
|
|
|
483
1130
|
const lineCount = Math.max(1, b.endLine - b.startLine + 1);
|
|
484
1131
|
const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
|
|
485
1132
|
const isDocExt = DOC_EXT_RE.test(rel);
|
|
1133
|
+
const isHtmlSection = HTML_EXT_RE.test(rel) && String(b.name || '').startsWith('<');
|
|
486
1134
|
let win = null;
|
|
487
1135
|
if (b.kind === 'module') {
|
|
488
1136
|
if (isConfigFile && lineCount > 200) {
|
|
489
1137
|
win = slicePlainTextConfigWindow(b.full, terms);
|
|
490
1138
|
} else if (isDocExt && lineCount > 45) {
|
|
491
1139
|
win = sliceDocWindow(b.full, terms, 16, 480);
|
|
1140
|
+
} else if (isHtmlSection && lineCount > 120) {
|
|
1141
|
+
win = sliceHtmlSectionWindow(b.full, b.startLine, terms, 30, Math.min(2400, Math.max(400, Math.floor(budget * 0.4))));
|
|
492
1142
|
}
|
|
1143
|
+
} else if (isHtmlSection && lineCount > 120) {
|
|
1144
|
+
win = sliceHtmlSectionWindow(b.full, b.startLine, terms, 30, Math.min(2400, Math.max(400, Math.floor(budget * 0.4))));
|
|
493
1145
|
}
|
|
494
1146
|
if (win) configWindowByKey.set(key, win);
|
|
495
1147
|
const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
|
|
@@ -554,7 +1206,7 @@ function assembleContextSliceXml(opts) {
|
|
|
554
1206
|
else if (b.role === 'source') score *= 1.25;
|
|
555
1207
|
}
|
|
556
1208
|
|
|
557
|
-
return { ...b, score };
|
|
1209
|
+
return { ...b, score, matchedTerms };
|
|
558
1210
|
}).sort((a, b) => b.score - a.score);
|
|
559
1211
|
|
|
560
1212
|
// Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
|
|
@@ -576,6 +1228,12 @@ function assembleContextSliceXml(opts) {
|
|
|
576
1228
|
}
|
|
577
1229
|
}
|
|
578
1230
|
|
|
1231
|
+
const isChildMethodOf = (child, parent) =>
|
|
1232
|
+
child.filePath === parent.filePath &&
|
|
1233
|
+
child.kind === 'method' &&
|
|
1234
|
+
(child.name.startsWith(parent.name + '.') ||
|
|
1235
|
+
(child.startLine > parent.startLine && child.endLine <= parent.endLine));
|
|
1236
|
+
|
|
579
1237
|
const callAdj = Array.from({ length: scored.length }, () => new Set());
|
|
580
1238
|
const definedNames = Array.from(symbolMap.keys());
|
|
581
1239
|
for (let i = 0; i < scored.length; i++) {
|
|
@@ -591,10 +1249,7 @@ function assembleContextSliceXml(opts) {
|
|
|
591
1249
|
if (re.test(maskedCaller)) {
|
|
592
1250
|
for (const t of (symbolMap.get(sym) || [])) {
|
|
593
1251
|
const target = scored[t];
|
|
594
|
-
if (caller
|
|
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;
|
|
1252
|
+
if (isChildMethodOf(target, caller) || isChildMethodOf(caller, target)) continue;
|
|
598
1253
|
callAdj[i].add(t);
|
|
599
1254
|
callAdj[t].add(i);
|
|
600
1255
|
}
|
|
@@ -625,7 +1280,7 @@ function assembleContextSliceXml(opts) {
|
|
|
625
1280
|
const childIndices = [];
|
|
626
1281
|
for (let ci = 0; ci < scored.length; ci++) {
|
|
627
1282
|
const c = scored[ci];
|
|
628
|
-
if (c
|
|
1283
|
+
if (isChildMethodOf(c, b)) {
|
|
629
1284
|
const cShort = c.name.split('.').pop().toLowerCase();
|
|
630
1285
|
const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
|
|
631
1286
|
if (explicitHit || c.score >= b.score * 0.55) {
|
|
@@ -635,7 +1290,7 @@ function assembleContextSliceXml(opts) {
|
|
|
635
1290
|
}
|
|
636
1291
|
if (childIndices.length > 0) {
|
|
637
1292
|
promotedParentClassSet.add(idx);
|
|
638
|
-
for (const ci of childIndices.slice(0,
|
|
1293
|
+
for (const ci of childIndices.slice(0, 4)) candidateChosen.add(ci);
|
|
639
1294
|
continue;
|
|
640
1295
|
}
|
|
641
1296
|
}
|
|
@@ -644,10 +1299,9 @@ function assembleContextSliceXml(opts) {
|
|
|
644
1299
|
for (const idx of candidateChosen) {
|
|
645
1300
|
const b = scored[idx];
|
|
646
1301
|
if (b.kind === 'method') {
|
|
647
|
-
const clsName = b.name.split('.')[0];
|
|
648
1302
|
const hasFullParent = [...candidateChosen].some((pIdx) => {
|
|
649
1303
|
const p = scored[pIdx];
|
|
650
|
-
return p && p.kind === 'class' &&
|
|
1304
|
+
return Boolean(p && p.kind === 'class' && isChildMethodOf(b, p));
|
|
651
1305
|
});
|
|
652
1306
|
if (hasFullParent) continue;
|
|
653
1307
|
}
|
|
@@ -676,7 +1330,39 @@ function assembleContextSliceXml(opts) {
|
|
|
676
1330
|
}
|
|
677
1331
|
}
|
|
678
1332
|
|
|
679
|
-
|
|
1333
|
+
const fileHeaderTokenCache = new Map();
|
|
1334
|
+
for (const [fp, hdr] of fileHeaders.entries()) {
|
|
1335
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
|
|
1336
|
+
if (hdr && hdr.header) fileHeaderTokenCache.set(fp, estimateTokens(hdr.header) + 12);
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
const directCoreFiles = new Set(focalFiles);
|
|
1340
|
+
for (const pid of promotedParentClassSet) directCoreFiles.add(scored[pid].filePath);
|
|
1341
|
+
const minDirectTerms = Math.min(2, Math.max(1, terms.length));
|
|
1342
|
+
for (let i = 0; i < scored.length; i++) {
|
|
1343
|
+
const b = scored[i];
|
|
1344
|
+
if (b.role !== 'source') continue;
|
|
1345
|
+
const h = hopDistances.get(i);
|
|
1346
|
+
const isDirectCallable = h === 1 && (b.kind === 'function' || b.kind === 'method' || b.kind === 'class');
|
|
1347
|
+
if ((terms.length >= 2 && b.matchedTerms >= minDirectTerms) || isDirectCallable) {
|
|
1348
|
+
directCoreFiles.add(b.filePath);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
const isPeripheralIdx = (idx) => {
|
|
1353
|
+
if (focalSet.has(idx) || promotedParentClassSet.has(idx)) return false;
|
|
1354
|
+
const b = scored[idx];
|
|
1355
|
+
if (focalFiles.has(b.filePath)) return false;
|
|
1356
|
+
const h = hopDistances.get(idx);
|
|
1357
|
+
if (h !== undefined && h >= 2) return true;
|
|
1358
|
+
if (!directCoreFiles.has(b.filePath)) return true;
|
|
1359
|
+
if ((b.kind === 'interface' || b.kind === 'type' || b.kind === 'const') && b.matchedTerms <= 1 && h === undefined) {
|
|
1360
|
+
return true;
|
|
1361
|
+
}
|
|
1362
|
+
return false;
|
|
1363
|
+
};
|
|
1364
|
+
|
|
1365
|
+
// Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, source -> non-peripheral -> matchedTerms -> hop -> score
|
|
680
1366
|
const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
|
|
681
1367
|
const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
|
|
682
1368
|
const focA = focalSet.has(a) ? 0 : 1;
|
|
@@ -688,6 +1374,10 @@ function assembleContextSliceXml(opts) {
|
|
|
688
1374
|
const rrA = roleRank(scored[a].role);
|
|
689
1375
|
const rrB = roleRank(scored[b].role);
|
|
690
1376
|
if (rrA !== rrB) return rrA - rrB;
|
|
1377
|
+
const perA = isPeripheralIdx(a) ? 1 : 0;
|
|
1378
|
+
const perB = isPeripheralIdx(b) ? 1 : 0;
|
|
1379
|
+
if (perA !== perB) return perA - perB;
|
|
1380
|
+
if (scored[a].matchedTerms !== scored[b].matchedTerms) return scored[b].matchedTerms - scored[a].matchedTerms;
|
|
691
1381
|
const hopA = hopDistances.get(a) ?? 99;
|
|
692
1382
|
const hopB = hopDistances.get(b) ?? 99;
|
|
693
1383
|
if (hopA !== hopB) return hopA - hopB;
|
|
@@ -697,14 +1387,17 @@ function assembleContextSliceXml(opts) {
|
|
|
697
1387
|
let remaining = budget;
|
|
698
1388
|
let docBudgetUsed = 0;
|
|
699
1389
|
let testBudgetUsed = 0;
|
|
1390
|
+
let peripheralBudgetUsed = 0;
|
|
700
1391
|
const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
|
|
701
1392
|
const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
|
|
1393
|
+
const peripheralBudgetCap = budget <= 16384 ? Math.floor(budget * 0.25) : Math.floor(budget * 0.3);
|
|
702
1394
|
const dirBudgetUsed = {};
|
|
703
1395
|
const maxDirBudget = budget * 0.72;
|
|
704
1396
|
|
|
705
1397
|
const includedIds = new Set();
|
|
706
1398
|
const includedFiles = [];
|
|
707
1399
|
const includedFilesSet = new Set();
|
|
1400
|
+
const headerChargedFiles = new Set();
|
|
708
1401
|
const fullStart1EndLine = new Map();
|
|
709
1402
|
const coveredRangesByFile = new Map();
|
|
710
1403
|
const partialFiles = new Set();
|
|
@@ -713,6 +1406,11 @@ function assembleContextSliceXml(opts) {
|
|
|
713
1406
|
const skelCandidates = [];
|
|
714
1407
|
const candidateItems = [];
|
|
715
1408
|
|
|
1409
|
+
const getHeaderReserve = (item) => {
|
|
1410
|
+
if (headerChargedFiles.has(item.filePath)) return 0;
|
|
1411
|
+
if (item.kind === 'module' && item.startLine === 1) return 0;
|
|
1412
|
+
return fileHeaderTokenCache.get(item.filePath) || 0;
|
|
1413
|
+
};
|
|
716
1414
|
const addCoveredRange = (fp, s, e) => {
|
|
717
1415
|
if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
|
|
718
1416
|
coveredRangesByFile.get(fp).push([s, e]);
|
|
@@ -738,9 +1436,8 @@ function assembleContextSliceXml(opts) {
|
|
|
738
1436
|
for (const idx of allocOrder) {
|
|
739
1437
|
const item = scored[idx];
|
|
740
1438
|
if (item.kind === 'method') {
|
|
741
|
-
const
|
|
742
|
-
|
|
743
|
-
if (fullSet && fullSet.has(clsName)) continue;
|
|
1439
|
+
const fullClasses = fullParentClassesByFile.get(item.filePath);
|
|
1440
|
+
if (fullClasses && fullClasses.some((cls) => isChildMethodOf(item, cls))) continue;
|
|
744
1441
|
}
|
|
745
1442
|
|
|
746
1443
|
const topDir = item.filePath.split('/')[0] || 'root';
|
|
@@ -748,17 +1445,23 @@ function assembleContextSliceXml(opts) {
|
|
|
748
1445
|
const hop = hopDistances.get(idx);
|
|
749
1446
|
const isFocal = focalSet.has(idx);
|
|
750
1447
|
const isPromotedParent = promotedParentClassSet.has(idx);
|
|
1448
|
+
const peripheral = isPeripheralIdx(idx);
|
|
751
1449
|
const key = item.filePath + ':' + item.startLine;
|
|
752
1450
|
const win = configWindowByKey.get(key);
|
|
1451
|
+
const hdrCost = getHeaderReserve(item);
|
|
753
1452
|
|
|
754
1453
|
if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
|
|
755
1454
|
remaining = Math.max(0, remaining - item.rawTk);
|
|
1455
|
+
if (hdrCost > 0 && hdrCost <= remaining) {
|
|
1456
|
+
remaining -= hdrCost;
|
|
1457
|
+
headerChargedFiles.add(item.filePath);
|
|
1458
|
+
}
|
|
756
1459
|
dirBudgetUsed[topDir] = curDir + item.rawTk;
|
|
757
1460
|
addRoleBudget(item.role, item.rawTk);
|
|
758
1461
|
includedIds.add(key);
|
|
759
1462
|
if (item.kind === 'class') {
|
|
760
|
-
if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath,
|
|
761
|
-
fullParentClassesByFile.get(item.filePath).
|
|
1463
|
+
if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, []);
|
|
1464
|
+
fullParentClassesByFile.get(item.filePath).push(item);
|
|
762
1465
|
}
|
|
763
1466
|
if (win) {
|
|
764
1467
|
for (const r of win.ranges) {
|
|
@@ -772,32 +1475,47 @@ function assembleContextSliceXml(opts) {
|
|
|
772
1475
|
addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
|
|
773
1476
|
} else if (isPromotedParent && item.skelTk <= remaining) {
|
|
774
1477
|
remaining -= item.skelTk;
|
|
1478
|
+
if (hdrCost > 0 && hdrCost <= remaining) {
|
|
1479
|
+
remaining -= hdrCost;
|
|
1480
|
+
headerChargedFiles.add(item.filePath);
|
|
1481
|
+
}
|
|
775
1482
|
dirBudgetUsed[topDir] = curDir + item.skelTk;
|
|
776
1483
|
includedIds.add(key);
|
|
777
1484
|
partialFiles.add(item.filePath);
|
|
778
1485
|
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
|
|
779
|
-
} else
|
|
780
|
-
const
|
|
781
|
-
const
|
|
782
|
-
if (
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
1486
|
+
} else {
|
|
1487
|
+
const totalSkelCost = item.skelTk + hdrCost;
|
|
1488
|
+
const fitsPeripheral = !peripheral || (peripheralBudgetUsed + totalSkelCost <= peripheralBudgetCap);
|
|
1489
|
+
if (
|
|
1490
|
+
fitsPeripheral &&
|
|
1491
|
+
totalSkelCost <= remaining &&
|
|
1492
|
+
(curDir + item.skelTk <= maxDirBudget || item.role === 'source') &&
|
|
1493
|
+
canUseRoleBudget(item.role, item.skelTk)
|
|
1494
|
+
) {
|
|
1495
|
+
const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
|
|
1496
|
+
const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
|
|
1497
|
+
if (linked) {
|
|
1498
|
+
remaining -= totalSkelCost;
|
|
1499
|
+
if (hdrCost > 0) headerChargedFiles.add(item.filePath);
|
|
1500
|
+
if (peripheral) peripheralBudgetUsed += totalSkelCost;
|
|
1501
|
+
dirBudgetUsed[topDir] = curDir + totalSkelCost;
|
|
1502
|
+
addRoleBudget(item.role, item.skelTk);
|
|
1503
|
+
includedIds.add(key);
|
|
1504
|
+
partialFiles.add(item.filePath);
|
|
1505
|
+
if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
1506
|
+
if (autoExpand && item.role === 'source' && !isPromotedParent && !peripheral) {
|
|
1507
|
+
skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
|
|
1508
|
+
} else {
|
|
1509
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
|
|
1510
|
+
}
|
|
791
1511
|
} else {
|
|
792
|
-
|
|
1512
|
+
partialFiles.add(item.filePath);
|
|
1513
|
+
candidateItems.push(item);
|
|
793
1514
|
}
|
|
794
1515
|
} else {
|
|
795
1516
|
partialFiles.add(item.filePath);
|
|
796
1517
|
candidateItems.push(item);
|
|
797
1518
|
}
|
|
798
|
-
} else {
|
|
799
|
-
partialFiles.add(item.filePath);
|
|
800
|
-
candidateItems.push(item);
|
|
801
1519
|
}
|
|
802
1520
|
}
|
|
803
1521
|
|
|
@@ -806,8 +1524,8 @@ function assembleContextSliceXml(opts) {
|
|
|
806
1524
|
for (const cand of skelCandidates) {
|
|
807
1525
|
const it = cand.item;
|
|
808
1526
|
const delta = Math.max(0, it.rawTk - it.skelTk);
|
|
809
|
-
const isComplexCluster = (cand.hop
|
|
810
|
-
const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
|
|
1527
|
+
const isComplexCluster = (cand.hop === 1 || it.matchedTerms >= minDirectTerms || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
|
|
1528
|
+
const canExpandClass = it.kind !== 'class' || (!it.filePath.endsWith('.py') && it.lineCount <= 80);
|
|
811
1529
|
if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
|
|
812
1530
|
remaining -= delta;
|
|
813
1531
|
autoExpandedNames.push(it.name);
|
|
@@ -829,20 +1547,29 @@ function assembleContextSliceXml(opts) {
|
|
|
829
1547
|
|
|
830
1548
|
if (includedFiles.length === 0) {
|
|
831
1549
|
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
832
|
-
|
|
1550
|
+
const outZero = [
|
|
833
1551
|
'<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
|
|
834
1552
|
' <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
1553
|
' <repository_file_tree>',
|
|
836
1554
|
...treeLines,
|
|
837
|
-
' </repository_file_tree>'
|
|
838
|
-
|
|
839
|
-
|
|
1555
|
+
' </repository_file_tree>'
|
|
1556
|
+
];
|
|
1557
|
+
if (isSingleFile && blocks.length > 0) {
|
|
1558
|
+
outZero.push(' <file_symbol_outline>');
|
|
1559
|
+
const sortedSym = blocks.slice().sort((a, b) => a.startLine - b.startLine).slice(0, 45);
|
|
1560
|
+
for (const sb of sortedSym) {
|
|
1561
|
+
outZero.push(' line ' + sb.startLine + '-' + sb.endLine + ': ' + sb.kind + ' ' + sb.name);
|
|
1562
|
+
}
|
|
1563
|
+
outZero.push(' </file_symbol_outline>');
|
|
1564
|
+
}
|
|
1565
|
+
outZero.push('</context_slice>');
|
|
1566
|
+
return outZero.join('\n');
|
|
840
1567
|
}
|
|
841
1568
|
|
|
842
1569
|
const headerByFile = new Map();
|
|
843
1570
|
const headerEndByFile = new Map();
|
|
844
1571
|
for (const fp of includedFiles) {
|
|
845
|
-
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
1572
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
|
|
846
1573
|
const entries = selectedByFile.get(fp) || [];
|
|
847
1574
|
const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
|
|
848
1575
|
if (hasStart1ModuleSkel) continue;
|
|
@@ -855,7 +1582,8 @@ function assembleContextSliceXml(opts) {
|
|
|
855
1582
|
|
|
856
1583
|
const footerByFile = new Map();
|
|
857
1584
|
for (const fp of includedFiles) {
|
|
858
|
-
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
|
|
1585
|
+
if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
|
|
1586
|
+
if (!directCoreFiles.has(fp)) continue;
|
|
859
1587
|
const ftr = fileFooters.get(fp);
|
|
860
1588
|
if (!ftr) continue;
|
|
861
1589
|
const ranges = coveredRangesByFile.get(fp) || [];
|
|
@@ -882,9 +1610,18 @@ function assembleContextSliceXml(opts) {
|
|
|
882
1610
|
|
|
883
1611
|
for (const fp of includedFiles) {
|
|
884
1612
|
const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
|
|
885
|
-
const
|
|
1613
|
+
const fullClasses = rawEntries.filter((e) => e.tier === 'full' && e.item.kind === 'class').map((e) => e.item);
|
|
1614
|
+
const structuralPyClasses = /\.pyw?$/i.test(fp)
|
|
1615
|
+
? rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item)
|
|
1616
|
+
: [];
|
|
886
1617
|
const entries = rawEntries.filter(
|
|
887
|
-
(e) =>
|
|
1618
|
+
(e) =>
|
|
1619
|
+
!(
|
|
1620
|
+
e.tier === 'skeleton' &&
|
|
1621
|
+
e.item.kind === 'method' &&
|
|
1622
|
+
(fullClasses.some((cls) => isChildMethodOf(e.item, cls)) ||
|
|
1623
|
+
structuralPyClasses.some((cls) => isChildMethodOf(e.item, cls)))
|
|
1624
|
+
),
|
|
888
1625
|
);
|
|
889
1626
|
const fullEntries = entries.filter((e) => e.tier === 'full');
|
|
890
1627
|
const hdr = headerByFile.get(fp);
|
|
@@ -918,7 +1655,7 @@ function assembleContextSliceXml(opts) {
|
|
|
918
1655
|
let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
|
|
919
1656
|
if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
|
|
920
1657
|
const expandedChildRanges = fullEntries
|
|
921
|
-
.filter((fe) => fe.item
|
|
1658
|
+
.filter((fe) => isChildMethodOf(fe.item, it))
|
|
922
1659
|
.map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
|
|
923
1660
|
if (expandedChildRanges.length > 0) {
|
|
924
1661
|
skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
|
|
@@ -1342,29 +2079,67 @@ function expandQueryTerms(query) {
|
|
|
1342
2079
|
|
|
1343
2080
|
const args = process.argv.slice(2);
|
|
1344
2081
|
if (args.includes('--version') || args.includes('-v')) {
|
|
1345
|
-
process.stdout.write('ctxslice v0.4.
|
|
2082
|
+
process.stdout.write('ctxslice v0.4.3\n');
|
|
1346
2083
|
process.exit(0);
|
|
1347
2084
|
}
|
|
1348
2085
|
if (args.includes('--help') || args.includes('-h')) {
|
|
1349
2086
|
process.stdout.write(
|
|
1350
|
-
'ContextSlice CLI v0.4.
|
|
1351
|
-
'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
|
|
1352
|
-
'Options:\n --root <dir>
|
|
1353
|
-
' --
|
|
1354
|
-
'
|
|
1355
|
-
' -
|
|
2087
|
+
'ContextSlice CLI v0.4.3 — Zero-Config Multi-Language Structural Code Slicer\n\n' +
|
|
2088
|
+
'Usage:\n ctxslice "<query>" [--root <dir|file>] [--sub <path>] [--budget <tokens>]\n\n' +
|
|
2089
|
+
'Options:\n --root <dir|file> Target repository directory or single file path (default: current directory)\n' +
|
|
2090
|
+
' --sub <path> Optional sub-directory or single file path relative to --root\n' +
|
|
2091
|
+
' --budget <num> Max token budget (default: 32768)\n' +
|
|
2092
|
+
' -v, --version Show version\n' +
|
|
2093
|
+
' -h, --help Show help\n'
|
|
1356
2094
|
);
|
|
1357
2095
|
process.exit(0);
|
|
1358
2096
|
}
|
|
1359
2097
|
const rootFlag = args.indexOf('--root');
|
|
1360
|
-
const
|
|
2098
|
+
const rawRootArg = rootFlag !== -1 && args[rootFlag + 1] ? path.resolve(args[rootFlag + 1]) : process.cwd();
|
|
2099
|
+
const subFlag = args.indexOf('--sub') !== -1 ? args.indexOf('--sub') : args.indexOf('--sub-path');
|
|
2100
|
+
const subPathArg = subFlag !== -1 && args[subFlag + 1] ? args[subFlag + 1] : '';
|
|
1361
2101
|
const budgetFlag = args.indexOf('--budget');
|
|
1362
2102
|
const budget = budgetFlag !== -1 ? Number(args[budgetFlag + 1]) : 32768;
|
|
1363
2103
|
const skipIdx = new Set();
|
|
1364
2104
|
if (rootFlag !== -1) { skipIdx.add(rootFlag); skipIdx.add(rootFlag + 1); }
|
|
2105
|
+
if (subFlag !== -1) { skipIdx.add(subFlag); skipIdx.add(subFlag + 1); }
|
|
1365
2106
|
if (budgetFlag !== -1) { skipIdx.add(budgetFlag); skipIdx.add(budgetFlag + 1); }
|
|
1366
2107
|
const queryArg = args.find((a, idx) => !skipIdx.has(idx) && !a.startsWith('--'));
|
|
1367
2108
|
const query = queryArg !== undefined ? queryArg : '';
|
|
2109
|
+
|
|
2110
|
+
if (!fs.existsSync(rawRootArg)) {
|
|
2111
|
+
process.stdout.write('Error: root path not found: ' + rawRootArg + '\n');
|
|
2112
|
+
process.exit(1);
|
|
2113
|
+
}
|
|
2114
|
+
const rootStat = fs.statSync(rawRootArg);
|
|
2115
|
+
let targetRoot = rawRootArg;
|
|
2116
|
+
let scanRoot = rawRootArg;
|
|
2117
|
+
let isSingleFile = rootStat.isFile();
|
|
2118
|
+
if (isSingleFile) {
|
|
2119
|
+
if (subPathArg && subPathArg.trim()) {
|
|
2120
|
+
const cleanSub = subPathArg.trim().replace(/\\/g, '/');
|
|
2121
|
+
if (cleanSub !== path.basename(rawRootArg) && cleanSub !== '.') {
|
|
2122
|
+
process.stdout.write('Error: --sub "' + subPathArg + '" cannot be used when --root is already a single file\n');
|
|
2123
|
+
process.exit(1);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
targetRoot = path.dirname(rawRootArg);
|
|
2127
|
+
scanRoot = rawRootArg;
|
|
2128
|
+
} else if (subPathArg && subPathArg.trim()) {
|
|
2129
|
+
scanRoot = path.resolve(targetRoot, subPathArg);
|
|
2130
|
+
const relCheck = path.relative(targetRoot, scanRoot);
|
|
2131
|
+
if (relCheck.startsWith('..') || path.isAbsolute(relCheck)) {
|
|
2132
|
+
process.stdout.write('Error: Security Error: --sub "' + subPathArg + '" escapes --root sandbox\n');
|
|
2133
|
+
process.exit(1);
|
|
2134
|
+
}
|
|
2135
|
+
if (!fs.existsSync(scanRoot)) {
|
|
2136
|
+
process.stdout.write('Error: --sub path not found: ' + scanRoot + '\n');
|
|
2137
|
+
process.exit(1);
|
|
2138
|
+
}
|
|
2139
|
+
isSingleFile = fs.statSync(scanRoot).isFile();
|
|
2140
|
+
}
|
|
2141
|
+
const subPathTag = subPathArg && subPathArg.trim() ? ' subPath="' + escapeXmlAttr(subPathArg.trim()) + '"' : '';
|
|
2142
|
+
|
|
1368
2143
|
const IGNORE = new Set([
|
|
1369
2144
|
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
1370
2145
|
'venv', '.venv', '__pycache__', 'vendor', 'target', '.build', '.swiftpm', 'DerivedData', 'Pods', 'bin', 'obj'
|
|
@@ -1400,6 +2175,13 @@ function isBinaryBuffer(buf) {
|
|
|
1400
2175
|
|
|
1401
2176
|
function walk(dir, acc = []) {
|
|
1402
2177
|
if (!fs.existsSync(dir)) return acc;
|
|
2178
|
+
let st;
|
|
2179
|
+
try { st = fs.statSync(dir); } catch { return acc; }
|
|
2180
|
+
if (st.isFile()) {
|
|
2181
|
+
if (isTextCandidate(dir)) acc.push(dir);
|
|
2182
|
+
return acc;
|
|
2183
|
+
}
|
|
2184
|
+
if (!st.isDirectory()) return acc;
|
|
1403
2185
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1404
2186
|
if (IGNORE.has(entry.name)) continue;
|
|
1405
2187
|
const full = path.join(dir, entry.name);
|
|
@@ -1439,6 +2221,10 @@ function findBraceEnd(lines, startIdx) {
|
|
|
1439
2221
|
|
|
1440
2222
|
function extractBlocks(code, ext, fileName) {
|
|
1441
2223
|
const e = (ext || '').toLowerCase();
|
|
2224
|
+
if (e === '.html' || e === '.htm' || e === '.xhtml') {
|
|
2225
|
+
const htmlBlocks = extractHtmlBlocks(code, fileName, (innerCode) => extractBlocks(innerCode, '.js', fileName));
|
|
2226
|
+
if (htmlBlocks && htmlBlocks.length > 0) return htmlBlocks;
|
|
2227
|
+
}
|
|
1442
2228
|
const lines = code.split('\n');
|
|
1443
2229
|
const blocks = [];
|
|
1444
2230
|
|
|
@@ -1545,8 +2331,15 @@ function extractBlocks(code, ext, fileName) {
|
|
|
1545
2331
|
const skeleton = (kind === 'interface' || kind === 'type' || isShortConst || sigIdx === -1 || end - i < 4)
|
|
1546
2332
|
? full
|
|
1547
2333
|
: full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
|
|
1548
|
-
|
|
1549
|
-
|
|
2334
|
+
const isExported = line.startsWith('export ');
|
|
2335
|
+
blocks.push({ name, kind, exported: isExported, startLine: i + 1, endLine: end + 1, full, skeleton });
|
|
2336
|
+
if (kind === 'class' && /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(e)) {
|
|
2337
|
+
const classMembers = extractTsClassMembers(lines, i, end, isExported, maskCommentsAndStrings, findBraceEnd, findStatementEndLine);
|
|
2338
|
+
if (classMembers.length > 0) blocks.push(...classMembers);
|
|
2339
|
+
i = end;
|
|
2340
|
+
} else if (kind !== 'class' && kind !== 'module') {
|
|
2341
|
+
i = end;
|
|
2342
|
+
}
|
|
1550
2343
|
}
|
|
1551
2344
|
}
|
|
1552
2345
|
|
|
@@ -1920,10 +2713,11 @@ function extractFileFooter(content, tailLines = 20) {
|
|
|
1920
2713
|
}
|
|
1921
2714
|
|
|
1922
2715
|
|
|
1923
|
-
const files = walk(
|
|
2716
|
+
const files = walk(scanRoot);
|
|
1924
2717
|
const fileLineCounts = new Map();
|
|
1925
2718
|
const fileEntries = [];
|
|
1926
2719
|
const textRecords = [];
|
|
2720
|
+
const rawContentByFile = isSingleFile ? new Map() : null;
|
|
1927
2721
|
for (const filePath of files) {
|
|
1928
2722
|
try {
|
|
1929
2723
|
const buf = fs.readFileSync(filePath);
|
|
@@ -1934,17 +2728,23 @@ for (const filePath of files) {
|
|
|
1934
2728
|
fileLineCounts.set(relPath, lineCount);
|
|
1935
2729
|
fileEntries.push({ relPath, lineCount });
|
|
1936
2730
|
textRecords.push({ filePath, relPath, content });
|
|
2731
|
+
if (rawContentByFile) rawContentByFile.set(relPath, content);
|
|
1937
2732
|
} catch {}
|
|
1938
2733
|
}
|
|
1939
2734
|
|
|
2735
|
+
if (isSingleFile && fileEntries.length === 0) {
|
|
2736
|
+
process.stdout.write('Error: Target file is binary, a secret (.env/.pem/.key), or a skipped lockfile/minified asset: ' + scanRoot + '\n');
|
|
2737
|
+
process.exit(1);
|
|
2738
|
+
}
|
|
2739
|
+
|
|
1940
2740
|
const terms = expandQueryTerms(query);
|
|
1941
2741
|
const allRawBlocks = [];
|
|
1942
2742
|
const fileHeaders = new Map();
|
|
1943
2743
|
const fileFooters = new Map();
|
|
1944
2744
|
|
|
1945
|
-
if (query.trim()) {
|
|
2745
|
+
if (query.trim() || isSingleFile) {
|
|
1946
2746
|
for (const rec of textRecords) {
|
|
1947
|
-
const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rec.relPath) || DOC_EXT_RE.test(rec.relPath);
|
|
2747
|
+
const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rec.relPath) || DOC_EXT_RE.test(rec.relPath) || HTML_EXT_RE.test(rec.relPath);
|
|
1948
2748
|
if (!skipHdrFtr) {
|
|
1949
2749
|
const hdr = extractFileHeader(rec.content);
|
|
1950
2750
|
if (hdr) fileHeaders.set(rec.relPath, hdr);
|
|
@@ -1970,9 +2770,11 @@ const outputXml = assembleContextSliceXml({
|
|
|
1970
2770
|
maxHops: 2,
|
|
1971
2771
|
autoExpand: false,
|
|
1972
2772
|
rootAttr: path.basename(targetRoot),
|
|
1973
|
-
version: '0.4.
|
|
1974
|
-
subPathTag
|
|
2773
|
+
version: '0.4.3',
|
|
2774
|
+
subPathTag,
|
|
1975
2775
|
includeParserAttr: false,
|
|
2776
|
+
isSingleFile,
|
|
2777
|
+
rawContentByFile,
|
|
1976
2778
|
controlWords: CONTROL_WORDS,
|
|
1977
2779
|
maskFn: maskCommentsAndStrings
|
|
1978
2780
|
});
|