@grundy40/contextslice 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.0
3
+ * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.1
4
4
  * Features: Embedded Base64 Tree-sitter WASM + Lazy Cache (~/.contextslice/parsers),
5
5
  * State-Machine Brace Matcher Fallback, True Call Graph (BFS), TF-IDF, subPath Sandbox, mtime Cache
6
6
  */
@@ -11,7 +11,7 @@ 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.0\n');
14
+ process.stdout.write('ctxslice-mcp v0.4.1\n');
15
15
  process.exit(0);
16
16
  }
17
17
 
@@ -134,6 +134,832 @@ function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
134
134
  }
135
135
  return out;
136
136
  }
137
+ const DOC_EXT_RE = /\.(md|mdx|rst|adoc|asciidoc)$/i;
138
+ const DOC_PATH_RE = /(^|\/)(docs?|documentation|wiki|guides?)\/|(^|\/)(README|CHANGELOG|HISTORY|CONTRIBUTING|CHANGES|RELEASES|MIGRATION|UPGRADING|AUTHORS|NOTICE|LICENSE)([^/]*)$/i;
139
+ const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|specs|testing|fixtures?|benchmarks?|examples?|samples?)\/|(\.|_)(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.[^/]+$/i;
140
+ const SYNTAX_NOISE_WORDS = new Set([
141
+ 'class', 'def', 'function', 'func', 'fn', 'struct', 'interface', 'type', 'enum',
142
+ 'const', 'let', 'var', 'async', 'await', 'import', 'export', 'return',
143
+ 'public', 'private', 'protected', 'static'
144
+ ]);
145
+
146
+ function classifyFileRole(filePath) {
147
+ const norm = String(filePath || '').replace(/\\/g, '/');
148
+ if (DOC_EXT_RE.test(norm) || DOC_PATH_RE.test(norm)) return 'doc';
149
+ if (TEST_PATH_RE.test(norm)) return 'test';
150
+ return 'source';
151
+ }
152
+
153
+ function getQueryRoleIntents(query) {
154
+ const q = String(query || '').toLowerCase();
155
+ return {
156
+ wantsDocs: /\b(readme|changelog|docs|documentation|markdown|guide)\b|\.md\b|文件|說明/.test(q),
157
+ wantsTests: /\b(tests?|specs?|pytest|unittest|jest|vitest)\b|測試/.test(q)
158
+ };
159
+ }
160
+
161
+ function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
162
+ const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
163
+ if (lines.length <= 45) {
164
+ return {
165
+ windowedCode: content,
166
+ ranges: [[1, Math.max(1, lines.length)]],
167
+ tokens: estimateTokens(content)
168
+ };
169
+ }
170
+ const matchedLines = [];
171
+ if (queryTerms && queryTerms.length > 0) {
172
+ for (let i = 0; i < lines.length; i++) {
173
+ const lower = lines[i].toLowerCase();
174
+ if (queryTerms.some((t) => lower.includes(t))) {
175
+ matchedLines.push(i + 1);
176
+ if (matchedLines.length >= 3) break;
177
+ }
178
+ }
179
+ }
180
+ const rawRanges = matchedLines.length > 0
181
+ ? matchedLines.slice(0, 2).map((ln) => [Math.max(1, ln - radius), Math.min(lines.length, ln + radius)])
182
+ : [[1, Math.min(lines.length, 24)]];
183
+ const merged = mergeLineRanges(rawRanges);
184
+ const parts = [];
185
+ const usedRanges = [];
186
+ let accTokens = 0;
187
+ for (let idx = 0; idx < merged.length; idx++) {
188
+ const s = merged[idx][0];
189
+ const e = merged[idx][1];
190
+ const sliceLines = [];
191
+ let endWritten = s - 1;
192
+ for (let ln = s; ln <= e; ln++) {
193
+ const candidate = lines[ln - 1];
194
+ const tk = estimateTokens(candidate);
195
+ if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
196
+ sliceLines.push(candidate);
197
+ accTokens += tk;
198
+ endWritten = ln;
199
+ }
200
+ if (sliceLines.length === 0) break;
201
+ if (idx > 0 && usedRanges.length > 0) {
202
+ const prevEnd = usedRanges[usedRanges.length - 1][1];
203
+ if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
204
+ }
205
+ parts.push(sliceLines.join('\n'));
206
+ usedRanges.push([s, endWritten]);
207
+ if (accTokens >= maxTokens) break;
208
+ }
209
+ if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < lines.length) {
210
+ parts.push('<!-- ... ' + (lines.length - usedRanges[usedRanges.length - 1][1]) + ' remaining doc lines omitted ... -->');
211
+ }
212
+ const windowedCode = parts.join('\n');
213
+ return {
214
+ windowedCode,
215
+ ranges: usedRanges.length > 0 ? usedRanges : [[1, Math.min(lines.length, 20)]],
216
+ tokens: estimateTokens(windowedCode)
217
+ };
218
+ }
219
+
220
+ function findPythonSignatureEndIdx(lines, startIdx) {
221
+ let paren = 0, bracket = 0, brace = 0;
222
+ const maxScan = Math.min(lines.length - 1, startIdx + 25);
223
+ for (let j = startIdx; j <= maxScan; j++) {
224
+ const raw = lines[j];
225
+ let k = 0;
226
+ while (k < raw.length) {
227
+ const ch = raw[k];
228
+ if (ch === '#') break;
229
+ if (ch === '"' || ch === "'") {
230
+ const quote = ch;
231
+ k++;
232
+ while (k < raw.length) {
233
+ if (raw[k] === '\\') { k += 2; continue; }
234
+ if (raw[k] === quote) { k++; break; }
235
+ k++;
236
+ }
237
+ continue;
238
+ }
239
+ if (ch === '(') paren++;
240
+ else if (ch === ')') paren = Math.max(0, paren - 1);
241
+ else if (ch === '[') bracket++;
242
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
243
+ else if (ch === '{') brace++;
244
+ else if (ch === '}') brace = Math.max(0, brace - 1);
245
+ k++;
246
+ }
247
+ const noComment = raw.replace(/#.*$/, '').trimEnd();
248
+ if (paren <= 0 && bracket <= 0 && brace <= 0 && noComment.endsWith(':')) return j;
249
+ }
250
+ return startIdx;
251
+ }
252
+
253
+ function findPythonBlockEndIdx(lines, sigEndIdx, baseIndent) {
254
+ let end = sigEndIdx;
255
+ let inTriple = null;
256
+ for (let j = sigEndIdx + 1; j < lines.length; j++) {
257
+ const raw = lines[j];
258
+ const trimmed = raw.trim();
259
+ if (inTriple) {
260
+ end = j;
261
+ if ((raw.split(inTriple).length - 1) % 2 === 1) inTriple = null;
262
+ continue;
263
+ }
264
+ if (trimmed === '') { end = j; continue; }
265
+ const indent = (raw.match(/^\s*/) || [''])[0].length;
266
+ if (indent <= baseIndent) break;
267
+ end = j;
268
+ const tm = trimmed.match(/^("""|''')/);
269
+ if (tm && (trimmed.split(tm[1]).length - 1) % 2 === 1) inTriple = tm[1];
270
+ }
271
+ while (end > sigEndIdx && lines[end].trim() === '') end--;
272
+ return end;
273
+ }
274
+
275
+ function buildPythonClassSkeleton(fullClassCode, classStartLine = 1, expandedMethodRanges = []) {
276
+ const lines = String(fullClassCode || '').split('\n');
277
+ if (lines.length <= 4) return fullClassCode;
278
+ let classDefRel = 0;
279
+ while (classDefRel < lines.length && lines[classDefRel].trimStart().startsWith('@')) classDefRel++;
280
+ if (classDefRel >= lines.length) return fullClassCode;
281
+
282
+ const classIndent = (lines[classDefRel].match(/^\s*/) || [''])[0].length;
283
+ const classSigEndRel = findPythonSignatureEndIdx(lines, classDefRel);
284
+ const out = [];
285
+ for (let i = 0; i <= classSigEndRel; i++) out.push(lines[i]);
286
+
287
+ let bodyIdx = classSigEndRel + 1;
288
+ while (bodyIdx < lines.length && lines[bodyIdx].trim() === '') bodyIdx++;
289
+ if (bodyIdx < lines.length) {
290
+ const t = lines[bodyIdx].trim();
291
+ if (t.startsWith('"""') || t.startsWith("'''")) {
292
+ const q = t.slice(0, 3);
293
+ if (t.length > 3 && t.slice(3).includes(q)) {
294
+ out.push(lines[bodyIdx]);
295
+ bodyIdx++;
296
+ } else {
297
+ let docEnd = bodyIdx;
298
+ for (let j = bodyIdx + 1; j < lines.length; j++) {
299
+ if (lines[j].includes(q)) { docEnd = j; break; }
300
+ }
301
+ if (docEnd - bodyIdx <= 4) {
302
+ for (let j = bodyIdx; j <= docEnd; j++) out.push(lines[j]);
303
+ } else {
304
+ out.push(lines[bodyIdx]);
305
+ out.push(lines[bodyIdx + 1]);
306
+ const indentStr = (lines[bodyIdx].match(/^\s*/) || [' '])[0];
307
+ out.push(indentStr + '... (' + (docEnd - bodyIdx - 1) + ' docstring lines folded)');
308
+ out.push(lines[docEnd]);
309
+ }
310
+ bodyIdx = docEnd + 1;
311
+ }
312
+ }
313
+ }
314
+
315
+ let methodIndent = null;
316
+ let memberCount = 0;
317
+ for (let i = bodyIdx; i < lines.length; i++) {
318
+ const raw = lines[i];
319
+ const trimmed = raw.trim();
320
+ if (!trimmed || trimmed.startsWith('#')) continue;
321
+ const indent = (raw.match(/^\s*/) || [''])[0].length;
322
+ if (indent <= classIndent) continue;
323
+
324
+ if (trimmed.startsWith('@') && (methodIndent === null || indent === methodIndent)) {
325
+ let k = i + 1;
326
+ while (k < lines.length && lines[k].trimStart().startsWith('@')) k++;
327
+ if (k < lines.length && /^(?:async\s+)?def\s+/.test(lines[k].trim())) {
328
+ if (methodIndent === null) methodIndent = indent;
329
+ for (let d = i; d < k; d++) out.push(lines[d]);
330
+ i = k - 1;
331
+ continue;
332
+ }
333
+ }
334
+
335
+ const dm = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
336
+ if (dm && (methodIndent === null || indent === methodIndent)) {
337
+ methodIndent = indent;
338
+ memberCount++;
339
+ const mSigEnd = findPythonSignatureEndIdx(lines, i);
340
+ const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
341
+ const absStart = classStartLine + i;
342
+ const absEnd = classStartLine + mEnd;
343
+ const hit = expandedMethodRanges.find((r) => r.startLine <= absEnd && r.endLine >= absStart);
344
+ for (let s = i; s <= mSigEnd; s++) {
345
+ if (s === mSigEnd) {
346
+ const folded = Math.max(1, mEnd - mSigEnd);
347
+ const note = hit
348
+ ? ' # [expanded in <focal symbol="' + hit.name + '"> below]'
349
+ : ' # ... ' + folded + ' lines folded';
350
+ out.push(lines[s] + note);
351
+ } else {
352
+ out.push(lines[s]);
353
+ }
354
+ }
355
+ i = mEnd;
356
+ continue;
357
+ }
358
+
359
+ if (methodIndent === null || indent <= methodIndent) {
360
+ if (/^[A-Za-z_][A-Za-z0-9_]*\s*(?::[^=]+)?(?:=.*)?$/.test(trimmed)) {
361
+ out.push(raw);
362
+ memberCount++;
363
+ }
364
+ }
365
+ }
366
+
367
+ if (memberCount === 0) {
368
+ return lines.length > 4
369
+ ? lines.slice(0, classSigEndRel + 1).join('\n') + '\n # ... ' + (lines.length - classSigEndRel - 1) + ' lines folded'
370
+ : fullClassCode;
371
+ }
372
+ return out.join('\n');
373
+ }
374
+
375
+ function extractPythonBlocks(lines, lineIdx) {
376
+ const line = lines[lineIdx];
377
+ const m = line.match(/^(async\s+def|def|class)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
378
+ if (!m) return null;
379
+
380
+ const kind = m[1] === 'class' ? 'class' : 'function';
381
+ const name = m[2];
382
+ let startIdx = lineIdx;
383
+ while (startIdx > 0 && /^@[A-Za-z_]/.test(lines[startIdx - 1])) startIdx--;
384
+ const startLine = startIdx + 1;
385
+ const sigEndIdx = findPythonSignatureEndIdx(lines, lineIdx);
386
+ const endIdx = findPythonBlockEndIdx(lines, sigEndIdx, 0);
387
+ const endLine = endIdx + 1;
388
+ const full = lines.slice(startIdx, endIdx + 1).join('\n');
389
+ const results = [];
390
+
391
+ if (kind === 'class') {
392
+ results.push({
393
+ name,
394
+ kind: 'class',
395
+ exported: !name.startsWith('_'),
396
+ startLine,
397
+ endLine,
398
+ full,
399
+ skeleton: buildPythonClassSkeleton(full, startLine)
400
+ });
401
+ let methodIndent = null;
402
+ for (let mIdx = sigEndIdx + 1; mIdx <= endIdx; mIdx++) {
403
+ const mLine = lines[mIdx];
404
+ const mTrimmed = mLine.trim();
405
+ if (!mTrimmed || mTrimmed.startsWith('#')) continue;
406
+ const indent = (mLine.match(/^\s*/) || [''])[0].length;
407
+ if (indent <= 0) continue;
408
+ const dm = mTrimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
409
+ if (!dm) continue;
410
+ if (methodIndent === null) methodIndent = indent;
411
+ if (indent !== methodIndent) continue;
412
+ const methodName = dm[1];
413
+ let mStartIdx = mIdx;
414
+ while (
415
+ mStartIdx > sigEndIdx + 1 &&
416
+ lines[mStartIdx - 1].trimStart().startsWith('@') &&
417
+ (lines[mStartIdx - 1].match(/^\s*/) || [''])[0].length === indent
418
+ ) {
419
+ mStartIdx--;
420
+ }
421
+ const mSigEnd = findPythonSignatureEndIdx(lines, mIdx);
422
+ const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
423
+ const mFull = lines.slice(mStartIdx, mEnd + 1).join('\n');
424
+ const mFolded = Math.max(1, mEnd - mSigEnd);
425
+ const indentStr = (mLine.match(/^\s*/) || [' '])[0];
426
+ const mSigLines = lines.slice(mStartIdx, mSigEnd + 1).join('\n');
427
+ const mSkel = mEnd - mSigEnd > 2 ? mSigLines + '\n' + indentStr + ' # ... ' + mFolded + ' lines folded' : mFull;
428
+ results.push({
429
+ name: name + '.' + methodName,
430
+ kind: 'method',
431
+ exported: !name.startsWith('_') && !methodName.startsWith('_'),
432
+ startLine: mStartIdx + 1,
433
+ endLine: mEnd + 1,
434
+ full: mFull,
435
+ skeleton: mSkel
436
+ });
437
+ mIdx = mEnd;
438
+ }
439
+ } else {
440
+ const sigLines = lines.slice(startIdx, sigEndIdx + 1).join('\n');
441
+ const skeleton = endIdx - sigEndIdx > 2 ? sigLines + '\n # ... ' + (endIdx - sigEndIdx) + ' lines folded' : full;
442
+ results.push({
443
+ name,
444
+ kind: 'function',
445
+ exported: !name.startsWith('_'),
446
+ startLine,
447
+ endLine,
448
+ full,
449
+ skeleton
450
+ });
451
+ }
452
+ return { blocks: results, endIdx };
453
+ }
454
+
455
+ function assembleContextSliceXml(opts) {
456
+ const {
457
+ blocks,
458
+ fileEntries,
459
+ fileLineCounts,
460
+ fileHeaders,
461
+ fileFooters,
462
+ rawQuery,
463
+ terms,
464
+ budget,
465
+ maxHops,
466
+ autoExpand,
467
+ rootAttr,
468
+ version,
469
+ subPathTag,
470
+ includeParserAttr,
471
+ controlWords,
472
+ maskFn
473
+ } = opts;
474
+
475
+ if (!String(rawQuery || '').trim()) {
476
+ const treeLines = buildRepositoryFileTree(fileEntries, 1800);
477
+ return [
478
+ '<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
479
+ ' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
480
+ ' <repository_file_tree>',
481
+ ...treeLines,
482
+ ' </repository_file_tree>',
483
+ '</context_slice>'
484
+ ].join('\n');
485
+ }
486
+
487
+ const roleIntents = getQueryRoleIntents(rawQuery);
488
+ const configWindowByKey = new Map();
489
+ const preparedBlocks = blocks.map((b) => {
490
+ const rel = b.filePath;
491
+ const key = rel + ':' + b.startLine;
492
+ const lineCount = Math.max(1, b.endLine - b.startLine + 1);
493
+ const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
494
+ const isDocExt = DOC_EXT_RE.test(rel);
495
+ let win = null;
496
+ if (b.kind === 'module') {
497
+ if (isConfigFile && lineCount > 200) {
498
+ win = slicePlainTextConfigWindow(b.full, terms);
499
+ } else if (isDocExt && lineCount > 45) {
500
+ win = sliceDocWindow(b.full, terms, 16, 480);
501
+ }
502
+ }
503
+ if (win) configWindowByKey.set(key, win);
504
+ const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
505
+ const skelTk = isDocExt
506
+ ? Math.min(b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton), win ? win.tokens : 480)
507
+ : (b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton));
508
+ return {
509
+ ...b,
510
+ filePath: rel,
511
+ lineCount,
512
+ role: classifyFileRole(rel),
513
+ isDocExt,
514
+ rawTk,
515
+ skelTk
516
+ };
517
+ });
518
+
519
+ const totalBlocks = Math.max(1, preparedBlocks.length);
520
+ const termDF = {};
521
+ for (const t of terms) {
522
+ let df = 0;
523
+ for (const b of preparedBlocks) {
524
+ if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
525
+ df++;
526
+ }
527
+ }
528
+ termDF[t] = Math.max(1, df);
529
+ }
530
+
531
+ const scored = preparedBlocks.map((b) => {
532
+ const nameLower = b.name.toLowerCase();
533
+ const shortLower = nameLower.includes('.') ? nameLower.split('.').pop() : nameLower;
534
+ const relLower = b.filePath.toLowerCase();
535
+ const lowerBody = b.full.toLowerCase();
536
+ let score = 0;
537
+ let matchedTerms = 0;
538
+
539
+ for (const t of terms) {
540
+ const df = termDF[t] || 1;
541
+ const idf = Math.log(1 + (totalBlocks / df));
542
+ const scarcity = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
543
+ let termScore = 0;
544
+ let hit = false;
545
+ if (nameLower === t || shortLower === t) { termScore += 48; hit = true; }
546
+ else if (nameLower.includes(t)) { termScore += 24; hit = true; }
547
+ if (relLower.includes(t)) { termScore += 12; hit = true; }
548
+ const bodyOcc = lowerBody.split(t).length - 1;
549
+ if (bodyOcc > 0) { termScore += Math.min(12, 3 * Math.log1p(bodyOcc)); hit = true; }
550
+ if (hit) matchedTerms++;
551
+ score += termScore * idf * scarcity;
552
+ }
553
+
554
+ if (matchedTerms >= 2) {
555
+ score *= 1 + 0.35 * (matchedTerms - 1);
556
+ }
557
+ if (score > 0 && (b.kind === 'function' || b.kind === 'method')) score *= 1.18;
558
+ else if (score > 0 && (b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' || b.kind === 'struct')) score *= 1.08;
559
+
560
+ if (score > 0) {
561
+ if (b.role === 'doc' && !roleIntents.wantsDocs) score *= 0.10;
562
+ else if (b.role === 'test' && !roleIntents.wantsTests) score *= 0.20;
563
+ else if (b.role === 'source') score *= 1.25;
564
+ }
565
+
566
+ return { ...b, score };
567
+ }).sort((a, b) => b.score - a.score);
568
+
569
+ // Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
570
+ const symbolMap = new Map();
571
+ const constSymbolNames = new Set();
572
+ for (let i = 0; i < scored.length; i++) {
573
+ const b = scored[i];
574
+ if (b.name && b.kind !== 'module' && !controlWords.has(b.name)) {
575
+ const rawShort = b.name.includes('.') ? b.name.split('.').pop() : b.name;
576
+ const names = (b.kind === 'const' && rawShort.includes(','))
577
+ ? rawShort.split(',').map((s) => s.trim()).filter(Boolean)
578
+ : [rawShort];
579
+ for (const sn of names) {
580
+ if (!sn || /^__.*__$/.test(sn)) continue;
581
+ if (!symbolMap.has(sn)) symbolMap.set(sn, []);
582
+ symbolMap.get(sn).push(i);
583
+ if (b.kind === 'const') constSymbolNames.add(sn);
584
+ }
585
+ }
586
+ }
587
+
588
+ const callAdj = Array.from({ length: scored.length }, () => new Set());
589
+ const definedNames = Array.from(symbolMap.keys());
590
+ for (let i = 0; i < scored.length; i++) {
591
+ const caller = scored[i];
592
+ const maskedCaller = maskFn(caller.full);
593
+ for (const sym of definedNames) {
594
+ const callerShort = caller.name.includes('.') ? caller.name.split('.').pop() : caller.name;
595
+ if (sym === caller.name || sym === callerShort) continue;
596
+ if (maskedCaller.includes(sym)) {
597
+ const esc = sym.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&');
598
+ const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
599
+ const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
600
+ if (re.test(maskedCaller)) {
601
+ for (const t of (symbolMap.get(sym) || [])) {
602
+ const target = scored[t];
603
+ if (caller.filePath === target.filePath && (
604
+ (caller.kind === 'class' && target.kind === 'method' && target.name.startsWith(caller.name + '.')) ||
605
+ (target.kind === 'class' && caller.kind === 'method' && caller.name.startsWith(target.name + '.'))
606
+ )) continue;
607
+ callAdj[i].add(t);
608
+ callAdj[t].add(i);
609
+ }
610
+ }
611
+ }
612
+ }
613
+ }
614
+
615
+ // Focal selection: strictly prefer source matches over docs/tests + class/method smart deduplication
616
+ const hasSourceMatches = scored.some((b) => b.role === 'source' && b.score > 0);
617
+ const eligibleIndices = [];
618
+ for (let i = 0; i < scored.length; i++) {
619
+ if (scored[i].score <= 0) continue;
620
+ if (hasSourceMatches && scored[i].role !== 'source') continue;
621
+ eligibleIndices.push(i);
622
+ }
623
+ const focalSet = new Set();
624
+ const promotedParentClassSet = new Set();
625
+ if (eligibleIndices.length > 0) {
626
+ const topScore = scored[eligibleIndices[0]].score;
627
+ const candidateIdx = eligibleIndices
628
+ .filter((idx, rank) => (rank < 3 && scored[idx].score >= topScore * 0.3) || scored[idx].score >= topScore * 0.55)
629
+ .slice(0, 5);
630
+ const candidateChosen = new Set();
631
+ for (const idx of candidateIdx) {
632
+ const b = scored[idx];
633
+ if (b.kind === 'class' && b.lineCount > 35) {
634
+ const childIndices = [];
635
+ for (let ci = 0; ci < scored.length; ci++) {
636
+ const c = scored[ci];
637
+ if (c.filePath === b.filePath && c.kind === 'method' && c.name.startsWith(b.name + '.')) {
638
+ const cShort = c.name.split('.').pop().toLowerCase();
639
+ const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
640
+ if (explicitHit || c.score >= b.score * 0.55) {
641
+ childIndices.push(ci);
642
+ }
643
+ }
644
+ }
645
+ if (childIndices.length > 0) {
646
+ promotedParentClassSet.add(idx);
647
+ for (const ci of childIndices.slice(0, 3)) candidateChosen.add(ci);
648
+ continue;
649
+ }
650
+ }
651
+ candidateChosen.add(idx);
652
+ }
653
+ for (const idx of candidateChosen) {
654
+ const b = scored[idx];
655
+ if (b.kind === 'method') {
656
+ const clsName = b.name.split('.')[0];
657
+ const hasFullParent = [...candidateChosen].some((pIdx) => {
658
+ const p = scored[pIdx];
659
+ return p && p.kind === 'class' && p.filePath === b.filePath && p.name === clsName;
660
+ });
661
+ if (hasFullParent) continue;
662
+ }
663
+ focalSet.add(idx);
664
+ }
665
+ }
666
+
667
+ // BFS from final focalSet
668
+ const hopDistances = new Map();
669
+ const focalFiles = new Set();
670
+ const bfsQ = [...focalSet];
671
+ for (const fi of bfsQ) {
672
+ hopDistances.set(fi, 0);
673
+ focalFiles.add(scored[fi].filePath);
674
+ }
675
+ let qHead = 0;
676
+ while (qHead < bfsQ.length) {
677
+ const curr = bfsQ[qHead++];
678
+ const curHop = hopDistances.get(curr) ?? 0;
679
+ if (curHop >= maxHops) continue;
680
+ for (const nbr of callAdj[curr]) {
681
+ if (!hopDistances.has(nbr)) {
682
+ hopDistances.set(nbr, curHop + 1);
683
+ bfsQ.push(nbr);
684
+ }
685
+ }
686
+ }
687
+
688
+ // Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, then 1/2-hop source -> test -> doc
689
+ const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
690
+ const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
691
+ const focA = focalSet.has(a) ? 0 : 1;
692
+ const focB = focalSet.has(b) ? 0 : 1;
693
+ if (focA !== focB) return focA - focB;
694
+ const parA = promotedParentClassSet.has(a) ? 0 : 1;
695
+ const parB = promotedParentClassSet.has(b) ? 0 : 1;
696
+ if (parA !== parB) return parA - parB;
697
+ const rrA = roleRank(scored[a].role);
698
+ const rrB = roleRank(scored[b].role);
699
+ if (rrA !== rrB) return rrA - rrB;
700
+ const hopA = hopDistances.get(a) ?? 99;
701
+ const hopB = hopDistances.get(b) ?? 99;
702
+ if (hopA !== hopB) return hopA - hopB;
703
+ return scored[b].score - scored[a].score;
704
+ });
705
+
706
+ let remaining = budget;
707
+ let docBudgetUsed = 0;
708
+ let testBudgetUsed = 0;
709
+ const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
710
+ const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
711
+ const dirBudgetUsed = {};
712
+ const maxDirBudget = budget * 0.72;
713
+
714
+ const includedIds = new Set();
715
+ const includedFiles = [];
716
+ const includedFilesSet = new Set();
717
+ const fullStart1EndLine = new Map();
718
+ const coveredRangesByFile = new Map();
719
+ const partialFiles = new Set();
720
+ const selectedByFile = new Map();
721
+ const fullParentClassesByFile = new Map();
722
+ const skelCandidates = [];
723
+ const candidateItems = [];
724
+
725
+ const addCoveredRange = (fp, s, e) => {
726
+ if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
727
+ coveredRangesByFile.get(fp).push([s, e]);
728
+ };
729
+ const addSelectedBlock = (fp, entry) => {
730
+ if (!includedFilesSet.has(fp)) {
731
+ includedFilesSet.add(fp);
732
+ includedFiles.push(fp);
733
+ }
734
+ if (!selectedByFile.has(fp)) selectedByFile.set(fp, []);
735
+ selectedByFile.get(fp).push(entry);
736
+ };
737
+ const canUseRoleBudget = (role, cost) => {
738
+ if (role === 'doc') return docBudgetUsed + cost <= docBudgetCap;
739
+ if (role === 'test') return testBudgetUsed + cost <= testBudgetCap;
740
+ return true;
741
+ };
742
+ const addRoleBudget = (role, cost) => {
743
+ if (role === 'doc') docBudgetUsed += cost;
744
+ else if (role === 'test') testBudgetUsed += cost;
745
+ };
746
+
747
+ for (const idx of allocOrder) {
748
+ const item = scored[idx];
749
+ if (item.kind === 'method') {
750
+ const clsName = item.name.split('.')[0];
751
+ const fullSet = fullParentClassesByFile.get(item.filePath);
752
+ if (fullSet && fullSet.has(clsName)) continue;
753
+ }
754
+
755
+ const topDir = item.filePath.split('/')[0] || 'root';
756
+ const curDir = dirBudgetUsed[topDir] || 0;
757
+ const hop = hopDistances.get(idx);
758
+ const isFocal = focalSet.has(idx);
759
+ const isPromotedParent = promotedParentClassSet.has(idx);
760
+ const key = item.filePath + ':' + item.startLine;
761
+ const win = configWindowByKey.get(key);
762
+
763
+ if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
764
+ remaining = Math.max(0, remaining - item.rawTk);
765
+ dirBudgetUsed[topDir] = curDir + item.rawTk;
766
+ addRoleBudget(item.role, item.rawTk);
767
+ includedIds.add(key);
768
+ if (item.kind === 'class') {
769
+ if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, new Set());
770
+ fullParentClassesByFile.get(item.filePath).add(item.name);
771
+ }
772
+ if (win) {
773
+ for (const r of win.ranges) {
774
+ addCoveredRange(item.filePath, r[0], r[1]);
775
+ if (r[0] === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, r[1]));
776
+ }
777
+ } else {
778
+ addCoveredRange(item.filePath, item.startLine, item.endLine);
779
+ if (item.startLine === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
780
+ }
781
+ addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
782
+ } else if (isPromotedParent && item.skelTk <= remaining) {
783
+ remaining -= item.skelTk;
784
+ dirBudgetUsed[topDir] = curDir + item.skelTk;
785
+ includedIds.add(key);
786
+ partialFiles.add(item.filePath);
787
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
788
+ } else if (item.skelTk <= remaining && (curDir + item.skelTk <= maxDirBudget || item.role === 'source') && canUseRoleBudget(item.role, item.skelTk)) {
789
+ const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
790
+ const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
791
+ if (linked) {
792
+ remaining -= item.skelTk;
793
+ dirBudgetUsed[topDir] = curDir + item.skelTk;
794
+ addRoleBudget(item.role, item.skelTk);
795
+ includedIds.add(key);
796
+ partialFiles.add(item.filePath);
797
+ if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
798
+ if (autoExpand && item.role === 'source' && !isPromotedParent) {
799
+ skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
800
+ } else {
801
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
802
+ }
803
+ } else {
804
+ partialFiles.add(item.filePath);
805
+ candidateItems.push(item);
806
+ }
807
+ } else {
808
+ partialFiles.add(item.filePath);
809
+ candidateItems.push(item);
810
+ }
811
+ }
812
+
813
+ const autoExpandedNames = [];
814
+ if (autoExpand && skelCandidates.length > 0) {
815
+ for (const cand of skelCandidates) {
816
+ const it = cand.item;
817
+ const delta = Math.max(0, it.rawTk - it.skelTk);
818
+ const isComplexCluster = (cand.hop !== null || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
819
+ const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
820
+ if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
821
+ remaining -= delta;
822
+ autoExpandedNames.push(it.name);
823
+ if (cand.win) {
824
+ for (const r of cand.win.ranges) {
825
+ addCoveredRange(it.filePath, r[0], r[1]);
826
+ if (r[0] === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, r[1]));
827
+ }
828
+ } else {
829
+ addCoveredRange(it.filePath, it.startLine, it.endLine);
830
+ if (it.startLine === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, it.endLine));
831
+ }
832
+ addSelectedBlock(it.filePath, { tier: 'full', item: it, win: cand.win, autoExpanded: true });
833
+ } else {
834
+ addSelectedBlock(it.filePath, { tier: 'skeleton', item: it, win: cand.win, hop: cand.hop });
835
+ }
836
+ }
837
+ }
838
+
839
+ if (includedFiles.length === 0) {
840
+ const treeLines = buildRepositoryFileTree(fileEntries, 1800);
841
+ return [
842
+ '<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
843
+ ' <note>WARNING: 0 matches found for query "' + escapeXmlText(rawQuery) + '". Do NOT guess code from this file tree alone—pick valid file paths or symbol names from the tree below and call context_slice again.</note>',
844
+ ' <repository_file_tree>',
845
+ ...treeLines,
846
+ ' </repository_file_tree>',
847
+ '</context_slice>'
848
+ ].join('\n');
849
+ }
850
+
851
+ const headerByFile = new Map();
852
+ const headerEndByFile = new Map();
853
+ for (const fp of includedFiles) {
854
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
855
+ const entries = selectedByFile.get(fp) || [];
856
+ const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
857
+ if (hasStart1ModuleSkel) continue;
858
+ const hdr = fileHeaders.get(fp);
859
+ if (!hdr) continue;
860
+ if ((fullStart1EndLine.get(fp) || 0) >= hdr.endLine) continue;
861
+ headerEndByFile.set(fp, hdr.endLine);
862
+ headerByFile.set(fp, hdr);
863
+ }
864
+
865
+ const footerByFile = new Map();
866
+ for (const fp of includedFiles) {
867
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
868
+ const ftr = fileFooters.get(fp);
869
+ if (!ftr) continue;
870
+ const ranges = coveredRangesByFile.get(fp) || [];
871
+ const totalLines = fileLineCounts.get(fp) || 0;
872
+ const wholeFileCovered = ranges.some((r) => r[0] <= 1 && r[1] >= totalLines);
873
+ if (!partialFiles.has(fp) && wholeFileCovered) continue;
874
+ const hdrEnd = headerEndByFile.get(fp) || 0;
875
+ const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some((r) => c.startLine >= r[0] && c.endLine <= r[1]));
876
+ if (uncovered.length > 0) {
877
+ footerByFile.set(fp, {
878
+ startLine: uncovered[0].startLine,
879
+ endLine: uncovered[uncovered.length - 1].endLine,
880
+ text: uncovered.map((c) => c.text).join('\n'),
881
+ chunks: uncovered
882
+ });
883
+ }
884
+ }
885
+
886
+ const used = Math.max(0, budget - remaining);
887
+ const expandAttr = autoExpandedNames.length > 0 ? ' autoExpanded="' + escapeXmlAttr(autoExpandedNames.join(',')) + '"' : '';
888
+ const out = [
889
+ '<context_slice mode="progressive-structural-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + used + '"' + expandAttr + '>'
890
+ ];
891
+
892
+ for (const fp of includedFiles) {
893
+ const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
894
+ const presentClassNames = new Set(rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item.name));
895
+ const entries = rawEntries.filter(
896
+ (e) => !(e.tier === 'skeleton' && e.item.kind === 'method' && presentClassNames.has(e.item.name.split('.')[0])),
897
+ );
898
+ const fullEntries = entries.filter((e) => e.tier === 'full');
899
+ const hdr = headerByFile.get(fp);
900
+ const ftr = footerByFile.get(fp);
901
+ const totalLines = fileLineCounts.get(fp) || 0;
902
+ const shownRanges = [];
903
+ if (hdr) shownRanges.push([1, hdr.endLine]);
904
+ for (const ent of entries) {
905
+ if (ent.win) shownRanges.push(...ent.win.ranges);
906
+ else shownRanges.push([ent.item.startLine, ent.item.endLine]);
907
+ }
908
+ if (ftr) {
909
+ for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
910
+ }
911
+ out.push(' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRanges) + '">');
912
+ if (hdr) {
913
+ out.push(' <file_header lines="1-' + hdr.endLine + '">');
914
+ out.push(hdr.header);
915
+ out.push(' </file_header>');
916
+ }
917
+ for (const ent of entries) {
918
+ const it = ent.item;
919
+ if (ent.tier === 'full') {
920
+ const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
921
+ const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
922
+ const autoAttr = ent.autoExpanded ? ' autoExpanded="true"' : '';
923
+ out.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + linesAttr + '"' + parserAttr + autoAttr + '>');
924
+ out.push(ent.win ? ent.win.windowedCode : it.full);
925
+ out.push(' </focal>');
926
+ } else {
927
+ let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
928
+ if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
929
+ const expandedChildRanges = fullEntries
930
+ .filter((fe) => fe.item.kind === 'method' && fe.item.name.startsWith(it.name + '.'))
931
+ .map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
932
+ if (expandedChildRanges.length > 0) {
933
+ skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
934
+ }
935
+ }
936
+ const hopAttr = (ent.hop !== null && ent.hop !== undefined) ? ' hop="' + ent.hop + '"' : '';
937
+ const skelLinesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
938
+ out.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + skelLinesAttr + '"' + hopAttr + '>');
939
+ out.push(skelBody);
940
+ out.push(' </skeleton>');
941
+ }
942
+ }
943
+ if (ftr) {
944
+ out.push(' <file_footer lines="' + ftr.startLine + '-' + ftr.endLine + '">');
945
+ out.push(ftr.text);
946
+ out.push(' </file_footer>');
947
+ }
948
+ out.push(' </file>');
949
+ }
950
+
951
+ const omitted = candidateItems.filter((it) => it.score > 0 && !includedIds.has(it.filePath + ':' + it.startLine)).slice(0, 3);
952
+ if (omitted.length > 0) {
953
+ out.push(' <omitted_top_matches>');
954
+ for (const o of omitted) {
955
+ out.push(' <!-- Omitted: ' + o.filePath + ':' + o.startLine + ' (' + o.name + ', score: ' + o.score.toFixed(1) + ') — consider expanding -->');
956
+ }
957
+ out.push(' </omitted_top_matches>');
958
+ }
959
+
960
+ out.push('</context_slice>');
961
+ return out.join('\n');
962
+ }
137
963
 
138
964
 
139
965
  const CJK_RE = /[一-鿿぀-ゟ゠-ヿ가-힯]/;
@@ -517,12 +1343,14 @@ function expandQueryTerms(query) {
517
1343
  for (const term of snapshot) {
518
1344
  for (const t of bilingualLookup(term)) terms.add(t);
519
1345
  }
520
- return [...terms].filter(Boolean);
1346
+ const collected = [...terms].filter(Boolean);
1347
+ const nonSyntax = collected.filter((t) => !SYNTAX_NOISE_WORDS.has(t));
1348
+ return nonSyntax.length > 0 ? nonSyntax : collected;
521
1349
  }
522
1350
 
523
1351
  const TOOL_DEF = {
524
1352
  name: 'get_context_slice',
525
- description: 'PRIMARY code-reading tool (v0.4.0) with Tree-sitter WASM / State-Machine structural parsing, True Call Graph, TF-IDF & Dual-State File Tree.',
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.',
526
1354
  annotations: { readOnlyHint: true },
527
1355
  inputSchema: {
528
1356
  type: 'object',
@@ -723,24 +1551,49 @@ async function extractBlocksWithTreeSitter(code, ext, fileName) {
723
1551
  if (!bodyCap || !nameCap) continue;
724
1552
  const startLine = bodyCap.node.startPosition.row + 1;
725
1553
  const endLine = bodyCap.node.endPosition.row + 1;
726
- const name = String(nameCap.node.text || '').trim();
727
- const key = name + '@' + startLine + '-' + endLine;
728
- if (!name || seen.has(key)) continue;
729
- seen.add(key);
1554
+ const rawName = String(nameCap.node.text || '').trim();
1555
+ if (!rawName) continue;
730
1556
 
731
1557
  const nodeType = bodyCap.node.type || 'function';
732
- const kind = nodeType.includes('class') ? 'class'
1558
+ let name = rawName;
1559
+ let kind = nodeType.includes('class') ? 'class'
733
1560
  : nodeType.includes('interface') ? 'interface'
734
1561
  : nodeType.includes('struct') ? 'struct'
735
1562
  : nodeType.includes('impl') ? 'impl'
736
1563
  : nodeType.includes('method') ? 'method'
737
1564
  : 'function';
738
1565
 
1566
+ if (langName === 'python' && nodeType === 'function_definition') {
1567
+ let p = bodyCap.node.parent;
1568
+ while (p) {
1569
+ if (p.type === 'class_definition') {
1570
+ const clsNameNode = p.childForFieldName ? p.childForFieldName('name') : null;
1571
+ const clsName = clsNameNode ? String(clsNameNode.text || '').trim() : '';
1572
+ if (clsName) {
1573
+ name = `${clsName}.${rawName}`;
1574
+ kind = 'method';
1575
+ }
1576
+ break;
1577
+ }
1578
+ p = p.parent;
1579
+ }
1580
+ }
1581
+
1582
+ const key = name + '@' + startLine + '-' + endLine;
1583
+ if (seen.has(key)) continue;
1584
+ seen.add(key);
1585
+
739
1586
  const full = lines.slice(startLine - 1, endLine).join('\n');
740
1587
  let skeleton = full;
741
- if (endLine - startLine >= 3) {
1588
+ if (langName === 'python' && kind === 'class') {
1589
+ skeleton = buildPythonClassSkeleton(full, startLine);
1590
+ } else if (endLine - startLine >= 3) {
742
1591
  if (langName === 'python') {
743
- skeleton = `${lines[startLine - 1]}\n # ... ${endLine - startLine} lines folded`;
1592
+ const sigEndIdx = findPythonSignatureEndIdx(lines, startLine - 1);
1593
+ const indentStr = (lines[startLine - 1].match(/^\s*/) || [''])[0];
1594
+ const sigText = lines.slice(startLine - 1, sigEndIdx + 1).join('\n');
1595
+ const foldedLines = Math.max(1, endLine - (sigEndIdx + 1));
1596
+ skeleton = foldedLines > 2 ? `${sigText}\n${indentStr} # ... ${foldedLines} lines folded` : full;
744
1597
  } else {
745
1598
  const sigIdx = full.indexOf('{');
746
1599
  if (sigIdx !== -1 && kind !== 'interface') {
@@ -807,20 +1660,10 @@ function extractBlocks(code, ext, fileName) {
807
1660
  let m = null;
808
1661
 
809
1662
  if (e === '.py' || e === '.pyw') {
810
- m = line.match(/^(?:async\s+)?(def|class)\s+([A-Za-z_][A-Za-z0-9_]*)/);
811
- if (m) {
812
- name = m[2];
813
- kind = m[1] === 'class' ? 'class' : 'function';
814
- let end = i;
815
- for (let j = i + 1; j < lines.length; j++) {
816
- if (lines[j].trim() === '' || /^\s+/.test(lines[j])) end = j;
817
- else break;
818
- }
819
- while (end > i && lines[end].trim() === '') end--;
820
- const full = lines.slice(i, end + 1).join('\n');
821
- const skeleton = end - i > 2 ? `${lines[i]}\n # ... ${end - i} lines folded` : full;
822
- blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
823
- i = end;
1663
+ const pyRes = extractPythonBlocks(lines, i);
1664
+ if (pyRes) {
1665
+ blocks.push(...pyRes.blocks);
1666
+ i = pyRes.endIdx;
824
1667
  continue;
825
1668
  }
826
1669
  }
@@ -1373,29 +2216,33 @@ async function collectProjectBlocks(root, scanRoot) {
1373
2216
  let fileHeader = null;
1374
2217
  let fileFooter = null;
1375
2218
  let fileLines = 0;
1376
- const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
2219
+ const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rel) || DOC_EXT_RE.test(rel);
1377
2220
  if (cached && cached.mtime === mtime) {
1378
2221
  items = cached.items;
1379
2222
  parserMode = cached.parserMode || 'regex';
1380
- fileHeader = isConfigFile ? null : (cached.header ?? null);
1381
- fileFooter = isConfigFile ? null : (cached.footer ?? null);
2223
+ fileHeader = skipHdrFtr ? null : (cached.header ?? null);
2224
+ fileFooter = skipHdrFtr ? null : (cached.footer ?? null);
1382
2225
  fileLines = cached.lineCount || 0;
1383
2226
  } else {
1384
2227
  const rawBuf = fs.readFileSync(f);
1385
2228
  if (isBinaryBuffer(rawBuf)) continue;
1386
2229
  const raw = rawBuf.toString('utf8');
1387
2230
  fileLines = raw.replace(/\r\n/g, '\n').split('\n').length;
1388
- fileHeader = isConfigFile ? null : extractFileHeader(raw);
1389
- fileFooter = isConfigFile ? null : extractFileFooter(raw);
2231
+ fileHeader = skipHdrFtr ? null : extractFileHeader(raw);
2232
+ fileFooter = skipHdrFtr ? null : extractFileFooter(raw);
1390
2233
  const ext = path.extname(f);
1391
- const tsBlocks = isConfigFile ? null : await extractBlocksWithTreeSitter(raw, ext, rel);
2234
+ const tsBlocks = skipHdrFtr ? null : await extractBlocksWithTreeSitter(raw, ext, rel);
1392
2235
  if (tsBlocks && tsBlocks.length > 0) {
1393
2236
  const extraConsts = extractTopLevelConstants(raw, ext, tsBlocks);
1394
2237
  items = extraConsts.length > 0 ? [...tsBlocks, ...extraConsts].sort((a, b) => a.startLine - b.startLine) : tsBlocks;
1395
2238
  parserMode = 'tree-sitter-wasm';
1396
2239
  } else {
1397
2240
  items = extractBlocks(raw, ext, rel);
1398
- parserMode = isConfigFile ? 'plain-text-config' : 'state-machine-regex';
2241
+ parserMode = PLAIN_TEXT_CONFIG_EXT_RE.test(rel)
2242
+ ? 'plain-text-config'
2243
+ : DOC_EXT_RE.test(rel)
2244
+ ? 'markdown-doc'
2245
+ : 'state-machine-regex';
1399
2246
  }
1400
2247
  FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
1401
2248
  }
@@ -1407,6 +2254,7 @@ async function collectProjectBlocks(root, scanRoot) {
1407
2254
  for (const b of items) {
1408
2255
  allBlocks.push({
1409
2256
  ...b,
2257
+ filePath: rel,
1410
2258
  rel,
1411
2259
  parserMode,
1412
2260
  lineCount: Math.max(1, b.endLine - b.startLine + 1),
@@ -1518,324 +2366,46 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1518
2366
  // State A: Empty query -> return repository file tree overview (~1K-2K tokens)
1519
2367
  if (!rawQuery.trim()) {
1520
2368
  const fileEntries = collectFileOverview(root, scanRoot);
1521
- const treeLines = buildRepositoryFileTree(fileEntries, 1800);
1522
- return [
1523
- `<context_slice mode="file_tree_empty_query" root="${escapeXmlAttr(root)}" version="0.4.0"${subPathTag} total_files="${fileEntries.length}">`,
1524
- ' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
1525
- ' <repository_file_tree>',
1526
- ...treeLines,
1527
- ' </repository_file_tree>',
1528
- '</context_slice>'
1529
- ].join('\n');
2369
+ return assembleContextSliceXml({
2370
+ blocks: [],
2371
+ fileEntries,
2372
+ fileLineCounts: new Map(),
2373
+ fileHeaders: new Map(),
2374
+ fileFooters: new Map(),
2375
+ rawQuery,
2376
+ terms: [],
2377
+ budget,
2378
+ maxHops: 2,
2379
+ autoExpand,
2380
+ rootAttr: root,
2381
+ version: '0.4.1',
2382
+ subPathTag,
2383
+ includeParserAttr: true,
2384
+ controlWords: CONTROL_WORDS,
2385
+ maskFn: maskCommentsAndStrings
2386
+ });
1530
2387
  }
1531
2388
 
1532
2389
  const terms = expandQueryTerms(rawQuery);
1533
2390
  const { blocks, headerMap, footerMap, lineCountMap, fileEntries } = await collectProjectBlocks(root, scanRoot);
1534
-
1535
- const configWindowByKey = new Map();
1536
- const preparedBlocks = blocks.map((b) => {
1537
- const key = b.rel + ':' + b.startLine;
1538
- if (PLAIN_TEXT_CONFIG_EXT_RE.test(b.rel) && b.kind === 'module' && b.lineCount > 200) {
1539
- const win = slicePlainTextConfigWindow(b.full, terms);
1540
- if (win) {
1541
- configWindowByKey.set(key, win);
1542
- return { ...b, rawTk: win.tokens };
1543
- }
1544
- }
1545
- return b;
2391
+ return assembleContextSliceXml({
2392
+ blocks,
2393
+ fileEntries,
2394
+ fileLineCounts: lineCountMap,
2395
+ fileHeaders: headerMap,
2396
+ fileFooters: footerMap,
2397
+ rawQuery,
2398
+ terms,
2399
+ budget,
2400
+ maxHops: 2,
2401
+ autoExpand,
2402
+ rootAttr: root,
2403
+ version: '0.4.1',
2404
+ subPathTag,
2405
+ includeParserAttr: true,
2406
+ controlWords: CONTROL_WORDS,
2407
+ maskFn: maskCommentsAndStrings
1546
2408
  });
1547
-
1548
- const totalBlocks = Math.max(1, preparedBlocks.length);
1549
- const termDF = {};
1550
- for (const t of terms) {
1551
- let df = 0;
1552
- for (const b of preparedBlocks) {
1553
- if (b.name.toLowerCase().includes(t) || b.rel.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
1554
- df++;
1555
- }
1556
- }
1557
- termDF[t] = Math.max(1, df);
1558
- }
1559
-
1560
- const allBlocks = preparedBlocks.map((b) => {
1561
- const lower = b.full.toLowerCase();
1562
- const relLower = b.rel.toLowerCase();
1563
- let score = 0;
1564
- for (const t of terms) {
1565
- const df = termDF[t] || 1;
1566
- const idf = Math.log(1 + (totalBlocks / df));
1567
- const scarcityMultiplier = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
1568
- const nameMatch = b.name.toLowerCase().includes(t) ? 35 : 0;
1569
- const pathMatch = relLower.includes(t) ? 25 : 0;
1570
- const bodyOcc = lower.split(t).length - 1;
1571
- const bodyScore = Math.min(12, 2.5 * Math.log1p(bodyOcc));
1572
- score += (nameMatch + pathMatch + bodyScore) * idf * scarcityMultiplier;
1573
- }
1574
- return { ...b, score };
1575
- }).sort((a, b) => b.score - a.score);
1576
-
1577
- // 構建專案 SymbolMap 與真實依賴圖 (True Call Graph + Constants)
1578
- const symbolMap = new Map();
1579
- const constSymbolNames = new Set();
1580
- for (let idx = 0; idx < allBlocks.length; idx++) {
1581
- const b = allBlocks[idx];
1582
- if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
1583
- const names = (b.kind === 'const' && b.name.includes(','))
1584
- ? b.name.split(',').map((s) => s.trim()).filter(Boolean)
1585
- : [b.name];
1586
- for (const sn of names) {
1587
- if (!symbolMap.has(sn)) symbolMap.set(sn, []);
1588
- symbolMap.get(sn).push(idx);
1589
- if (b.kind === 'const') constSymbolNames.add(sn);
1590
- }
1591
- }
1592
- }
1593
-
1594
- const callAdj = Array.from({ length: allBlocks.length }, () => new Set());
1595
- const definedNames = Array.from(symbolMap.keys());
1596
- for (let i = 0; i < allBlocks.length; i++) {
1597
- const caller = allBlocks[i];
1598
- const maskedCaller = maskCommentsAndStrings(caller.full);
1599
- for (const sym of definedNames) {
1600
- if (sym === caller.name) continue;
1601
- if (maskedCaller.includes(sym)) {
1602
- const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1603
- const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
1604
- const callRe = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
1605
- if (callRe.test(maskedCaller)) {
1606
- for (const t of (symbolMap.get(sym) || [])) {
1607
- callAdj[i].add(t);
1608
- callAdj[t].add(i);
1609
- }
1610
- }
1611
- }
1612
- }
1613
- }
1614
-
1615
- // 計算自頂部修改重點 (Focal) 出發的 1 層 (1-hop) 與 2 層 (2-hop) 關聯距離
1616
- const focalIndices = [];
1617
- const focalFiles = new Set();
1618
- const hopDistances = new Map();
1619
- for (let i = 0; i < allBlocks.length; i++) {
1620
- if (allBlocks[i].score > 0 && focalIndices.length < 3) {
1621
- focalIndices.push(i);
1622
- hopDistances.set(i, 0);
1623
- focalFiles.add(allBlocks[i].rel);
1624
- }
1625
- }
1626
-
1627
- const bfsQ = [...focalIndices];
1628
- let qHead = 0;
1629
- while (qHead < bfsQ.length) {
1630
- const curr = bfsQ[qHead++];
1631
- const curHop = hopDistances.get(curr) ?? 0;
1632
- if (curHop >= 2) continue;
1633
- for (const nbr of callAdj[curr]) {
1634
- if (!hopDistances.has(nbr)) {
1635
- hopDistances.set(nbr, curHop + 1);
1636
- bfsQ.push(nbr);
1637
- }
1638
- }
1639
- }
1640
-
1641
- let used = 0;
1642
- const skelCandidates = [];
1643
- const includedIds = new Set();
1644
- const includedFiles = [];
1645
- const includedFilesSet = new Set();
1646
- const partialFiles = new Set();
1647
- const selectedByFile = new Map();
1648
- const fullStart1EndLine = new Map();
1649
- const coveredRangesByFile = new Map();
1650
- const addCoveredRange = (rel, s, e) => {
1651
- if (!coveredRangesByFile.has(rel)) coveredRangesByFile.set(rel, []);
1652
- coveredRangesByFile.get(rel).push([s, e]);
1653
- };
1654
- const addSelectedBlock = (rel, entry) => {
1655
- if (!includedFilesSet.has(rel)) {
1656
- includedFilesSet.add(rel);
1657
- includedFiles.push(rel);
1658
- }
1659
- if (!selectedByFile.has(rel)) selectedByFile.set(rel, []);
1660
- selectedByFile.get(rel).push(entry);
1661
- };
1662
- const candidateItems = [];
1663
- const dirBudgetUsed = {};
1664
- const maxDirBudget = budget * 0.65;
1665
-
1666
- for (let i = 0; i < allBlocks.length; i++) {
1667
- const b = allBlocks[i];
1668
- const topDir = b.rel.split('/')[0] || 'root';
1669
- const curDir = dirBudgetUsed[topDir] || 0;
1670
- const hop = hopDistances.get(i);
1671
- const isFocal = (hop === 0 || (i < 3 && b.score > 0));
1672
- const winKey = b.rel + ':' + b.startLine;
1673
- const win = configWindowByKey.get(winKey);
1674
-
1675
- if (isFocal && ((used + b.rawTk <= budget && curDir + b.rawTk <= maxDirBudget) || used === 0)) {
1676
- used += b.rawTk;
1677
- dirBudgetUsed[topDir] = curDir + b.rawTk;
1678
- includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1679
- if (win) {
1680
- for (const r of win.ranges) {
1681
- addCoveredRange(b.rel, r[0], r[1]);
1682
- if (r[0] === 1) fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, r[1]));
1683
- }
1684
- } else {
1685
- addCoveredRange(b.rel, b.startLine, b.endLine);
1686
- if (b.startLine === 1) {
1687
- fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
1688
- }
1689
- }
1690
- addSelectedBlock(b.rel, { tier: 'full', b, win, autoExpanded: false });
1691
- } else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
1692
- const sameFileConst = b.kind === 'const' && (b.exported || /^[A-Z][A-Z0-9_]+$/.test(b.name)) && b.lineCount <= 25 && focalFiles.has(b.rel);
1693
- const linked = (hop !== undefined && hop <= 2) || b.score > 0 || sameFileConst;
1694
- if (linked) {
1695
- used += b.skelTk;
1696
- dirBudgetUsed[topDir] = curDir + b.skelTk;
1697
- skelCandidates.push({ ...b, linked, hop: hop ?? null, win });
1698
- includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1699
- if (!includedFilesSet.has(b.rel)) {
1700
- includedFilesSet.add(b.rel);
1701
- includedFiles.push(b.rel);
1702
- }
1703
- partialFiles.add(b.rel);
1704
- if (b.skeleton === b.full) {
1705
- addCoveredRange(b.rel, b.startLine, b.endLine);
1706
- }
1707
- } else {
1708
- partialFiles.add(b.rel);
1709
- candidateItems.push(b);
1710
- }
1711
- } else {
1712
- partialFiles.add(b.rel);
1713
- candidateItems.push(b);
1714
- }
1715
- }
1716
-
1717
- const autoExpandedNames = [];
1718
- for (const item of skelCandidates) {
1719
- const delta = Math.max(0, item.rawTk - item.skelTk);
1720
- const isComplexCluster = (item.linked || item.score > 0) && (item.lineCount >= 16 || delta >= 45);
1721
- const topDir = item.rel.split('/')[0] || 'root';
1722
- const curDir = dirBudgetUsed[topDir] || 0;
1723
-
1724
- if (autoExpand && isComplexCluster && autoExpandedNames.length < 4 && used + delta <= budget && curDir + delta <= maxDirBudget) {
1725
- used += delta;
1726
- dirBudgetUsed[topDir] = curDir + delta;
1727
- autoExpandedNames.push(item.name);
1728
- if (item.win) {
1729
- for (const r of item.win.ranges) {
1730
- addCoveredRange(item.rel, r[0], r[1]);
1731
- if (r[0] === 1) fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, r[1]));
1732
- }
1733
- } else {
1734
- addCoveredRange(item.rel, item.startLine, item.endLine);
1735
- if (item.startLine === 1) {
1736
- fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, item.endLine));
1737
- }
1738
- }
1739
- addSelectedBlock(item.rel, { tier: 'full', b: item, win: item.win, autoExpanded: true });
1740
- } else {
1741
- addSelectedBlock(item.rel, { tier: 'skeleton', b: item, win: item.win, hop: item.hop });
1742
- }
1743
- }
1744
-
1745
- // State B: Non-empty query with 0 matches -> warn agent & return repository file tree
1746
- if (includedFiles.length === 0) {
1747
- const treeLines = buildRepositoryFileTree(fileEntries, 1800);
1748
- return [
1749
- `<context_slice mode="file_tree_zero_matches" root="${escapeXmlAttr(root)}" version="0.4.0"${subPathTag} query="${escapeXmlAttr(rawQuery)}">`,
1750
- ` <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>`,
1751
- ' <repository_file_tree>',
1752
- ...treeLines,
1753
- ' </repository_file_tree>',
1754
- '</context_slice>'
1755
- ].join('\n');
1756
- }
1757
-
1758
- const headerByFile = new Map();
1759
- const headerEndByFile = new Map();
1760
- for (const rel of includedFiles) {
1761
- const hdr = headerMap.get(rel);
1762
- if (!hdr) continue;
1763
- if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1764
- headerEndByFile.set(rel, hdr.endLine);
1765
- headerByFile.set(rel, hdr);
1766
- }
1767
-
1768
- const footerByFile = new Map();
1769
- for (const rel of includedFiles) {
1770
- const ftr = footerMap.get(rel);
1771
- if (!ftr) continue;
1772
- const ranges = coveredRangesByFile.get(rel) || [];
1773
- const totalLines = lineCountMap.get(rel) || 0;
1774
- const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
1775
- if (!partialFiles.has(rel) && wholeFileCovered) continue;
1776
- const hdrEnd = headerEndByFile.get(rel) || 0;
1777
- const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1778
- if (uncovered.length > 0) {
1779
- footerByFile.set(rel, {
1780
- startLine: uncovered[0].startLine,
1781
- endLine: uncovered[uncovered.length - 1].endLine,
1782
- text: uncovered.map((c) => c.text).join('\n'),
1783
- chunks: uncovered
1784
- });
1785
- }
1786
- }
1787
-
1788
- const fileSections = [];
1789
- for (const rel of includedFiles) {
1790
- const entries = (selectedByFile.get(rel) || []).slice().sort((a, b) => a.b.startLine - b.b.startLine);
1791
- const hdr = headerByFile.get(rel);
1792
- const ftr = footerByFile.get(rel);
1793
- const totalLines = lineCountMap.get(rel) || 0;
1794
- const shownRanges = [];
1795
- if (hdr) shownRanges.push([1, hdr.endLine]);
1796
- for (const ent of entries) {
1797
- if (ent.win) shownRanges.push(...ent.win.ranges);
1798
- else shownRanges.push([ent.b.startLine, ent.b.endLine]);
1799
- }
1800
- if (ftr) {
1801
- for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
1802
- }
1803
- fileSections.push(` <file path="${escapeXmlAttr(rel)}" total_lines="${totalLines}" shown_lines="${formatShownLines(shownRanges)}">`);
1804
- if (hdr) {
1805
- fileSections.push(` <file_header lines="1-${hdr.endLine}">`);
1806
- fileSections.push(hdr.header);
1807
- fileSections.push(' </file_header>');
1808
- }
1809
- for (const ent of entries) {
1810
- const b = ent.b;
1811
- if (ent.tier === 'full') {
1812
- const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : `${b.startLine}-${b.endLine}`;
1813
- const autoAttr = ent.autoExpanded ? ' autoExpanded="true"' : '';
1814
- fileSections.push(` <focal symbol="${escapeXmlAttr(b.name)}" lines="${linesAttr}" parser="${escapeXmlAttr(b.parserMode)}"${autoAttr}>`);
1815
- fileSections.push(ent.win ? ent.win.windowedCode : b.full);
1816
- fileSections.push(' </focal>');
1817
- } else {
1818
- const hopAttr = ent.hop !== null && ent.hop !== undefined ? ` hop="${ent.hop}"` : '';
1819
- fileSections.push(` <skeleton symbol="${escapeXmlAttr(b.name)}" lines="${b.startLine}-${b.endLine}"${hopAttr}>`);
1820
- fileSections.push(ent.win ? ent.win.windowedCode : b.skeleton);
1821
- fileSections.push(' </skeleton>');
1822
- }
1823
- }
1824
- if (ftr) {
1825
- fileSections.push(` <file_footer lines="${ftr.startLine}-${ftr.endLine}">`);
1826
- fileSections.push(ftr.text);
1827
- fileSections.push(' </file_footer>');
1828
- }
1829
- fileSections.push(' </file>');
1830
- }
1831
-
1832
- const omitted = candidateItems.filter(b => b.score > 0 && !includedIds.has(b.rel + ':' + b.name + '@' + b.startLine)).slice(0, 3);
1833
- const omittedTag = omitted.length > 0
1834
- ? `\n <omitted_top_matches>\n` + omitted.map(o => ` <!-- Omitted: ${o.rel}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`).join('\n') + `\n </omitted_top_matches>`
1835
- : '';
1836
-
1837
- const expandTag = autoExpandedNames.length > 0 ? ` autoExpanded="${escapeXmlAttr(autoExpandedNames.join(','))}"` : '';
1838
- return `<context_slice mode="progressive-structural-slice" root="${escapeXmlAttr(root)}" version="0.4.0"${subPathTag} budget="${budget}" used="${used}"${expandTag}>\n${fileSections.join('\n')}${omittedTag}\n</context_slice>`;
1839
2409
  } catch (err) {
1840
2410
  return `Error: ${err.message}`;
1841
2411
  }
@@ -1854,7 +2424,7 @@ rl.on('line', async (line) => {
1854
2424
  return send({
1855
2425
  protocolVersion: req.params?.protocolVersion || '2024-11-05',
1856
2426
  capabilities: { tools: {} },
1857
- serverInfo: { name: 'ctxslice-thin', version: '0.4.0' }
2427
+ serverInfo: { name: 'ctxslice-thin', version: '0.4.1' }
1858
2428
  });
1859
2429
  }
1860
2430
  if (req.method === 'ping') return send({});