@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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.1
3
+ * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.3
4
4
  * Features: Embedded Base64 Tree-sitter WASM + Lazy Cache (~/.contextslice/parsers),
5
5
  * State-Machine Brace Matcher Fallback, True Call Graph (BFS), TF-IDF, subPath Sandbox, mtime Cache
6
6
  */
@@ -11,12 +11,13 @@ import readline from 'node:readline';
11
11
  import { createRequire } from 'node:module';
12
12
 
13
13
  if (process.argv.includes('--version') || process.argv.includes('-v')) {
14
- process.stdout.write('ctxslice-mcp v0.4.1\n');
14
+ process.stdout.write('ctxslice-mcp v0.4.3\n');
15
15
  process.exit(0);
16
16
  }
17
17
 
18
18
 
19
19
  const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
20
+ const HTML_EXT_RE = /\.(html?|xhtml)$/i;
20
21
  const EN_CONVERSATIONAL_STOPWORDS = new Set([
21
22
  'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
22
23
  'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
@@ -217,6 +218,373 @@ function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
217
218
  };
218
219
  }
219
220
 
221
+ function dedentHtmlInnerLines(rawLines) {
222
+ let minIndent = Infinity;
223
+ for (let i = 0; i < rawLines.length; i++) {
224
+ const l = rawLines[i];
225
+ if (!l.trim()) continue;
226
+ const indent = (l.match(/^[ \t]*/) || [''])[0].length;
227
+ if (indent < minIndent) minIndent = indent;
228
+ }
229
+ if (!Number.isFinite(minIndent) || minIndent <= 0) return rawLines.join('\n');
230
+ return rawLines.map((l) => (l.length >= minIndent ? l.slice(minIndent) : l.trimStart())).join('\n');
231
+ }
232
+
233
+ function findHtmlTagCloseIdx(lines, startIdx, tag) {
234
+ if (tag === 'script' || tag === 'style') {
235
+ const closeRawRe = new RegExp('</' + tag + '\\s*>', 'i');
236
+ const firstLine = lines[startIdx] || '';
237
+ const gtIdx = firstLine.indexOf('>');
238
+ if (gtIdx !== -1 && closeRawRe.test(firstLine.slice(gtIdx + 1))) {
239
+ return startIdx;
240
+ }
241
+ for (let i = startIdx + 1; i < lines.length; i++) {
242
+ if (closeRawRe.test(lines[i])) return i;
243
+ }
244
+ return lines.length - 1;
245
+ }
246
+
247
+ const openTagRe = new RegExp('<' + tag + '(?:\\s|>)', 'gi');
248
+ const closeTagRe = new RegExp('</' + tag + '\\s*>', 'gi');
249
+ const selfCloseRe = new RegExp('<' + tag + '\\b[^>]*/>', 'gi');
250
+ let depth = 0;
251
+ let inRawTag = null;
252
+ for (let i = startIdx; i < lines.length; i++) {
253
+ const line = lines[i];
254
+ if (inRawTag) {
255
+ if (new RegExp('</' + inRawTag + '\\s*>', 'i').test(line)) {
256
+ inRawTag = null;
257
+ }
258
+ continue;
259
+ }
260
+ const rawOpen = line.match(/<(script|style)(?:\s|>)/i);
261
+ if (rawOpen && i > startIdx) {
262
+ const rTag = rawOpen[1].toLowerCase();
263
+ if (!new RegExp('</' + rTag + '\\s*>', 'i').test(line)) {
264
+ inRawTag = rTag;
265
+ }
266
+ continue;
267
+ }
268
+ const opens = (line.match(openTagRe) || []).length - (line.match(selfCloseRe) || []).length;
269
+ const closes = (line.match(closeTagRe) || []).length;
270
+ depth += opens - closes;
271
+ if (depth <= 0 && i >= startIdx) {
272
+ return i;
273
+ }
274
+ }
275
+ return lines.length - 1;
276
+ }
277
+
278
+ function buildHtmlSectionSkeleton(lines, startIdx, endIdx, tag) {
279
+ const full = lines.slice(startIdx, endIdx + 1).join('\n');
280
+ const lineCount = endIdx - startIdx + 1;
281
+ if (lineCount <= 10) return full;
282
+ const openLine = lines[startIdx];
283
+ const previewLine = lines[startIdx + 1] !== undefined ? lines[startIdx + 1] : '';
284
+ const closeLine = lines[endIdx] || ('</' + tag + '>');
285
+ const folded = Math.max(1, lineCount - 3);
286
+ const comment = tag === 'style'
287
+ ? ' /* ... ' + folded + ' lines folded */'
288
+ : ' <!-- ... ' + folded + ' lines folded -->';
289
+ return openLine + (previewLine ? '\n' + previewLine : '') + '\n' + comment + '\n' + closeLine;
290
+ }
291
+
292
+ function extractHtmlBlocks(code, fileName, extractJsBlocksFn) {
293
+ const lines = String(code || '').replace(/\r\n/g, '\n').split('\n');
294
+ if (lines.length === 0) return [];
295
+ const blocks = [];
296
+ const rawTagRanges = [];
297
+ const isInRanges = (ranges, ln) => ranges.some((r) => ln >= r[0] && ln <= r[1]);
298
+
299
+ // Pass 1: Extract <style> and inline <script> blocks (and nested JS symbols inside <script>)
300
+ const rawOpenRe = /^([ \t]*)<(script|style)(?:\s+([^>]*))?>/i;
301
+ for (let i = 0; i < lines.length; i++) {
302
+ const startLine = i + 1;
303
+ if (isInRanges(rawTagRanges, startLine)) continue;
304
+ const m = lines[i].match(rawOpenRe);
305
+ if (!m) continue;
306
+ const tag = m[2].toLowerCase();
307
+ const attrs = m[3] || '';
308
+ if (tag === 'script' && /\bsrc\s*=/i.test(attrs)) continue;
309
+
310
+ const endIdx = findHtmlTagCloseIdx(lines, i, tag);
311
+ const endLine = endIdx + 1;
312
+ const lineCount = endLine - startLine + 1;
313
+ if (lineCount < 2) continue;
314
+
315
+ rawTagRanges.push([startLine, endLine]);
316
+
317
+ if (tag === 'style') {
318
+ const full = lines.slice(i, endLine).join('\n');
319
+ blocks.push({
320
+ name: '<style>',
321
+ kind: 'type',
322
+ exported: true,
323
+ startLine,
324
+ endLine,
325
+ full,
326
+ skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, 'style')
327
+ });
328
+ i = endIdx;
329
+ continue;
330
+ }
331
+
332
+ // Inline <script>: extract JS symbols and shift line numbers back to HTML lines
333
+ const innerStartIdx = i + 1;
334
+ const innerEndIdx = endIdx; // exclusive in lines.slice (endIdx is closing </script> line)
335
+ let parsedInner = false;
336
+ if (innerEndIdx > innerStartIdx && typeof extractJsBlocksFn === 'function') {
337
+ const innerRawLines = lines.slice(innerStartIdx, innerEndIdx);
338
+ const dedented = dedentHtmlInnerLines(innerRawLines);
339
+ if (dedented.trim()) {
340
+ const jsBlocks = extractJsBlocksFn(dedented) || [];
341
+ const realJs = jsBlocks.filter((b) => b.kind !== 'module');
342
+ if (realJs.length > 0) {
343
+ parsedInner = true;
344
+ const coveredInner = [];
345
+ for (const jb of realJs) {
346
+ const realStart = jb.startLine + innerStartIdx;
347
+ const realEnd = Math.min(endLine - 1, jb.endLine + innerStartIdx);
348
+ const realFull = lines.slice(realStart - 1, realEnd).join('\n');
349
+ const realLinesCount = Math.max(1, realEnd - realStart + 1);
350
+ let realSkel = jb.skeleton;
351
+ if (realLinesCount <= 4) {
352
+ realSkel = realFull;
353
+ }
354
+ coveredInner.push([realStart, realEnd]);
355
+ blocks.push({
356
+ ...jb,
357
+ startLine: realStart,
358
+ endLine: realEnd,
359
+ full: realFull,
360
+ skeleton: realSkel
361
+ });
362
+ }
363
+
364
+ // Preserve substantial top-level script chunks outside functions (e.g. DOM bindings/init)
365
+ let chunkStart = -1;
366
+ let nonEmptyCount = 0;
367
+ const flushTopChunk = (endLn) => {
368
+ if (chunkStart !== -1 && nonEmptyCount >= 6) {
369
+ let cStart = chunkStart;
370
+ let cEnd = endLn;
371
+ while (cStart <= cEnd && !lines[cStart - 1].trim()) cStart++;
372
+ while (cEnd >= cStart && !lines[cEnd - 1].trim()) cEnd--;
373
+ if (cEnd - cStart + 1 >= 5) {
374
+ const cFull = lines.slice(cStart - 1, cEnd).join('\n');
375
+ const cCount = cEnd - cStart + 1;
376
+ const cSkel = cCount > 10
377
+ ? lines[cStart - 1] + '\n' + (lines[cStart] || '') + '\n /* ... ' + (cCount - 3) + ' script lines folded */\n' + lines[cEnd - 1]
378
+ : cFull;
379
+ blocks.push({
380
+ name: '<script#top@' + cStart + '>',
381
+ kind: 'const',
382
+ exported: false,
383
+ startLine: cStart,
384
+ endLine: cEnd,
385
+ full: cFull,
386
+ skeleton: cSkel
387
+ });
388
+ }
389
+ }
390
+ chunkStart = -1;
391
+ nonEmptyCount = 0;
392
+ };
393
+ for (let ln = innerStartIdx + 1; ln <= endLine - 1; ln++) {
394
+ if (isInRanges(coveredInner, ln)) {
395
+ flushTopChunk(ln - 1);
396
+ } else {
397
+ if (chunkStart === -1) chunkStart = ln;
398
+ if (lines[ln - 1] && lines[ln - 1].trim()) nonEmptyCount++;
399
+ }
400
+ }
401
+ flushTopChunk(endLine - 1);
402
+ }
403
+ }
404
+ }
405
+
406
+ if (!parsedInner) {
407
+ const full = lines.slice(i, endLine).join('\n');
408
+ blocks.push({
409
+ name: '<script>',
410
+ kind: 'module',
411
+ exported: true,
412
+ startLine,
413
+ endLine,
414
+ full,
415
+ skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, 'script')
416
+ });
417
+ }
418
+ i = endIdx;
419
+ }
420
+
421
+ // Pass 2: Extract HTML structural landmark sections without overlapping <script>/<style>
422
+ const landmarkRanges = [];
423
+ const landmarkRe = /^([ \t]*)<(head|header|nav|main|section|article|form|template|footer|div)(?:\s+([^>]*))?>/i;
424
+ for (let i = 0; i < lines.length; i++) {
425
+ const startLine = i + 1;
426
+ if (isInRanges(rawTagRanges, startLine) || isInRanges(landmarkRanges, startLine)) continue;
427
+ const m = lines[i].match(landmarkRe);
428
+ if (!m) continue;
429
+
430
+ const tag = m[2].toLowerCase();
431
+ const attrs = m[3] || '';
432
+ const idMatch = attrs.match(/\bid=["']([^"']+)["']/i);
433
+ const classMatch = attrs.match(/\bclass=["']([^"'\s]+)/i);
434
+ if (tag === 'div' && !idMatch) continue;
435
+
436
+ let endIdx = findHtmlTagCloseIdx(lines, i, tag);
437
+ let endLine = endIdx + 1;
438
+ if (endLine - startLine + 1 < 2) continue;
439
+
440
+ // Avoid enclosing child <script> or <style> inside outer container blocks (<head>, <main>, <div#app>)
441
+ const overlapsRaw = rawTagRanges.filter((r) => r[0] > startLine && r[0] <= endLine);
442
+ if (overlapsRaw.length > 0) {
443
+ const firstRawStart = Math.min(...overlapsRaw.map((r) => r[0]));
444
+ if (firstRawStart - startLine >= 3) {
445
+ endLine = firstRawStart - 1;
446
+ endIdx = endLine - 1;
447
+ } else {
448
+ continue;
449
+ }
450
+ }
451
+
452
+ if (tag === 'main' || tag === 'div') {
453
+ const hasChildSection = lines
454
+ .slice(i + 1, Math.max(i + 1, endLine - 1))
455
+ .some((l) => /^\s*<(section|article|form|template)(?:\s|>)/i.test(l));
456
+ if (hasChildSection) continue;
457
+ }
458
+
459
+ landmarkRanges.push([startLine, endLine]);
460
+ const suffix = idMatch ? '#' + idMatch[1] : (classMatch ? '.' + classMatch[1] : '');
461
+ const name = '<' + tag + suffix + '>';
462
+ const full = lines.slice(i, endLine).join('\n');
463
+ blocks.push({
464
+ name,
465
+ kind: tag === 'template' ? 'class' : 'type',
466
+ exported: true,
467
+ startLine,
468
+ endLine,
469
+ full,
470
+ skeleton: buildHtmlSectionSkeleton(lines, i, endIdx, tag)
471
+ });
472
+ i = endIdx;
473
+ }
474
+
475
+ blocks.sort((a, b) => a.startLine - b.startLine);
476
+ return blocks;
477
+ }
478
+
479
+ function sliceSingleFileWindow(content, maxTokens) {
480
+ const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
481
+ if (lines.length === 0) return { windowedCode: '', ranges: [[1, 1]], tokens: 0 };
482
+ const headBudget = Math.max(120, Math.floor(maxTokens * 0.7));
483
+ const tailBudget = Math.max(60, maxTokens - headBudget - 15);
484
+ const headLines = [];
485
+ let headTk = 0;
486
+ let headEnd = 0;
487
+ for (let i = 0; i < lines.length; i++) {
488
+ const tk = estimateTokens(lines[i]);
489
+ if (headTk + tk > headBudget && headLines.length > 0) break;
490
+ headLines.push(lines[i]);
491
+ headTk += tk;
492
+ headEnd = i + 1;
493
+ }
494
+ const tailLinesRev = [];
495
+ let tailTk = 0;
496
+ let tailStart = lines.length + 1;
497
+ for (let i = lines.length - 1; i >= headEnd; i--) {
498
+ const tk = estimateTokens(lines[i]);
499
+ if (tailTk + tk > tailBudget && tailLinesRev.length > 0) break;
500
+ tailLinesRev.push(lines[i]);
501
+ tailTk += tk;
502
+ tailStart = i + 1;
503
+ }
504
+ const tailLines = tailLinesRev.reverse();
505
+ const parts = [];
506
+ const ranges = [];
507
+ if (headLines.length > 0) {
508
+ parts.push(headLines.join('\n'));
509
+ ranges.push([1, headEnd]);
510
+ }
511
+ if (tailLines.length > 0 && tailStart > headEnd + 1) {
512
+ parts.push('<!-- ... lines ' + (headEnd + 1) + '-' + (tailStart - 1) + ' omitted to fit budget ... -->');
513
+ parts.push(tailLines.join('\n'));
514
+ ranges.push([tailStart, lines.length]);
515
+ } else if (tailLines.length > 0) {
516
+ parts.push(tailLines.join('\n'));
517
+ ranges.push([tailStart, lines.length]);
518
+ }
519
+ const windowedCode = parts.join('\n');
520
+ return {
521
+ windowedCode,
522
+ ranges: mergeLineRanges(ranges),
523
+ tokens: estimateTokens(windowedCode)
524
+ };
525
+ }
526
+
527
+ function sliceHtmlSectionWindow(sectionContent, sectionStartLine, queryTerms, radius = 30, maxTokens = 1800) {
528
+ const lines = String(sectionContent || '').replace(/\r\n/g, '\n').split('\n');
529
+ if (lines.length <= 120) return null;
530
+
531
+ const matchedRel = [];
532
+ if (queryTerms && queryTerms.length > 0) {
533
+ for (let i = 0; i < lines.length; i++) {
534
+ const lower = lines[i].toLowerCase();
535
+ if (queryTerms.some((t) => lower.includes(t))) {
536
+ matchedRel.push(i + 1);
537
+ if (matchedRel.length >= 4) break;
538
+ }
539
+ }
540
+ }
541
+
542
+ const rawAbsRanges = matchedRel.length > 0
543
+ ? matchedRel.map((relLn) => [
544
+ sectionStartLine + Math.max(0, relLn - 1 - radius),
545
+ sectionStartLine + Math.min(lines.length - 1, relLn - 1 + radius)
546
+ ])
547
+ : [[sectionStartLine, sectionStartLine + Math.min(lines.length - 1, 59)]];
548
+
549
+ const merged = mergeLineRanges(rawAbsRanges);
550
+ const parts = [];
551
+ const usedRanges = [];
552
+ let accTokens = 0;
553
+ for (let idx = 0; idx < merged.length; idx++) {
554
+ const s = merged[idx][0];
555
+ const e = merged[idx][1];
556
+ const sliceLines = [];
557
+ let endWritten = s - 1;
558
+ for (let absLn = s; absLn <= e; absLn++) {
559
+ const candidate = lines[absLn - sectionStartLine];
560
+ if (candidate === undefined) break;
561
+ const tk = estimateTokens(candidate);
562
+ if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
563
+ sliceLines.push(candidate);
564
+ accTokens += tk;
565
+ endWritten = absLn;
566
+ }
567
+ if (sliceLines.length === 0) break;
568
+ if (idx > 0 && usedRanges.length > 0) {
569
+ const prevEnd = usedRanges[usedRanges.length - 1][1];
570
+ if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
571
+ }
572
+ parts.push(sliceLines.join('\n'));
573
+ usedRanges.push([s, endWritten]);
574
+ if (accTokens >= maxTokens) break;
575
+ }
576
+ const sectionEndLine = sectionStartLine + lines.length - 1;
577
+ if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < sectionEndLine) {
578
+ parts.push('<!-- ... lines ' + (usedRanges[usedRanges.length - 1][1] + 1) + '-' + sectionEndLine + ' omitted ... -->');
579
+ }
580
+ const windowedCode = parts.join('\n');
581
+ return {
582
+ windowedCode,
583
+ ranges: usedRanges.length > 0 ? usedRanges : [[sectionStartLine, Math.min(sectionEndLine, sectionStartLine + 40)]],
584
+ tokens: estimateTokens(windowedCode)
585
+ };
586
+ }
587
+
220
588
  function findPythonSignatureEndIdx(lines, startIdx) {
221
589
  let paren = 0, bracket = 0, brace = 0;
222
590
  const maxScan = Math.min(lines.length - 1, startIdx + 25);
@@ -452,6 +820,133 @@ function extractPythonBlocks(lines, lineIdx) {
452
820
  return { blocks: results, endIdx };
453
821
  }
454
822
 
823
+ function extractTsClassMembers(lines, classStartIdx, classEndIdx, exported, maskFn, findBraceEndFn, findStmtEndFn) {
824
+ const members = [];
825
+ const classSlice = lines.slice(classStartIdx, classEndIdx + 1).join('\n');
826
+ const maskedClassLines = maskFn(classSlice).split('\n');
827
+ let depth = 0;
828
+ let opened = false;
829
+ let relIdx = 0;
830
+
831
+ while (relIdx < maskedClassLines.length) {
832
+ const absIdx = classStartIdx + relIdx;
833
+ const rawLine = lines[absIdx] || '';
834
+ const trimmed = rawLine.trim();
835
+ const mLine = maskedClassLines[relIdx] || '';
836
+
837
+ if (depth === 1 && trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*') && !trimmed.startsWith('*') && absIdx < classEndIdx) {
838
+ // 1) Standard class method: 'async text(...) { ... }'
839
+ 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*\(/);
840
+ if (methodMatch && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodMatch[1])) {
841
+ const mName = methodMatch[1];
842
+ let braceRelLine = relIdx;
843
+ while (braceRelLine < maskedClassLines.length && braceRelLine - relIdx < 8 && !maskedClassLines[braceRelLine].includes('{')) {
844
+ braceRelLine++;
845
+ }
846
+ if (braceRelLine < maskedClassLines.length && maskedClassLines[braceRelLine].includes('{')) {
847
+ const mEnd = Math.min(classEndIdx - 1, findBraceEndFn(lines, absIdx));
848
+ if (mEnd >= absIdx + 1 && mEnd < classEndIdx) {
849
+ const mFull = lines.slice(absIdx, mEnd + 1).join('\n');
850
+ const sigIdx = mFull.indexOf('{');
851
+ const mSkel = (sigIdx === -1 || mEnd - absIdx < 3)
852
+ ? mFull
853
+ : mFull.slice(0, sigIdx).trim() + ' { /* ... ' + (mEnd - absIdx - 1) + ' lines folded */ }';
854
+ members.push({
855
+ name: mName,
856
+ kind: 'method',
857
+ exported,
858
+ startLine: absIdx + 1,
859
+ endLine: mEnd + 1,
860
+ full: mFull,
861
+ skeleton: mSkel
862
+ });
863
+ // Advance depth tracking past method lines cleanly
864
+ for (let k = relIdx; k <= mEnd - classStartIdx && k < maskedClassLines.length; k++) {
865
+ for (const ch of maskedClassLines[k]) {
866
+ if (ch === '{') { depth++; opened = true; }
867
+ else if (ch === '}') depth--;
868
+ }
869
+ }
870
+ relIdx = (mEnd - classStartIdx) + 1;
871
+ continue;
872
+ }
873
+ }
874
+ }
875
+
876
+ // 2) Class field arrow function / function expression: 'text: TextRespond = (...) => { ... }'
877
+ 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*(?::[^=]*)?(?:=|$)/);
878
+ if (fieldMatch && !['if', 'for', 'while', 'switch', 'catch', 'return'].includes(fieldMatch[1])) {
879
+ const fName = fieldMatch[1].replace(/^#/, '');
880
+ const lookSlice = maskedClassLines.slice(relIdx, Math.min(maskedClassLines.length, relIdx + 8)).join('\n');
881
+ const eqIdx = lookSlice.indexOf('=');
882
+ if (eqIdx !== -1) {
883
+ const afterEq = lookSlice.slice(eqIdx + 1);
884
+ const arrowRel = afterEq.indexOf('=>');
885
+ const fnMatch = afterEq.match(/\bfunction\b/);
886
+ const fnRel = fnMatch && fnMatch.index !== undefined ? fnMatch.index : -1;
887
+ const fnPosInLook = (arrowRel !== -1 && (fnRel === -1 || arrowRel < fnRel))
888
+ ? eqIdx + 1 + arrowRel
889
+ : (fnRel !== -1 ? eqIdx + 1 + fnRel : -1);
890
+ if (fnPosInLook !== -1) {
891
+ const lineOffsetToFn = lookSlice.slice(0, fnPosInLook).split('\n').length - 1;
892
+ const fnLineAbs = absIdx + lineOffsetToFn;
893
+ let bodyBraceLineAbs = -1;
894
+ for (let scan = fnLineAbs; scan <= Math.min(classEndIdx - 1, fnLineAbs + 5); scan++) {
895
+ const sMask = maskedClassLines[scan - classStartIdx] || '';
896
+ if (sMask.includes('{')) { bodyBraceLineAbs = scan; break; }
897
+ if (sMask.trim().endsWith(';')) break;
898
+ }
899
+ const mEnd = bodyBraceLineAbs !== -1
900
+ ? Math.min(classEndIdx - 1, findBraceEndFn(lines, bodyBraceLineAbs))
901
+ : Math.min(classEndIdx - 1, findStmtEndFn(lines, absIdx, 'ts'));
902
+ if (mEnd >= absIdx && mEnd < classEndIdx) {
903
+ const mFull = lines.slice(absIdx, mEnd + 1).join('\n');
904
+ let mSkel = mFull;
905
+ if (bodyBraceLineAbs !== -1 && mEnd - absIdx >= 3) {
906
+ const preBodyLines = lines.slice(absIdx, bodyBraceLineAbs + 1);
907
+ const lastPre = preBodyLines[preBodyLines.length - 1];
908
+ const lastMask = maskedClassLines[bodyBraceLineAbs - classStartIdx] || '';
909
+ const bCol = lastMask.indexOf('{');
910
+ if (bCol !== -1) {
911
+ preBodyLines[preBodyLines.length - 1] = lastPre.slice(0, bCol);
912
+ const sigText = preBodyLines.join('\n').trim();
913
+ const folded = Math.max(1, mEnd - bodyBraceLineAbs - 1);
914
+ mSkel = sigText + ' { /* ... ' + folded + ' lines folded */ }';
915
+ }
916
+ }
917
+ members.push({
918
+ name: fName,
919
+ kind: 'method',
920
+ exported,
921
+ startLine: absIdx + 1,
922
+ endLine: mEnd + 1,
923
+ full: mFull,
924
+ skeleton: mSkel
925
+ });
926
+ for (let k = relIdx; k <= mEnd - classStartIdx && k < maskedClassLines.length; k++) {
927
+ for (const ch of maskedClassLines[k]) {
928
+ if (ch === '{') { depth++; opened = true; }
929
+ else if (ch === '}') depth--;
930
+ }
931
+ }
932
+ relIdx = (mEnd - classStartIdx) + 1;
933
+ continue;
934
+ }
935
+ }
936
+ }
937
+ }
938
+ }
939
+
940
+ for (const ch of mLine) {
941
+ if (ch === '{') { depth++; opened = true; }
942
+ else if (ch === '}') depth--;
943
+ }
944
+ if (opened && depth <= 0) break;
945
+ relIdx++;
946
+ }
947
+ return members;
948
+ }
949
+
455
950
  function assembleContextSliceXml(opts) {
456
951
  const {
457
952
  blocks,
@@ -468,20 +963,172 @@ function assembleContextSliceXml(opts) {
468
963
  version,
469
964
  subPathTag,
470
965
  includeParserAttr,
966
+ isSingleFile = false,
967
+ rawContentByFile = null,
471
968
  controlWords,
472
969
  maskFn
473
970
  } = opts;
474
971
 
475
972
  if (!String(rawQuery || '').trim()) {
476
- const treeLines = buildRepositoryFileTree(fileEntries, 1800);
477
- return [
478
- '<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
479
- ' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
480
- ' <repository_file_tree>',
481
- ...treeLines,
482
- ' </repository_file_tree>',
483
- '</context_slice>'
484
- ].join('\n');
973
+ if (!isSingleFile) {
974
+ const treeLines = buildRepositoryFileTree(fileEntries, 1800);
975
+ return [
976
+ '<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
977
+ ' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
978
+ ' <repository_file_tree>',
979
+ ...treeLines,
980
+ ' </repository_file_tree>',
981
+ '</context_slice>'
982
+ ].join('\n');
983
+ }
984
+
985
+ // Direct Single-File Slice Within Budget (Empty Query on a Single-File Target)
986
+ const fp = (fileEntries[0] && fileEntries[0].relPath) || (blocks[0] && blocks[0].filePath) || '';
987
+ const totalLines = fileLineCounts.get(fp) || (rawContentByFile && rawContentByFile.get(fp) ? rawContentByFile.get(fp).replace(/\r\n/g, '\n').split('\n').length : 0);
988
+ const rawContent = rawContentByFile ? rawContentByFile.get(fp) : null;
989
+ const rawFileTk = rawContent !== null && rawContent !== undefined
990
+ ? estimateTokens(rawContent)
991
+ : blocks.reduce((acc, b) => acc + (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full)), 0);
992
+
993
+ if (rawContent !== null && rawContent !== undefined && rawFileTk <= budget) {
994
+ const fileLabel = fp.split('/').pop() || fp || 'file';
995
+ const parserAttr = includeParserAttr && blocks[0] && blocks[0].parserMode ? ' parser="' + escapeXmlAttr(blocks[0].parserMode) + '"' : '';
996
+ return [
997
+ '<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + rawFileTk + '">',
998
+ ' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + (totalLines > 0 ? '1-' + totalLines : '1') + '">',
999
+ ' <focal symbol="' + escapeXmlAttr(fileLabel) + '" lines="1-' + Math.max(1, totalLines) + '"' + parserAttr + '>',
1000
+ rawContent,
1001
+ ' </focal>',
1002
+ ' </file>',
1003
+ '</context_slice>'
1004
+ ].join('\n');
1005
+ }
1006
+
1007
+ // Oversized single file: assemble priority sections + skeletons strictly within budget
1008
+ let remainingSf = budget;
1009
+ const sfBlocks = blocks.map((b) => {
1010
+ const rTk = b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full);
1011
+ const sTk = b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton);
1012
+ return { ...b, rawTk: rTk, skelTk: sTk };
1013
+ });
1014
+
1015
+ const sfPriority = (b) => {
1016
+ if (b.kind === 'function' || b.kind === 'method' || b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' && !String(b.name || '').startsWith('<style')) {
1017
+ if (String(b.name || '').startsWith('<')) return 1;
1018
+ return 0;
1019
+ }
1020
+ if (String(b.name || '').startsWith('<style')) return 3;
1021
+ if (b.kind === 'module') return 3;
1022
+ return 1;
1023
+ };
1024
+
1025
+ const sortedByPriority = sfBlocks
1026
+ .slice()
1027
+ .sort((a, b) => sfPriority(a) - sfPriority(b) || a.startLine - b.startLine);
1028
+
1029
+ const skipHdrSf = PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp);
1030
+ const hdrSf = !skipHdrSf ? fileHeaders.get(fp) : null;
1031
+ let showHdrSf = false;
1032
+ if (hdrSf && hdrSf.header) {
1033
+ const hdrCost = estimateTokens(hdrSf.header) + 12;
1034
+ if (hdrCost <= remainingSf) {
1035
+ remainingSf -= hdrCost;
1036
+ showHdrSf = true;
1037
+ }
1038
+ }
1039
+
1040
+ const pickedMap = new Map();
1041
+ const isNestedMethodCovered = (b) =>
1042
+ b.kind === 'method' &&
1043
+ 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');
1044
+
1045
+ // First reserve compact skeletons across all top sections/symbols
1046
+ for (const b of sortedByPriority) {
1047
+ const key = b.startLine + ':' + b.name;
1048
+ if (pickedMap.has(key)) continue;
1049
+ if (b.kind === 'module' && sfBlocks.length === 1) continue;
1050
+ if (b.skelTk <= remainingSf) {
1051
+ remainingSf -= b.skelTk;
1052
+ pickedMap.set(key, { tier: 'skeleton', item: b, win: null });
1053
+ }
1054
+ }
1055
+
1056
+ // Upgrade highest-priority blocks to full while budget allows
1057
+ for (const b of sortedByPriority) {
1058
+ const key = b.startLine + ':' + b.name;
1059
+ if (isNestedMethodCovered(b)) {
1060
+ const cur = pickedMap.get(key);
1061
+ if (cur && cur.tier === 'skeleton') {
1062
+ remainingSf += b.skelTk;
1063
+ pickedMap.delete(key);
1064
+ }
1065
+ continue;
1066
+ }
1067
+ const existing = pickedMap.get(key);
1068
+ if (existing) {
1069
+ const delta = Math.max(0, b.rawTk - b.skelTk);
1070
+ if (delta <= remainingSf) {
1071
+ remainingSf -= delta;
1072
+ existing.tier = 'full';
1073
+ }
1074
+ } else if (b.rawTk <= remainingSf && !(b.kind === 'module' && b.rawTk > budget)) {
1075
+ remainingSf -= b.rawTk;
1076
+ pickedMap.set(key, { tier: 'full', item: b, win: null });
1077
+ }
1078
+ }
1079
+
1080
+ const selectedSf = Array.from(pickedMap.values()).sort((a, b) => a.item.startLine - b.item.startLine);
1081
+ // Fallback window if single giant module or no blocks fit in full
1082
+ if (selectedSf.length === 0 && (rawContent || (sfBlocks[0] && sfBlocks[0].full))) {
1083
+ const srcText = rawContent || sfBlocks[0].full;
1084
+ const win = sliceSingleFileWindow(srcText, Math.max(200, budget - 40));
1085
+ const usedSf = Math.min(budget, win.tokens);
1086
+ const shownStr = formatShownLines(win.ranges);
1087
+ const fileLabel = fp.split('/').pop() || fp || 'file';
1088
+ return [
1089
+ '<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + usedSf + '">',
1090
+ ' <note>File exceeds ' + budget + ' token budget (' + rawFileTk + ' tokens total); returning windowed structural slice within budget.</note>',
1091
+ ' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + shownStr + '">',
1092
+ ' <focal symbol="' + escapeXmlAttr(fileLabel) + '" lines="' + shownStr + '">',
1093
+ win.windowedCode,
1094
+ ' </focal>',
1095
+ ' </file>',
1096
+ '</context_slice>'
1097
+ ].join('\n');
1098
+ }
1099
+
1100
+ const shownRangesSf = [];
1101
+ if (showHdrSf) shownRangesSf.push([1, hdrSf.endLine]);
1102
+ for (const ent of selectedSf) {
1103
+ shownRangesSf.push([ent.item.startLine, ent.item.endLine]);
1104
+ }
1105
+ const usedSf = Math.max(0, budget - remainingSf);
1106
+ const outSf = [
1107
+ '<context_slice mode="single-file-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + usedSf + '">',
1108
+ ' <note>File exceeds ' + budget + ' token budget (' + rawFileTk + ' tokens total); returning prioritized sections/symbols and folded skeletons within budget.</note>',
1109
+ ' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRangesSf) + '">'
1110
+ ];
1111
+ if (showHdrSf) {
1112
+ outSf.push(' <file_header lines="1-' + hdrSf.endLine + '">');
1113
+ outSf.push(hdrSf.header);
1114
+ outSf.push(' </file_header>');
1115
+ }
1116
+ for (const ent of selectedSf) {
1117
+ const it = ent.item;
1118
+ if (ent.tier === 'full') {
1119
+ const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
1120
+ outSf.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + it.startLine + '-' + it.endLine + '"' + parserAttr + '>');
1121
+ outSf.push(it.full);
1122
+ outSf.push(' </focal>');
1123
+ } else {
1124
+ outSf.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + it.startLine + '-' + it.endLine + '">');
1125
+ outSf.push(it.skeleton);
1126
+ outSf.push(' </skeleton>');
1127
+ }
1128
+ }
1129
+ outSf.push(' </file>');
1130
+ outSf.push('</context_slice>');
1131
+ return outSf.join('\n');
485
1132
  }
486
1133
 
487
1134
  const roleIntents = getQueryRoleIntents(rawQuery);
@@ -492,13 +1139,18 @@ function assembleContextSliceXml(opts) {
492
1139
  const lineCount = Math.max(1, b.endLine - b.startLine + 1);
493
1140
  const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
494
1141
  const isDocExt = DOC_EXT_RE.test(rel);
1142
+ const isHtmlSection = HTML_EXT_RE.test(rel) && String(b.name || '').startsWith('<');
495
1143
  let win = null;
496
1144
  if (b.kind === 'module') {
497
1145
  if (isConfigFile && lineCount > 200) {
498
1146
  win = slicePlainTextConfigWindow(b.full, terms);
499
1147
  } else if (isDocExt && lineCount > 45) {
500
1148
  win = sliceDocWindow(b.full, terms, 16, 480);
1149
+ } else if (isHtmlSection && lineCount > 120) {
1150
+ win = sliceHtmlSectionWindow(b.full, b.startLine, terms, 30, Math.min(2400, Math.max(400, Math.floor(budget * 0.4))));
501
1151
  }
1152
+ } else if (isHtmlSection && lineCount > 120) {
1153
+ win = sliceHtmlSectionWindow(b.full, b.startLine, terms, 30, Math.min(2400, Math.max(400, Math.floor(budget * 0.4))));
502
1154
  }
503
1155
  if (win) configWindowByKey.set(key, win);
504
1156
  const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
@@ -563,7 +1215,7 @@ function assembleContextSliceXml(opts) {
563
1215
  else if (b.role === 'source') score *= 1.25;
564
1216
  }
565
1217
 
566
- return { ...b, score };
1218
+ return { ...b, score, matchedTerms };
567
1219
  }).sort((a, b) => b.score - a.score);
568
1220
 
569
1221
  // Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
@@ -585,6 +1237,12 @@ function assembleContextSliceXml(opts) {
585
1237
  }
586
1238
  }
587
1239
 
1240
+ const isChildMethodOf = (child, parent) =>
1241
+ child.filePath === parent.filePath &&
1242
+ child.kind === 'method' &&
1243
+ (child.name.startsWith(parent.name + '.') ||
1244
+ (child.startLine > parent.startLine && child.endLine <= parent.endLine));
1245
+
588
1246
  const callAdj = Array.from({ length: scored.length }, () => new Set());
589
1247
  const definedNames = Array.from(symbolMap.keys());
590
1248
  for (let i = 0; i < scored.length; i++) {
@@ -600,10 +1258,7 @@ function assembleContextSliceXml(opts) {
600
1258
  if (re.test(maskedCaller)) {
601
1259
  for (const t of (symbolMap.get(sym) || [])) {
602
1260
  const target = scored[t];
603
- if (caller.filePath === target.filePath && (
604
- (caller.kind === 'class' && target.kind === 'method' && target.name.startsWith(caller.name + '.')) ||
605
- (target.kind === 'class' && caller.kind === 'method' && caller.name.startsWith(target.name + '.'))
606
- )) continue;
1261
+ if (isChildMethodOf(target, caller) || isChildMethodOf(caller, target)) continue;
607
1262
  callAdj[i].add(t);
608
1263
  callAdj[t].add(i);
609
1264
  }
@@ -634,7 +1289,7 @@ function assembleContextSliceXml(opts) {
634
1289
  const childIndices = [];
635
1290
  for (let ci = 0; ci < scored.length; ci++) {
636
1291
  const c = scored[ci];
637
- if (c.filePath === b.filePath && c.kind === 'method' && c.name.startsWith(b.name + '.')) {
1292
+ if (isChildMethodOf(c, b)) {
638
1293
  const cShort = c.name.split('.').pop().toLowerCase();
639
1294
  const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
640
1295
  if (explicitHit || c.score >= b.score * 0.55) {
@@ -644,7 +1299,7 @@ function assembleContextSliceXml(opts) {
644
1299
  }
645
1300
  if (childIndices.length > 0) {
646
1301
  promotedParentClassSet.add(idx);
647
- for (const ci of childIndices.slice(0, 3)) candidateChosen.add(ci);
1302
+ for (const ci of childIndices.slice(0, 4)) candidateChosen.add(ci);
648
1303
  continue;
649
1304
  }
650
1305
  }
@@ -653,10 +1308,9 @@ function assembleContextSliceXml(opts) {
653
1308
  for (const idx of candidateChosen) {
654
1309
  const b = scored[idx];
655
1310
  if (b.kind === 'method') {
656
- const clsName = b.name.split('.')[0];
657
1311
  const hasFullParent = [...candidateChosen].some((pIdx) => {
658
1312
  const p = scored[pIdx];
659
- return p && p.kind === 'class' && p.filePath === b.filePath && p.name === clsName;
1313
+ return Boolean(p && p.kind === 'class' && isChildMethodOf(b, p));
660
1314
  });
661
1315
  if (hasFullParent) continue;
662
1316
  }
@@ -685,7 +1339,39 @@ function assembleContextSliceXml(opts) {
685
1339
  }
686
1340
  }
687
1341
 
688
- // Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, then 1/2-hop source -> test -> doc
1342
+ const fileHeaderTokenCache = new Map();
1343
+ for (const [fp, hdr] of fileHeaders.entries()) {
1344
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
1345
+ if (hdr && hdr.header) fileHeaderTokenCache.set(fp, estimateTokens(hdr.header) + 12);
1346
+ }
1347
+
1348
+ const directCoreFiles = new Set(focalFiles);
1349
+ for (const pid of promotedParentClassSet) directCoreFiles.add(scored[pid].filePath);
1350
+ const minDirectTerms = Math.min(2, Math.max(1, terms.length));
1351
+ for (let i = 0; i < scored.length; i++) {
1352
+ const b = scored[i];
1353
+ if (b.role !== 'source') continue;
1354
+ const h = hopDistances.get(i);
1355
+ const isDirectCallable = h === 1 && (b.kind === 'function' || b.kind === 'method' || b.kind === 'class');
1356
+ if ((terms.length >= 2 && b.matchedTerms >= minDirectTerms) || isDirectCallable) {
1357
+ directCoreFiles.add(b.filePath);
1358
+ }
1359
+ }
1360
+
1361
+ const isPeripheralIdx = (idx) => {
1362
+ if (focalSet.has(idx) || promotedParentClassSet.has(idx)) return false;
1363
+ const b = scored[idx];
1364
+ if (focalFiles.has(b.filePath)) return false;
1365
+ const h = hopDistances.get(idx);
1366
+ if (h !== undefined && h >= 2) return true;
1367
+ if (!directCoreFiles.has(b.filePath)) return true;
1368
+ if ((b.kind === 'interface' || b.kind === 'type' || b.kind === 'const') && b.matchedTerms <= 1 && h === undefined) {
1369
+ return true;
1370
+ }
1371
+ return false;
1372
+ };
1373
+
1374
+ // Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, source -> non-peripheral -> matchedTerms -> hop -> score
689
1375
  const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
690
1376
  const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
691
1377
  const focA = focalSet.has(a) ? 0 : 1;
@@ -697,6 +1383,10 @@ function assembleContextSliceXml(opts) {
697
1383
  const rrA = roleRank(scored[a].role);
698
1384
  const rrB = roleRank(scored[b].role);
699
1385
  if (rrA !== rrB) return rrA - rrB;
1386
+ const perA = isPeripheralIdx(a) ? 1 : 0;
1387
+ const perB = isPeripheralIdx(b) ? 1 : 0;
1388
+ if (perA !== perB) return perA - perB;
1389
+ if (scored[a].matchedTerms !== scored[b].matchedTerms) return scored[b].matchedTerms - scored[a].matchedTerms;
700
1390
  const hopA = hopDistances.get(a) ?? 99;
701
1391
  const hopB = hopDistances.get(b) ?? 99;
702
1392
  if (hopA !== hopB) return hopA - hopB;
@@ -706,14 +1396,17 @@ function assembleContextSliceXml(opts) {
706
1396
  let remaining = budget;
707
1397
  let docBudgetUsed = 0;
708
1398
  let testBudgetUsed = 0;
1399
+ let peripheralBudgetUsed = 0;
709
1400
  const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
710
1401
  const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
1402
+ const peripheralBudgetCap = budget <= 16384 ? Math.floor(budget * 0.25) : Math.floor(budget * 0.3);
711
1403
  const dirBudgetUsed = {};
712
1404
  const maxDirBudget = budget * 0.72;
713
1405
 
714
1406
  const includedIds = new Set();
715
1407
  const includedFiles = [];
716
1408
  const includedFilesSet = new Set();
1409
+ const headerChargedFiles = new Set();
717
1410
  const fullStart1EndLine = new Map();
718
1411
  const coveredRangesByFile = new Map();
719
1412
  const partialFiles = new Set();
@@ -722,6 +1415,11 @@ function assembleContextSliceXml(opts) {
722
1415
  const skelCandidates = [];
723
1416
  const candidateItems = [];
724
1417
 
1418
+ const getHeaderReserve = (item) => {
1419
+ if (headerChargedFiles.has(item.filePath)) return 0;
1420
+ if (item.kind === 'module' && item.startLine === 1) return 0;
1421
+ return fileHeaderTokenCache.get(item.filePath) || 0;
1422
+ };
725
1423
  const addCoveredRange = (fp, s, e) => {
726
1424
  if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
727
1425
  coveredRangesByFile.get(fp).push([s, e]);
@@ -747,9 +1445,8 @@ function assembleContextSliceXml(opts) {
747
1445
  for (const idx of allocOrder) {
748
1446
  const item = scored[idx];
749
1447
  if (item.kind === 'method') {
750
- const clsName = item.name.split('.')[0];
751
- const fullSet = fullParentClassesByFile.get(item.filePath);
752
- if (fullSet && fullSet.has(clsName)) continue;
1448
+ const fullClasses = fullParentClassesByFile.get(item.filePath);
1449
+ if (fullClasses && fullClasses.some((cls) => isChildMethodOf(item, cls))) continue;
753
1450
  }
754
1451
 
755
1452
  const topDir = item.filePath.split('/')[0] || 'root';
@@ -757,17 +1454,23 @@ function assembleContextSliceXml(opts) {
757
1454
  const hop = hopDistances.get(idx);
758
1455
  const isFocal = focalSet.has(idx);
759
1456
  const isPromotedParent = promotedParentClassSet.has(idx);
1457
+ const peripheral = isPeripheralIdx(idx);
760
1458
  const key = item.filePath + ':' + item.startLine;
761
1459
  const win = configWindowByKey.get(key);
1460
+ const hdrCost = getHeaderReserve(item);
762
1461
 
763
1462
  if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
764
1463
  remaining = Math.max(0, remaining - item.rawTk);
1464
+ if (hdrCost > 0 && hdrCost <= remaining) {
1465
+ remaining -= hdrCost;
1466
+ headerChargedFiles.add(item.filePath);
1467
+ }
765
1468
  dirBudgetUsed[topDir] = curDir + item.rawTk;
766
1469
  addRoleBudget(item.role, item.rawTk);
767
1470
  includedIds.add(key);
768
1471
  if (item.kind === 'class') {
769
- if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, new Set());
770
- fullParentClassesByFile.get(item.filePath).add(item.name);
1472
+ if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, []);
1473
+ fullParentClassesByFile.get(item.filePath).push(item);
771
1474
  }
772
1475
  if (win) {
773
1476
  for (const r of win.ranges) {
@@ -781,32 +1484,47 @@ function assembleContextSliceXml(opts) {
781
1484
  addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
782
1485
  } else if (isPromotedParent && item.skelTk <= remaining) {
783
1486
  remaining -= item.skelTk;
1487
+ if (hdrCost > 0 && hdrCost <= remaining) {
1488
+ remaining -= hdrCost;
1489
+ headerChargedFiles.add(item.filePath);
1490
+ }
784
1491
  dirBudgetUsed[topDir] = curDir + item.skelTk;
785
1492
  includedIds.add(key);
786
1493
  partialFiles.add(item.filePath);
787
1494
  addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
788
- } else if (item.skelTk <= remaining && (curDir + item.skelTk <= maxDirBudget || item.role === 'source') && canUseRoleBudget(item.role, item.skelTk)) {
789
- const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
790
- const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
791
- if (linked) {
792
- remaining -= item.skelTk;
793
- dirBudgetUsed[topDir] = curDir + item.skelTk;
794
- addRoleBudget(item.role, item.skelTk);
795
- includedIds.add(key);
796
- partialFiles.add(item.filePath);
797
- if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
798
- if (autoExpand && item.role === 'source' && !isPromotedParent) {
799
- skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
1495
+ } else {
1496
+ const totalSkelCost = item.skelTk + hdrCost;
1497
+ const fitsPeripheral = !peripheral || (peripheralBudgetUsed + totalSkelCost <= peripheralBudgetCap);
1498
+ if (
1499
+ fitsPeripheral &&
1500
+ totalSkelCost <= remaining &&
1501
+ (curDir + item.skelTk <= maxDirBudget || item.role === 'source') &&
1502
+ canUseRoleBudget(item.role, item.skelTk)
1503
+ ) {
1504
+ const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
1505
+ const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
1506
+ if (linked) {
1507
+ remaining -= totalSkelCost;
1508
+ if (hdrCost > 0) headerChargedFiles.add(item.filePath);
1509
+ if (peripheral) peripheralBudgetUsed += totalSkelCost;
1510
+ dirBudgetUsed[topDir] = curDir + totalSkelCost;
1511
+ addRoleBudget(item.role, item.skelTk);
1512
+ includedIds.add(key);
1513
+ partialFiles.add(item.filePath);
1514
+ if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
1515
+ if (autoExpand && item.role === 'source' && !isPromotedParent && !peripheral) {
1516
+ skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
1517
+ } else {
1518
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
1519
+ }
800
1520
  } else {
801
- addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
1521
+ partialFiles.add(item.filePath);
1522
+ candidateItems.push(item);
802
1523
  }
803
1524
  } else {
804
1525
  partialFiles.add(item.filePath);
805
1526
  candidateItems.push(item);
806
1527
  }
807
- } else {
808
- partialFiles.add(item.filePath);
809
- candidateItems.push(item);
810
1528
  }
811
1529
  }
812
1530
 
@@ -815,8 +1533,8 @@ function assembleContextSliceXml(opts) {
815
1533
  for (const cand of skelCandidates) {
816
1534
  const it = cand.item;
817
1535
  const delta = Math.max(0, it.rawTk - it.skelTk);
818
- const isComplexCluster = (cand.hop !== null || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
819
- const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
1536
+ const isComplexCluster = (cand.hop === 1 || it.matchedTerms >= minDirectTerms || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
1537
+ const canExpandClass = it.kind !== 'class' || (!it.filePath.endsWith('.py') && it.lineCount <= 80);
820
1538
  if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
821
1539
  remaining -= delta;
822
1540
  autoExpandedNames.push(it.name);
@@ -838,20 +1556,29 @@ function assembleContextSliceXml(opts) {
838
1556
 
839
1557
  if (includedFiles.length === 0) {
840
1558
  const treeLines = buildRepositoryFileTree(fileEntries, 1800);
841
- return [
1559
+ const outZero = [
842
1560
  '<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
843
1561
  ' <note>WARNING: 0 matches found for query "' + escapeXmlText(rawQuery) + '". Do NOT guess code from this file tree alone—pick valid file paths or symbol names from the tree below and call context_slice again.</note>',
844
1562
  ' <repository_file_tree>',
845
1563
  ...treeLines,
846
- ' </repository_file_tree>',
847
- '</context_slice>'
848
- ].join('\n');
1564
+ ' </repository_file_tree>'
1565
+ ];
1566
+ if (isSingleFile && blocks.length > 0) {
1567
+ outZero.push(' <file_symbol_outline>');
1568
+ const sortedSym = blocks.slice().sort((a, b) => a.startLine - b.startLine).slice(0, 45);
1569
+ for (const sb of sortedSym) {
1570
+ outZero.push(' line ' + sb.startLine + '-' + sb.endLine + ': ' + sb.kind + ' ' + sb.name);
1571
+ }
1572
+ outZero.push(' </file_symbol_outline>');
1573
+ }
1574
+ outZero.push('</context_slice>');
1575
+ return outZero.join('\n');
849
1576
  }
850
1577
 
851
1578
  const headerByFile = new Map();
852
1579
  const headerEndByFile = new Map();
853
1580
  for (const fp of includedFiles) {
854
- if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
1581
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
855
1582
  const entries = selectedByFile.get(fp) || [];
856
1583
  const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
857
1584
  if (hasStart1ModuleSkel) continue;
@@ -864,7 +1591,8 @@ function assembleContextSliceXml(opts) {
864
1591
 
865
1592
  const footerByFile = new Map();
866
1593
  for (const fp of includedFiles) {
867
- if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
1594
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp) || HTML_EXT_RE.test(fp)) continue;
1595
+ if (!directCoreFiles.has(fp)) continue;
868
1596
  const ftr = fileFooters.get(fp);
869
1597
  if (!ftr) continue;
870
1598
  const ranges = coveredRangesByFile.get(fp) || [];
@@ -891,9 +1619,18 @@ function assembleContextSliceXml(opts) {
891
1619
 
892
1620
  for (const fp of includedFiles) {
893
1621
  const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
894
- const presentClassNames = new Set(rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item.name));
1622
+ const fullClasses = rawEntries.filter((e) => e.tier === 'full' && e.item.kind === 'class').map((e) => e.item);
1623
+ const structuralPyClasses = /\.pyw?$/i.test(fp)
1624
+ ? rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item)
1625
+ : [];
895
1626
  const entries = rawEntries.filter(
896
- (e) => !(e.tier === 'skeleton' && e.item.kind === 'method' && presentClassNames.has(e.item.name.split('.')[0])),
1627
+ (e) =>
1628
+ !(
1629
+ e.tier === 'skeleton' &&
1630
+ e.item.kind === 'method' &&
1631
+ (fullClasses.some((cls) => isChildMethodOf(e.item, cls)) ||
1632
+ structuralPyClasses.some((cls) => isChildMethodOf(e.item, cls)))
1633
+ ),
897
1634
  );
898
1635
  const fullEntries = entries.filter((e) => e.tier === 'full');
899
1636
  const hdr = headerByFile.get(fp);
@@ -927,7 +1664,7 @@ function assembleContextSliceXml(opts) {
927
1664
  let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
928
1665
  if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
929
1666
  const expandedChildRanges = fullEntries
930
- .filter((fe) => fe.item.kind === 'method' && fe.item.name.startsWith(it.name + '.'))
1667
+ .filter((fe) => isChildMethodOf(fe.item, it))
931
1668
  .map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
932
1669
  if (expandedChildRanges.length > 0) {
933
1670
  skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
@@ -1350,14 +2087,14 @@ function expandQueryTerms(query) {
1350
2087
 
1351
2088
  const TOOL_DEF = {
1352
2089
  name: 'get_context_slice',
1353
- description: 'PRIMARY code-reading tool (v0.4.1) with Tree-sitter WASM / State-Machine structural parsing, True Call Graph, TF-IDF & Dual-State File Tree.',
2090
+ description: 'PRIMARY code-reading tool (v0.4.3) with Tree-sitter WASM / State-Machine structural parsing, True Call Graph, TF-IDF, Single-File & HTML Slicing, and Dual-State File Tree.',
1354
2091
  annotations: { readOnlyHint: true },
1355
2092
  inputSchema: {
1356
2093
  type: 'object',
1357
2094
  properties: {
1358
- query: { type: 'string', description: 'Task or symbol keywords (Supports CJK multi-language + bilingual matching; omit or pass "" to return repository file tree overview)' },
1359
- projectPath: { type: 'string', description: 'Absolute path to target project folder' },
1360
- subPath: { type: 'string', description: 'Optional sub-directory path to sandbox/restrict project scanning (e.g. src/auth)' },
2095
+ query: { type: 'string', description: 'Task or symbol keywords (Supports CJK + bilingual matching; omit or pass "" to return repository file tree for directories, or direct single-file slice when targeting a single file)' },
2096
+ projectPath: { type: 'string', description: 'Absolute path to target project directory or single file' },
2097
+ subPath: { type: 'string', description: 'Optional sub-directory or single file path relative to projectPath (e.g. src/auth or ai_test.html)' },
1361
2098
  budget: { type: 'number', description: 'Max token budget (default 32768)' },
1362
2099
  autoExpand: { type: 'boolean', description: 'Auto-expand high-complexity skeleton clusters (default true)' }
1363
2100
  },
@@ -1373,8 +2110,8 @@ const EXPAND_TOOL_DEF = {
1373
2110
  type: 'object',
1374
2111
  properties: {
1375
2112
  symbols: { type: 'array', items: { type: 'string' }, description: 'Symbol or file names to expand' },
1376
- projectPath: { type: 'string', description: 'Absolute path to target project folder' },
1377
- subPath: { type: 'string', description: 'Optional sub-directory path sandbox' },
2113
+ projectPath: { type: 'string', description: 'Absolute path to target project directory or single file' },
2114
+ subPath: { type: 'string', description: 'Optional sub-directory or single file path sandbox' },
1378
2115
  budget: { type: 'number', description: 'Max token budget for expanded code' }
1379
2116
  },
1380
2117
  required: ['symbols']
@@ -1604,6 +2341,97 @@ async function extractBlocksWithTreeSitter(code, ext, fileName) {
1604
2341
  blocks.push({ name, kind, startLine, endLine, full, skeleton });
1605
2342
  }
1606
2343
 
2344
+ // Extract TS/JS class field arrow functions & function expressions inside class_body
2345
+ // (covers public_field_definition, property_definition, field_definition)
2346
+ if (langName === 'typescript' || langName === 'tsx' || langName === 'javascript') {
2347
+ const stack = [tree.rootNode];
2348
+ while (stack.length > 0) {
2349
+ const cur = stack.pop();
2350
+ if (!cur) continue;
2351
+ if (cur.type === 'class_body') {
2352
+ const children = cur.namedChildren || [];
2353
+ for (const fieldNode of children) {
2354
+ if (
2355
+ fieldNode.type !== 'public_field_definition' &&
2356
+ fieldNode.type !== 'property_definition' &&
2357
+ fieldNode.type !== 'field_definition'
2358
+ ) {
2359
+ continue;
2360
+ }
2361
+ let valNode = fieldNode.childForFieldName
2362
+ ? (fieldNode.childForFieldName('value') || fieldNode.childForFieldName('initializer'))
2363
+ : null;
2364
+ if (!valNode && fieldNode.namedChildren) {
2365
+ valNode = fieldNode.namedChildren.find(
2366
+ (nc) =>
2367
+ nc.type === 'arrow_function' ||
2368
+ nc.type === 'function_expression' ||
2369
+ nc.type === 'function' ||
2370
+ nc.type === 'parenthesized_expression',
2371
+ ) || null;
2372
+ }
2373
+ while (valNode && valNode.type === 'parenthesized_expression' && valNode.namedChildCount === 1) {
2374
+ valNode = valNode.namedChild(0);
2375
+ }
2376
+ if (
2377
+ !valNode ||
2378
+ (valNode.type !== 'arrow_function' &&
2379
+ valNode.type !== 'function_expression' &&
2380
+ valNode.type !== 'function')
2381
+ ) {
2382
+ continue;
2383
+ }
2384
+ const nameNode =
2385
+ (fieldNode.childForFieldName
2386
+ ? (fieldNode.childForFieldName('name') || fieldNode.childForFieldName('property'))
2387
+ : null) ||
2388
+ (fieldNode.namedChildren || []).find(
2389
+ (nc) =>
2390
+ nc.type === 'property_identifier' ||
2391
+ nc.type === 'private_property_identifier' ||
2392
+ nc.type === 'identifier',
2393
+ );
2394
+ const rawFieldName = nameNode ? String(nameNode.text || '').trim().replace(/^#/, '') : '';
2395
+ if (!rawFieldName) continue;
2396
+
2397
+ const startLine = fieldNode.startPosition.row + 1;
2398
+ const endLine = fieldNode.endPosition.row + 1;
2399
+ const key = rawFieldName + '@' + startLine + '-' + endLine;
2400
+ if (seen.has(key)) continue;
2401
+ seen.add(key);
2402
+
2403
+ const full = lines.slice(startLine - 1, endLine).join('\n');
2404
+ let skeleton = full;
2405
+ if (endLine - startLine >= 3) {
2406
+ const fnBody = valNode.childForFieldName ? valNode.childForFieldName('body') : null;
2407
+ if (fnBody && fnBody.type === 'statement_block') {
2408
+ const bodyRow = fnBody.startPosition.row;
2409
+ const bodyCol = fnBody.startPosition.column;
2410
+ const preLines = lines.slice(startLine - 1, bodyRow + 1);
2411
+ if (preLines.length > 0) {
2412
+ preLines[preLines.length - 1] = preLines[preLines.length - 1].slice(0, bodyCol);
2413
+ const sigPrefix = preLines.join('\n').trim();
2414
+ const foldedLines = Math.max(1, endLine - (bodyRow + 1) - 1);
2415
+ skeleton = sigPrefix + ` { /* ... ${foldedLines} lines folded */ }`;
2416
+ }
2417
+ } else {
2418
+ const sigIdx = full.indexOf('{');
2419
+ if (sigIdx !== -1) {
2420
+ skeleton = full.slice(0, sigIdx).trim() + ` { /* ... ${endLine - startLine - 1} lines folded */ }`;
2421
+ }
2422
+ }
2423
+ }
2424
+ blocks.push({ name: rawFieldName, kind: 'method', startLine, endLine, full, skeleton });
2425
+ }
2426
+ continue;
2427
+ }
2428
+ const kids = cur.namedChildren || [];
2429
+ for (let k = kids.length - 1; k >= 0; k--) {
2430
+ stack.push(kids[k]);
2431
+ }
2432
+ }
2433
+ }
2434
+
1607
2435
  if (blocks.length === 0) return null;
1608
2436
  blocks.sort((a, b) => a.startLine - b.startLine);
1609
2437
  return blocks;
@@ -1644,9 +2472,13 @@ function findBraceEnd(lines, startIdx) {
1644
2472
  return startIdx + endRel;
1645
2473
  }
1646
2474
 
1647
- // 支援 Go, Rust, Java, Kotlin, C#, C++, Python, TS/JS 之多語言區塊提取器 (Offline Fallback)
2475
+ // 支援 Go, Rust, Java, Kotlin, C#, C++, Python, HTML, TS/JS 之多語言區塊提取器 (Offline Fallback)
1648
2476
  function extractBlocks(code, ext, fileName) {
1649
2477
  const e = (ext || '').toLowerCase();
2478
+ if (e === '.html' || e === '.htm' || e === '.xhtml') {
2479
+ const htmlBlocks = extractHtmlBlocks(code, fileName, (innerCode) => extractBlocks(innerCode, '.js', fileName));
2480
+ if (htmlBlocks && htmlBlocks.length > 0) return htmlBlocks;
2481
+ }
1650
2482
  const lines = code.split('\n');
1651
2483
  const blocks = [];
1652
2484
 
@@ -1773,8 +2605,15 @@ function extractBlocks(code, ext, fileName) {
1773
2605
  const skeleton = (kind === 'interface' || kind === 'type' || isShortConst || sigIdx === -1 || end - i < 4)
1774
2606
  ? full
1775
2607
  : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
1776
- blocks.push({ name, kind, exported: line.startsWith('export '), startLine: i + 1, endLine: end + 1, full, skeleton });
1777
- if (kind !== 'class' && kind !== 'module') i = end;
2608
+ const isExported = line.startsWith('export ');
2609
+ blocks.push({ name, kind, exported: isExported, startLine: i + 1, endLine: end + 1, full, skeleton });
2610
+ if (kind === 'class' && /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(e)) {
2611
+ const classMembers = extractTsClassMembers(lines, i, end, isExported, maskCommentsAndStrings, findBraceEnd, findStatementEndLine);
2612
+ if (classMembers.length > 0) blocks.push(...classMembers);
2613
+ i = end;
2614
+ } else if (kind !== 'class' && kind !== 'module') {
2615
+ i = end;
2616
+ }
1778
2617
  }
1779
2618
  }
1780
2619
 
@@ -2155,6 +2994,13 @@ function collectFileOverview(root, scanRoot) {
2155
2994
  const files = [];
2156
2995
  const walk = (d) => {
2157
2996
  if (!fs.existsSync(d)) return;
2997
+ let st;
2998
+ try { st = fs.statSync(d); } catch { return; }
2999
+ if (st.isFile()) {
3000
+ if (isAcceptedFile(d.replace(/\\/g, '/'))) files.push(d);
3001
+ return;
3002
+ }
3003
+ if (!st.isDirectory()) return;
2158
3004
  for (const e of fs.readdirSync(d, { withFileTypes: true })) {
2159
3005
  if (IGNORE_DIRS.has(e.name)) continue;
2160
3006
  const full = path.join(d, e.name);
@@ -2176,10 +3022,17 @@ function collectFileOverview(root, scanRoot) {
2176
3022
  return fileEntries;
2177
3023
  }
2178
3024
 
2179
- async function collectProjectBlocks(root, scanRoot) {
3025
+ async function collectProjectBlocks(root, scanRoot, includeRawContent = false) {
2180
3026
  const files = [];
2181
3027
  const walk = (d) => {
2182
3028
  if (!fs.existsSync(d)) return;
3029
+ let st;
3030
+ try { st = fs.statSync(d); } catch { return; }
3031
+ if (st.isFile()) {
3032
+ if (isAcceptedFile(d.replace(/\\/g, '/'))) files.push(d);
3033
+ return;
3034
+ }
3035
+ if (!st.isDirectory()) return;
2183
3036
  for (const e of fs.readdirSync(d, { withFileTypes: true })) {
2184
3037
  if (IGNORE_DIRS.has(e.name)) continue;
2185
3038
  const full = path.join(d, e.name);
@@ -2200,6 +3053,7 @@ async function collectProjectBlocks(root, scanRoot) {
2200
3053
  const footerMap = new Map();
2201
3054
  const lineCountMap = new Map();
2202
3055
  const fileEntries = [];
3056
+ const rawContentMap = includeRawContent ? new Map() : null;
2203
3057
  for (const f of files) {
2204
3058
  const rel = path.relative(root, f).replace(/\\/g, '/');
2205
3059
  let stat;
@@ -2216,17 +3070,26 @@ async function collectProjectBlocks(root, scanRoot) {
2216
3070
  let fileHeader = null;
2217
3071
  let fileFooter = null;
2218
3072
  let fileLines = 0;
2219
- const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rel) || DOC_EXT_RE.test(rel);
3073
+ const isHtmlExt = HTML_EXT_RE.test(rel);
3074
+ const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rel) || DOC_EXT_RE.test(rel) || isHtmlExt;
3075
+ let rawText = null;
2220
3076
  if (cached && cached.mtime === mtime) {
2221
3077
  items = cached.items;
2222
3078
  parserMode = cached.parserMode || 'regex';
2223
3079
  fileHeader = skipHdrFtr ? null : (cached.header ?? null);
2224
3080
  fileFooter = skipHdrFtr ? null : (cached.footer ?? null);
2225
3081
  fileLines = cached.lineCount || 0;
3082
+ if (rawContentMap) {
3083
+ try {
3084
+ const rawBuf = fs.readFileSync(f);
3085
+ if (!isBinaryBuffer(rawBuf)) rawText = rawBuf.toString('utf8');
3086
+ } catch {}
3087
+ }
2226
3088
  } else {
2227
3089
  const rawBuf = fs.readFileSync(f);
2228
3090
  if (isBinaryBuffer(rawBuf)) continue;
2229
3091
  const raw = rawBuf.toString('utf8');
3092
+ rawText = raw;
2230
3093
  fileLines = raw.replace(/\r\n/g, '\n').split('\n').length;
2231
3094
  fileHeader = skipHdrFtr ? null : extractFileHeader(raw);
2232
3095
  fileFooter = skipHdrFtr ? null : extractFileFooter(raw);
@@ -2242,10 +3105,13 @@ async function collectProjectBlocks(root, scanRoot) {
2242
3105
  ? 'plain-text-config'
2243
3106
  : DOC_EXT_RE.test(rel)
2244
3107
  ? 'markdown-doc'
2245
- : 'state-machine-regex';
3108
+ : isHtmlExt
3109
+ ? 'html-script-slicer'
3110
+ : 'state-machine-regex';
2246
3111
  }
2247
3112
  FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
2248
3113
  }
3114
+ if (rawContentMap && rawText !== null) rawContentMap.set(rel, rawText);
2249
3115
  if (fileHeader) headerMap.set(rel, fileHeader);
2250
3116
  if (fileFooter) footerMap.set(rel, fileFooter);
2251
3117
  lineCountMap.set(rel, fileLines);
@@ -2263,24 +3129,47 @@ async function collectProjectBlocks(root, scanRoot) {
2263
3129
  });
2264
3130
  }
2265
3131
  }
2266
- return { blocks: allBlocks, headerMap, footerMap, lineCountMap, fileEntries };
3132
+ return { blocks: allBlocks, headerMap, footerMap, lineCountMap, fileEntries, rawContentMap };
2267
3133
  }
2268
3134
 
2269
3135
  function resolveScanRoot(projectPath, subPath) {
2270
- const root = projectPath ? path.resolve(projectPath) : (process.env.WORKSPACE_ROOT || process.cwd());
2271
- if (!fs.existsSync(root)) throw new Error(`projectPath not found: ${root}`);
3136
+ const rawProject = projectPath ? path.resolve(projectPath) : (process.env.WORKSPACE_ROOT || process.cwd());
3137
+ if (!fs.existsSync(rawProject)) throw new Error(`projectPath not found: ${rawProject}`);
3138
+ let projStat;
3139
+ try {
3140
+ projStat = fs.statSync(rawProject);
3141
+ } catch {
3142
+ throw new Error(`Cannot stat projectPath: ${rawProject}`);
3143
+ }
3144
+
3145
+ if (projStat.isFile()) {
3146
+ if (subPath && typeof subPath === 'string' && subPath.trim()) {
3147
+ const cleanSub = subPath.trim().replace(/\\/g, '/');
3148
+ if (cleanSub !== path.basename(rawProject) && cleanSub !== '.') {
3149
+ throw new Error(`subPath '${subPath}' cannot be used when projectPath is already a file: ${rawProject}`);
3150
+ }
3151
+ }
3152
+ return { root: path.dirname(rawProject), scanRoot: rawProject, isSingleFile: true };
3153
+ }
3154
+
2272
3155
  if (!subPath || typeof subPath !== 'string' || !subPath.trim()) {
2273
- return { root, scanRoot: root };
3156
+ return { root: rawProject, scanRoot: rawProject, isSingleFile: false };
2274
3157
  }
2275
- const scanRoot = path.resolve(root, subPath);
2276
- const rel = path.relative(root, scanRoot);
3158
+ const scanRoot = path.resolve(rawProject, subPath);
3159
+ const rel = path.relative(rawProject, scanRoot);
2277
3160
  if (rel.startsWith('..') || path.isAbsolute(rel)) {
2278
3161
  throw new Error(`Security Error: subPath '${subPath}' escapes projectPath sandbox`);
2279
3162
  }
2280
3163
  if (!fs.existsSync(scanRoot)) {
2281
3164
  throw new Error(`subPath not found: ${scanRoot}`);
2282
3165
  }
2283
- return { root, scanRoot };
3166
+ let scanStat;
3167
+ try {
3168
+ scanStat = fs.statSync(scanRoot);
3169
+ } catch {
3170
+ throw new Error(`Cannot stat subPath: ${scanRoot}`);
3171
+ }
3172
+ return { root: rawProject, scanRoot, isSingleFile: scanStat.isFile() };
2284
3173
  }
2285
3174
 
2286
3175
  async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPath) {
@@ -2359,12 +3248,12 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
2359
3248
 
2360
3249
  async function sliceProject(query, projectPath, budget = 32768, autoExpand = true, subPath) {
2361
3250
  try {
2362
- const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
3251
+ const { root, scanRoot, isSingleFile } = resolveScanRoot(projectPath, subPath);
2363
3252
  const rawQuery = String(query ?? '');
2364
3253
  const subPathTag = subPath ? ` subPath="${escapeXmlAttr(subPath)}"` : '';
2365
3254
 
2366
- // State A: Empty query -> return repository file tree overview (~1K-2K tokens)
2367
- if (!rawQuery.trim()) {
3255
+ // State A: Empty query on directory -> return repository file tree overview (~1K-2K tokens)
3256
+ if (!rawQuery.trim() && !isSingleFile) {
2368
3257
  const fileEntries = collectFileOverview(root, scanRoot);
2369
3258
  return assembleContextSliceXml({
2370
3259
  blocks: [],
@@ -2378,16 +3267,20 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
2378
3267
  maxHops: 2,
2379
3268
  autoExpand,
2380
3269
  rootAttr: root,
2381
- version: '0.4.1',
3270
+ version: '0.4.3',
2382
3271
  subPathTag,
2383
3272
  includeParserAttr: true,
3273
+ isSingleFile: false,
2384
3274
  controlWords: CONTROL_WORDS,
2385
3275
  maskFn: maskCommentsAndStrings
2386
3276
  });
2387
3277
  }
2388
3278
 
2389
3279
  const terms = expandQueryTerms(rawQuery);
2390
- const { blocks, headerMap, footerMap, lineCountMap, fileEntries } = await collectProjectBlocks(root, scanRoot);
3280
+ const { blocks, headerMap, footerMap, lineCountMap, fileEntries, rawContentMap } = await collectProjectBlocks(root, scanRoot, isSingleFile);
3281
+ if (isSingleFile && fileEntries.length === 0) {
3282
+ return `Error: Target file is binary, a secret (.env/.pem/.key), or a skipped lockfile/minified asset: ${scanRoot}`;
3283
+ }
2391
3284
  return assembleContextSliceXml({
2392
3285
  blocks,
2393
3286
  fileEntries,
@@ -2400,9 +3293,11 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
2400
3293
  maxHops: 2,
2401
3294
  autoExpand,
2402
3295
  rootAttr: root,
2403
- version: '0.4.1',
3296
+ version: '0.4.3',
2404
3297
  subPathTag,
2405
3298
  includeParserAttr: true,
3299
+ isSingleFile,
3300
+ rawContentByFile: rawContentMap,
2406
3301
  controlWords: CONTROL_WORDS,
2407
3302
  maskFn: maskCommentsAndStrings
2408
3303
  });
@@ -2424,7 +3319,7 @@ rl.on('line', async (line) => {
2424
3319
  return send({
2425
3320
  protocolVersion: req.params?.protocolVersion || '2024-11-05',
2426
3321
  capabilities: { tools: {} },
2427
- serverInfo: { name: 'ctxslice-thin', version: '0.4.1' }
3322
+ serverInfo: { name: 'ctxslice-thin', version: '0.4.3' }
2428
3323
  });
2429
3324
  }
2430
3325
  if (req.method === 'ping') return send({});