@grundy40/contextslice 0.3.5 → 0.4.0

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.3.5
3
+ * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.4.0
4
4
  * Features: Embedded Base64 Tree-sitter WASM + Lazy Cache (~/.contextslice/parsers),
5
5
  * State-Machine Brace Matcher Fallback, True Call Graph (BFS), TF-IDF, subPath Sandbox, mtime Cache
6
6
  */
@@ -11,10 +11,131 @@ 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.3.5\n');
14
+ process.stdout.write('ctxslice-mcp v0.4.0\n');
15
15
  process.exit(0);
16
16
  }
17
17
 
18
+
19
+ const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
20
+ const EN_CONVERSATIONAL_STOPWORDS = new Set([
21
+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
22
+ 'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
23
+ 'how', 'why', 'what', 'when', 'where', 'who', 'which', 'whom', 'whose',
24
+ 'can', 'could', 'would', 'should', 'will', 'shall', 'may', 'might', 'must',
25
+ 'do', 'does', 'did', 'done', 'doing', 'have', 'has', 'had', 'having',
26
+ 'please', 'pls', 'help', 'me', 'my', 'we', 'our', 'you', 'your', 'they', 'their',
27
+ 'it', 'its', 'this', 'that', 'these', 'those', 'there', 'here',
28
+ 'and', 'or', 'but', 'so', 'than', 'too', 'very', 'just', 'only', 'also',
29
+ 'fix', 'modify', 'want', 'need', 'tell'
30
+ ]);
31
+ const ZH_CONVERSATIONAL_STOPWORDS_RE = /為什麼|为什么|怎麼樣|怎么样|怎麼|怎么|如何|請幫我|请帮我|幫我|帮我|請問|请问|修改|更改|調整|调整|一下|什麼|什么|這個|这个|那個|那个|哪裡|哪里|[的了嗎呢啊吧著着過把被給跟與及]/g;
32
+
33
+ function estimateTokens(str) {
34
+ if (!str) return 0;
35
+ let cjk = 0;
36
+ for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
37
+ return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
38
+ }
39
+
40
+ function escapeXmlAttr(value) {
41
+ return String(value || '')
42
+ .replace(/&/g, '&amp;')
43
+ .replace(/"/g, '&quot;')
44
+ .replace(/</g, '&lt;')
45
+ .replace(/>/g, '&gt;');
46
+ }
47
+
48
+ function escapeXmlText(value) {
49
+ return String(value || '')
50
+ .replace(/&/g, '&amp;')
51
+ .replace(/</g, '&lt;')
52
+ .replace(/>/g, '&gt;');
53
+ }
54
+
55
+ function mergeLineRanges(ranges) {
56
+ if (!ranges || ranges.length === 0) return [];
57
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
58
+ const merged = [];
59
+ for (const r of sorted) {
60
+ const s = Math.max(1, r[0]);
61
+ const e = Math.max(s, r[1]);
62
+ if (merged.length === 0) {
63
+ merged.push([s, e]);
64
+ } else {
65
+ const prev = merged[merged.length - 1];
66
+ if (s <= prev[1] + 1) prev[1] = Math.max(prev[1], e);
67
+ else merged.push([s, e]);
68
+ }
69
+ }
70
+ return merged;
71
+ }
72
+
73
+ function formatShownLines(ranges) {
74
+ const merged = mergeLineRanges(ranges);
75
+ if (merged.length === 0) return 'none';
76
+ return merged.map((r) => (r[0] === r[1] ? String(r[0]) : r[0] + '-' + r[1])).join(', ');
77
+ }
78
+
79
+ function slicePlainTextConfigWindow(content, queryTerms) {
80
+ const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
81
+ if (lines.length <= 200) return null;
82
+
83
+ const matchedLines = [];
84
+ if (queryTerms && queryTerms.length > 0) {
85
+ for (let i = 0; i < lines.length; i++) {
86
+ const lower = lines[i].toLowerCase();
87
+ if (queryTerms.some((t) => lower.includes(t))) {
88
+ matchedLines.push(i + 1);
89
+ }
90
+ }
91
+ }
92
+
93
+ const rawRanges = matchedLines.length > 0
94
+ ? matchedLines.map((ln) => [Math.max(1, ln - 40), Math.min(lines.length, ln + 40)])
95
+ : [[1, Math.min(lines.length, 81)]];
96
+
97
+ const merged = mergeLineRanges(rawRanges);
98
+ const parts = [];
99
+ for (let idx = 0; idx < merged.length; idx++) {
100
+ const s = merged[idx][0];
101
+ const e = merged[idx][1];
102
+ if (idx > 0) {
103
+ const prevEnd = merged[idx - 1][1];
104
+ parts.push('// ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ...');
105
+ }
106
+ parts.push(lines.slice(s - 1, e).join('\n'));
107
+ }
108
+
109
+ const windowedCode = parts.join('\n');
110
+ return {
111
+ windowedCode,
112
+ ranges: merged,
113
+ tokens: estimateTokens(windowedCode)
114
+ };
115
+ }
116
+
117
+ function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
118
+ const sorted = [...fileEntries].sort((a, b) => a.relPath.localeCompare(b.relPath));
119
+ const out = [];
120
+ let usedTokens = 0;
121
+ let omittedCount = 0;
122
+ for (const f of sorted) {
123
+ const line = ' ' + f.relPath + ' (' + f.lineCount + ' lines)';
124
+ const tk = estimateTokens(line);
125
+ if (usedTokens + tk > maxTokens && out.length > 0) {
126
+ omittedCount++;
127
+ continue;
128
+ }
129
+ usedTokens += tk;
130
+ out.push(line);
131
+ }
132
+ if (omittedCount > 0) {
133
+ out.push(' ... (' + omittedCount + ' more files omitted to keep overview within ~1.8K tokens)');
134
+ }
135
+ return out;
136
+ }
137
+
138
+
18
139
  const CJK_RE = /[一-鿿぀-ゟ゠-ヿ가-힯]/;
19
140
  const CJK_RUN_RE = new RegExp('[一-鿿぀-ゟ゠-ヿ가-힯]+', 'g');
20
141
  const CJK_WORDS = {
@@ -362,37 +483,57 @@ function bilingualLookup(term) {
362
483
  return out;
363
484
  }
364
485
  function expandQueryTerms(query) {
365
- const q = String(query || '').toLowerCase();
366
- const terms = new Set(q.split(/\s+/).filter(Boolean));
367
- const asciiParts = q.match(/[a-z0-9_]+/g) || [];
486
+ const trimmed = String(query || '').trim();
487
+ if (!trimmed) return [];
488
+ const q = trimmed.toLowerCase();
489
+ const terms = new Set();
490
+ const asciiParts = q.match(/[a-z0-9_]+(?:[.-][a-z0-9_]+)*/g) || [];
368
491
  for (const p of asciiParts) {
369
- if (p.length >= 2) terms.add(p);
370
- for (const t of bilingualLookup(p)) terms.add(t);
492
+ if (p.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(p)) {
493
+ terms.add(p);
494
+ if (/^v\d/.test(p) && p.length >= 3) terms.add(p.slice(1));
495
+ if (p.includes('.') || p.includes('-')) {
496
+ for (const sub of p.split(/[.-]/)) {
497
+ if (sub.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(sub)) terms.add(sub);
498
+ }
499
+ }
500
+ for (const t of bilingualLookup(p)) terms.add(t);
501
+ }
371
502
  }
372
- if (containsCJK(q)) {
373
- for (const gram of tokenizeCJK2gram(q)) {
374
- terms.add(gram);
375
- for (const t of bilingualLookup(gram)) terms.add(t);
503
+ if (containsCJK(trimmed)) {
504
+ const cleanedCjk = trimmed.replace(ZH_CONVERSATIONAL_STOPWORDS_RE, ' ');
505
+ if (containsCJK(cleanedCjk)) {
506
+ for (const gram of tokenizeCJK2gram(cleanedCjk)) {
507
+ terms.add(gram);
508
+ for (const t of bilingualLookup(gram)) terms.add(t);
509
+ }
510
+ for (const run of cleanedCjk.match(CJK_RUN_RE) || []) {
511
+ terms.add(run);
512
+ for (const t of bilingualLookup(run)) terms.add(t);
513
+ }
376
514
  }
377
- for (const run of q.match(CJK_RUN_RE) || []) terms.add(run);
515
+ }
516
+ const snapshot = [...terms];
517
+ for (const term of snapshot) {
518
+ for (const t of bilingualLookup(term)) terms.add(t);
378
519
  }
379
520
  return [...terms].filter(Boolean);
380
521
  }
381
522
 
382
523
  const TOOL_DEF = {
383
524
  name: 'get_context_slice',
384
- description: 'PRIMARY code-reading tool (v0.3.5) with Tree-sitter WASM / State-Machine AST parsing, True Call Graph, TF-IDF & omitted summary.',
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.',
385
526
  annotations: { readOnlyHint: true },
386
527
  inputSchema: {
387
528
  type: 'object',
388
529
  properties: {
389
- query: { type: 'string', description: 'Task or symbol keywords (Supports CJK multi-language + bilingual zh-en matching)' },
530
+ query: { type: 'string', description: 'Task or symbol keywords (Supports CJK multi-language + bilingual matching; omit or pass "" to return repository file tree overview)' },
390
531
  projectPath: { type: 'string', description: 'Absolute path to target project folder' },
391
532
  subPath: { type: 'string', description: 'Optional sub-directory path to sandbox/restrict project scanning (e.g. src/auth)' },
392
533
  budget: { type: 'number', description: 'Max token budget (default 32768)' },
393
534
  autoExpand: { type: 'boolean', description: 'Auto-expand high-complexity skeleton clusters (default true)' }
394
535
  },
395
- required: ['query']
536
+ required: []
396
537
  }
397
538
  };
398
539
 
@@ -418,7 +559,7 @@ const IGNORE_DIRS = new Set([
418
559
  ]);
419
560
 
420
561
  const BINARY_EXT_RE = /\.(png|jpe?g|gif|webp|bmp|ico|icns|tiff?|svg|mp4|mov|avi|mkv|webm|wmv|flv|mp3|wav|ogg|flac|aac|m4a|wma|zip|rar|7z|tar|gz|bz2|xz|tgz|iso|dmg|exe|dll|so|dylib|bin|o|a|obj|lib|wasm|class|jar|war|pyc|pyo|ttf|otf|woff2?|eot|pdf|docx?|xlsx?|pptx?|odt|ods|odp|rtf|db|sqlite3?|mdb|psd|ai|sketch|fig|xd|blend|fbx|glb|gltf)$/i;
421
- const NOISE_FILE_RE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock|Gemfile\.lock|composer\.lock|go\.sum|Podfile\.lock|packages\.lock\.json|\.env(\..*)?|\.pem|\.key|credentials\.json|service-account.*\.json|secrets\.json)$|\.min\.(js|mjs|cjs|css)$|\.map$/i;
562
+ const NOISE_FILE_RE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.lock|poetry\.lock|Gemfile\.lock|composer\.lock|go\.sum|Podfile\.lock|packages\.lock\.json|\.env(\..*)?|\.pem|\.key|credentials\.json|service-account.*\.json|secrets\.json)$|\.min\.(js|mjs|cjs|css)$|\.map$/i;
422
563
  const CONTROL_WORDS = new Set(['if', 'else', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'typeof', 'do', 'try']);
423
564
 
424
565
  // Pure in-memory mtime cache: Map<filePath, { mtime: number, parserMode: string, items: Array<...> }>
@@ -1167,6 +1308,31 @@ function extractFileFooter(content, tailLines = 20) {
1167
1308
  }
1168
1309
 
1169
1310
 
1311
+ function collectFileOverview(root, scanRoot) {
1312
+ const files = [];
1313
+ const walk = (d) => {
1314
+ if (!fs.existsSync(d)) return;
1315
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
1316
+ if (IGNORE_DIRS.has(e.name)) continue;
1317
+ const full = path.join(d, e.name);
1318
+ if (e.isDirectory()) walk(full);
1319
+ else if (isAcceptedFile(full.replace(/\\/g, '/'))) files.push(full);
1320
+ }
1321
+ };
1322
+ walk(scanRoot);
1323
+ const fileEntries = [];
1324
+ for (const f of files) {
1325
+ try {
1326
+ const buf = fs.readFileSync(f);
1327
+ if (isBinaryBuffer(buf)) continue;
1328
+ const relPath = path.relative(root, f).replace(/\\/g, '/');
1329
+ const lineCount = buf.toString('utf8').replace(/\r\n/g, '\n').split('\n').length;
1330
+ fileEntries.push({ relPath, lineCount });
1331
+ } catch {}
1332
+ }
1333
+ return fileEntries;
1334
+ }
1335
+
1170
1336
  async function collectProjectBlocks(root, scanRoot) {
1171
1337
  const files = [];
1172
1338
  const walk = (d) => {
@@ -1175,7 +1341,7 @@ async function collectProjectBlocks(root, scanRoot) {
1175
1341
  if (IGNORE_DIRS.has(e.name)) continue;
1176
1342
  const full = path.join(d, e.name);
1177
1343
  if (e.isDirectory()) walk(full);
1178
- else if (isAcceptedFile(e.name)) files.push(full);
1344
+ else if (isAcceptedFile(full.replace(/\\/g, '/'))) files.push(full);
1179
1345
  }
1180
1346
  };
1181
1347
  walk(scanRoot);
@@ -1190,8 +1356,9 @@ async function collectProjectBlocks(root, scanRoot) {
1190
1356
  const headerMap = new Map();
1191
1357
  const footerMap = new Map();
1192
1358
  const lineCountMap = new Map();
1359
+ const fileEntries = [];
1193
1360
  for (const f of files) {
1194
- const rel = path.relative(root, f);
1361
+ const rel = path.relative(root, f).replace(/\\/g, '/');
1195
1362
  let stat;
1196
1363
  try {
1197
1364
  stat = fs.statSync(f);
@@ -1206,34 +1373,36 @@ async function collectProjectBlocks(root, scanRoot) {
1206
1373
  let fileHeader = null;
1207
1374
  let fileFooter = null;
1208
1375
  let fileLines = 0;
1376
+ const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
1209
1377
  if (cached && cached.mtime === mtime) {
1210
1378
  items = cached.items;
1211
1379
  parserMode = cached.parserMode || 'regex';
1212
- fileHeader = cached.header ?? null;
1213
- fileFooter = cached.footer ?? null;
1380
+ fileHeader = isConfigFile ? null : (cached.header ?? null);
1381
+ fileFooter = isConfigFile ? null : (cached.footer ?? null);
1214
1382
  fileLines = cached.lineCount || 0;
1215
1383
  } else {
1216
1384
  const rawBuf = fs.readFileSync(f);
1217
1385
  if (isBinaryBuffer(rawBuf)) continue;
1218
1386
  const raw = rawBuf.toString('utf8');
1219
- fileLines = raw.split('\n').length;
1220
- fileHeader = extractFileHeader(raw);
1221
- fileFooter = extractFileFooter(raw);
1387
+ fileLines = raw.replace(/\r\n/g, '\n').split('\n').length;
1388
+ fileHeader = isConfigFile ? null : extractFileHeader(raw);
1389
+ fileFooter = isConfigFile ? null : extractFileFooter(raw);
1222
1390
  const ext = path.extname(f);
1223
- const tsBlocks = await extractBlocksWithTreeSitter(raw, ext, rel);
1391
+ const tsBlocks = isConfigFile ? null : await extractBlocksWithTreeSitter(raw, ext, rel);
1224
1392
  if (tsBlocks && tsBlocks.length > 0) {
1225
1393
  const extraConsts = extractTopLevelConstants(raw, ext, tsBlocks);
1226
1394
  items = extraConsts.length > 0 ? [...tsBlocks, ...extraConsts].sort((a, b) => a.startLine - b.startLine) : tsBlocks;
1227
1395
  parserMode = 'tree-sitter-wasm';
1228
1396
  } else {
1229
1397
  items = extractBlocks(raw, ext, rel);
1230
- parserMode = 'state-machine-regex';
1398
+ parserMode = isConfigFile ? 'plain-text-config' : 'state-machine-regex';
1231
1399
  }
1232
1400
  FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
1233
1401
  }
1234
1402
  if (fileHeader) headerMap.set(rel, fileHeader);
1235
1403
  if (fileFooter) footerMap.set(rel, fileFooter);
1236
1404
  lineCountMap.set(rel, fileLines);
1405
+ fileEntries.push({ relPath: rel, lineCount: fileLines });
1237
1406
 
1238
1407
  for (const b of items) {
1239
1408
  allBlocks.push({
@@ -1241,12 +1410,12 @@ async function collectProjectBlocks(root, scanRoot) {
1241
1410
  rel,
1242
1411
  parserMode,
1243
1412
  lineCount: Math.max(1, b.endLine - b.startLine + 1),
1244
- rawTk: Math.max(1, Math.round(b.full.length / 3.8)),
1245
- skelTk: Math.max(1, Math.round(b.skeleton.length / 3.8))
1413
+ rawTk: estimateTokens(b.full),
1414
+ skelTk: estimateTokens(b.skeleton)
1246
1415
  });
1247
1416
  }
1248
1417
  }
1249
- return { blocks: allBlocks, headerMap, footerMap, lineCountMap };
1418
+ return { blocks: allBlocks, headerMap, footerMap, lineCountMap, fileEntries };
1250
1419
  }
1251
1420
 
1252
1421
  function resolveScanRoot(projectPath, subPath) {
@@ -1272,48 +1441,69 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
1272
1441
  const wanted = new Set((symbols || []).map((s) => String(s).toLowerCase()));
1273
1442
  const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
1274
1443
  let used = 0;
1275
- const expanded = [];
1276
- const expandedFiles = new Set();
1444
+ const expandedFiles = [];
1445
+ const expandedFilesSet = new Set();
1446
+ const expandedByFile = new Map();
1277
1447
  const fullStart1EndLine = new Map();
1278
1448
  const coveredRangesByFile = new Map();
1449
+ let expandedCount = 0;
1279
1450
  for (const b of blocks) {
1280
1451
  const match = wanted.has(b.name.toLowerCase()) || [...wanted].some((w) => b.name.toLowerCase().includes(w) || b.rel.toLowerCase().includes(w));
1281
1452
  if (match && used + b.rawTk <= budget) {
1282
1453
  used += b.rawTk;
1283
- expandedFiles.add(b.rel);
1454
+ expandedCount++;
1455
+ if (!expandedFilesSet.has(b.rel)) {
1456
+ expandedFilesSet.add(b.rel);
1457
+ expandedFiles.push(b.rel);
1458
+ }
1459
+ if (!expandedByFile.has(b.rel)) expandedByFile.set(b.rel, []);
1460
+ expandedByFile.get(b.rel).push(b);
1284
1461
  if (!coveredRangesByFile.has(b.rel)) coveredRangesByFile.set(b.rel, []);
1285
1462
  coveredRangesByFile.get(b.rel).push([b.startLine, b.endLine]);
1286
1463
  if (b.startLine === 1) {
1287
1464
  fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
1288
1465
  }
1289
- expanded.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [MCP: expand_skeleton_cluster]\n${b.full}`);
1290
1466
  }
1291
1467
  }
1292
- const headerChunks = [];
1293
- const headerEndByFile = new Map();
1468
+
1469
+ const sections = [];
1294
1470
  for (const rel of expandedFiles) {
1295
1471
  const hdr = headerMap.get(rel);
1296
- if (!hdr) continue;
1297
- if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1298
- headerEndByFile.set(rel, hdr.endLine);
1299
- headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
1300
- }
1301
- const footerChunks = [];
1302
- for (const rel of expandedFiles) {
1472
+ const showHdr = hdr && (fullStart1EndLine.get(rel) || 0) < hdr.endLine;
1473
+ const hdrEnd = showHdr ? hdr.endLine : 0;
1303
1474
  const ftr = footerMap.get(rel);
1304
- if (!ftr) continue;
1305
1475
  const ranges = coveredRangesByFile.get(rel) || [];
1306
1476
  const totalLines = lineCountMap.get(rel) || 0;
1307
- if (ranges.some(([s, e]) => s <= 1 && e >= totalLines)) continue;
1308
- const hdrEnd = headerEndByFile.get(rel) || 0;
1309
- const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1310
- if (uncovered.length > 0) {
1311
- footerChunks.push(`// [${rel}:${uncovered[0].startLine}-${uncovered[uncovered.length - 1].endLine}] (file footer)\n${uncovered.map((c) => c.text).join('\n')}`);
1477
+ const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
1478
+ const uncoveredFooter = (!wholeFileCovered && ftr)
1479
+ ? ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e))
1480
+ : [];
1481
+ const shownRanges = [];
1482
+ if (showHdr) shownRanges.push([1, hdr.endLine]);
1483
+ const items = (expandedByFile.get(rel) || []).slice().sort((a, b) => a.startLine - b.startLine);
1484
+ for (const it of items) shownRanges.push([it.startLine, it.endLine]);
1485
+ for (const c of uncoveredFooter) shownRanges.push([c.startLine, c.endLine]);
1486
+
1487
+ sections.push(` <file path="${escapeXmlAttr(rel)}" total_lines="${totalLines}" shown_lines="${formatShownLines(shownRanges)}">`);
1488
+ if (showHdr) {
1489
+ sections.push(` <file_header lines="1-${hdr.endLine}">`);
1490
+ sections.push(hdr.header);
1491
+ sections.push(' </file_header>');
1492
+ }
1493
+ for (const it of items) {
1494
+ sections.push(` <focal symbol="${escapeXmlAttr(it.name)}" lines="${it.startLine}-${it.endLine}" source="expand_skeleton_cluster">`);
1495
+ sections.push(it.full);
1496
+ sections.push(' </focal>');
1497
+ }
1498
+ if (uncoveredFooter.length > 0) {
1499
+ sections.push(` <file_footer lines="${uncoveredFooter[0].startLine}-${uncoveredFooter[uncoveredFooter.length - 1].endLine}">`);
1500
+ sections.push(uncoveredFooter.map((c) => c.text).join('\n'));
1501
+ sections.push(' </file_footer>');
1312
1502
  }
1503
+ sections.push(' </file>');
1313
1504
  }
1314
- const hdrTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
1315
- const ftrTag = footerChunks.length > 0 ? `\n<file_footers>\n${footerChunks.join('\n\n')}\n</file_footers>` : '';
1316
- return `<skeleton_expansion root="${root}" subPath="${subPath || ''}" expanded="${expanded.length}" used="${used}">${hdrTag}\n${expanded.join('\n\n')}${ftrTag}\n</skeleton_expansion>`;
1505
+
1506
+ return `<skeleton_expansion root="${escapeXmlAttr(root)}" subPath="${escapeXmlAttr(subPath || '')}" expanded="${expandedCount}" used="${used}">\n${sections.join('\n')}\n</skeleton_expansion>`;
1317
1507
  } catch (err) {
1318
1508
  return `Error: ${err.message}`;
1319
1509
  }
@@ -1322,13 +1512,44 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
1322
1512
  async function sliceProject(query, projectPath, budget = 32768, autoExpand = true, subPath) {
1323
1513
  try {
1324
1514
  const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
1325
- const terms = expandQueryTerms(String(query));
1326
- const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
1327
- const totalBlocks = Math.max(1, blocks.length);
1515
+ const rawQuery = String(query ?? '');
1516
+ const subPathTag = subPath ? ` subPath="${escapeXmlAttr(subPath)}"` : '';
1517
+
1518
+ // State A: Empty query -> return repository file tree overview (~1K-2K tokens)
1519
+ if (!rawQuery.trim()) {
1520
+ 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');
1530
+ }
1531
+
1532
+ const terms = expandQueryTerms(rawQuery);
1533
+ 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;
1546
+ });
1547
+
1548
+ const totalBlocks = Math.max(1, preparedBlocks.length);
1328
1549
  const termDF = {};
1329
1550
  for (const t of terms) {
1330
1551
  let df = 0;
1331
- for (const b of blocks) {
1552
+ for (const b of preparedBlocks) {
1332
1553
  if (b.name.toLowerCase().includes(t) || b.rel.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
1333
1554
  df++;
1334
1555
  }
@@ -1336,7 +1557,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1336
1557
  termDF[t] = Math.max(1, df);
1337
1558
  }
1338
1559
 
1339
- const allBlocks = blocks.map((b) => {
1560
+ const allBlocks = preparedBlocks.map((b) => {
1340
1561
  const lower = b.full.toLowerCase();
1341
1562
  const relLower = b.rel.toLowerCase();
1342
1563
  let score = 0;
@@ -1418,49 +1639,67 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1418
1639
  }
1419
1640
 
1420
1641
  let used = 0;
1421
- const fullChunks = [];
1422
1642
  const skelCandidates = [];
1423
- const focalNames = new Set();
1424
1643
  const includedIds = new Set();
1425
- const includedFiles = new Set();
1644
+ const includedFiles = [];
1645
+ const includedFilesSet = new Set();
1426
1646
  const partialFiles = new Set();
1647
+ const selectedByFile = new Map();
1427
1648
  const fullStart1EndLine = new Map();
1428
1649
  const coveredRangesByFile = new Map();
1429
1650
  const addCoveredRange = (rel, s, e) => {
1430
1651
  if (!coveredRangesByFile.has(rel)) coveredRangesByFile.set(rel, []);
1431
1652
  coveredRangesByFile.get(rel).push([s, e]);
1432
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
+ };
1433
1662
  const candidateItems = [];
1434
1663
  const dirBudgetUsed = {};
1435
1664
  const maxDirBudget = budget * 0.65;
1436
1665
 
1437
1666
  for (let i = 0; i < allBlocks.length; i++) {
1438
1667
  const b = allBlocks[i];
1439
- const topDir = b.rel.split(path.sep)[0] || 'root';
1668
+ const topDir = b.rel.split('/')[0] || 'root';
1440
1669
  const curDir = dirBudgetUsed[topDir] || 0;
1441
1670
  const hop = hopDistances.get(i);
1442
1671
  const isFocal = (hop === 0 || (i < 3 && b.score > 0));
1672
+ const winKey = b.rel + ':' + b.startLine;
1673
+ const win = configWindowByKey.get(winKey);
1443
1674
 
1444
- if (isFocal && used + b.rawTk <= budget && curDir + b.rawTk <= maxDirBudget) {
1675
+ if (isFocal && ((used + b.rawTk <= budget && curDir + b.rawTk <= maxDirBudget) || used === 0)) {
1445
1676
  used += b.rawTk;
1446
1677
  dirBudgetUsed[topDir] = curDir + b.rawTk;
1447
- focalNames.add(b.name);
1448
1678
  includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1449
- includedFiles.add(b.rel);
1450
- addCoveredRange(b.rel, b.startLine, b.endLine);
1451
- if (b.startLine === 1) {
1452
- fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
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
+ }
1453
1689
  }
1454
- fullChunks.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [${b.parserMode}]\n${b.full}`);
1690
+ addSelectedBlock(b.rel, { tier: 'full', b, win, autoExpanded: false });
1455
1691
  } else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
1456
1692
  const sameFileConst = b.kind === 'const' && (b.exported || /^[A-Z][A-Z0-9_]+$/.test(b.name)) && b.lineCount <= 25 && focalFiles.has(b.rel);
1457
1693
  const linked = (hop !== undefined && hop <= 2) || b.score > 0 || sameFileConst;
1458
- if (linked || i < 12) {
1694
+ if (linked) {
1459
1695
  used += b.skelTk;
1460
1696
  dirBudgetUsed[topDir] = curDir + b.skelTk;
1461
- skelCandidates.push({ ...b, linked, hop: hop ?? null });
1697
+ skelCandidates.push({ ...b, linked, hop: hop ?? null, win });
1462
1698
  includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1463
- includedFiles.add(b.rel);
1699
+ if (!includedFilesSet.has(b.rel)) {
1700
+ includedFilesSet.add(b.rel);
1701
+ includedFiles.push(b.rel);
1702
+ }
1464
1703
  partialFiles.add(b.rel);
1465
1704
  if (b.skeleton === b.full) {
1466
1705
  addCoveredRange(b.rel, b.startLine, b.endLine);
@@ -1476,40 +1715,57 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1476
1715
  }
1477
1716
 
1478
1717
  const autoExpandedNames = [];
1479
- const finalSkelChunks = [];
1480
1718
  for (const item of skelCandidates) {
1481
1719
  const delta = Math.max(0, item.rawTk - item.skelTk);
1482
1720
  const isComplexCluster = (item.linked || item.score > 0) && (item.lineCount >= 16 || delta >= 45);
1483
- const topDir = item.rel.split(path.sep)[0] || 'root';
1721
+ const topDir = item.rel.split('/')[0] || 'root';
1484
1722
  const curDir = dirBudgetUsed[topDir] || 0;
1485
1723
 
1486
1724
  if (autoExpand && isComplexCluster && autoExpandedNames.length < 4 && used + delta <= budget && curDir + delta <= maxDirBudget) {
1487
1725
  used += delta;
1488
1726
  dirBudgetUsed[topDir] = curDir + delta;
1489
1727
  autoExpandedNames.push(item.name);
1490
- addCoveredRange(item.rel, item.startLine, item.endLine);
1491
- if (item.startLine === 1) {
1492
- fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, item.endLine));
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
+ }
1493
1738
  }
1494
- fullChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] [MCP auto-expanded: ${item.lineCount} lines]\n${item.full}`);
1739
+ addSelectedBlock(item.rel, { tier: 'full', b: item, win: item.win, autoExpanded: true });
1495
1740
  } else {
1496
- const hopNote = item.hop ? ` | ${item.hop}-hop` : '';
1497
- finalSkelChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] (skeleton${hopNote})\n${item.skeleton}`);
1741
+ addSelectedBlock(item.rel, { tier: 'skeleton', b: item, win: item.win, hop: item.hop });
1498
1742
  }
1499
1743
  }
1500
1744
 
1501
- const headerChunks = [];
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();
1502
1759
  const headerEndByFile = new Map();
1503
1760
  for (const rel of includedFiles) {
1504
1761
  const hdr = headerMap.get(rel);
1505
1762
  if (!hdr) continue;
1506
1763
  if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1507
1764
  headerEndByFile.set(rel, hdr.endLine);
1508
- headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
1765
+ headerByFile.set(rel, hdr);
1509
1766
  }
1510
- const headerTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
1511
1767
 
1512
- const footerChunks = [];
1768
+ const footerByFile = new Map();
1513
1769
  for (const rel of includedFiles) {
1514
1770
  const ftr = footerMap.get(rel);
1515
1771
  if (!ftr) continue;
@@ -1520,19 +1776,66 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1520
1776
  const hdrEnd = headerEndByFile.get(rel) || 0;
1521
1777
  const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1522
1778
  if (uncovered.length > 0) {
1523
- footerChunks.push(`// [${rel}:${uncovered[0].startLine}-${uncovered[uncovered.length - 1].endLine}] (file footer)\n${uncovered.map((c) => c.text).join('\n')}`);
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>');
1524
1828
  }
1829
+ fileSections.push(' </file>');
1525
1830
  }
1526
- const footerTag = footerChunks.length > 0 ? `\n<file_footers>\n${footerChunks.join('\n\n')}\n</file_footers>` : '';
1527
1831
 
1528
1832
  const omitted = candidateItems.filter(b => b.score > 0 && !includedIds.has(b.rel + ':' + b.name + '@' + b.startLine)).slice(0, 3);
1529
1833
  const omittedTag = omitted.length > 0
1530
- ? `\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>`
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>`
1531
1835
  : '';
1532
1836
 
1533
- const expandTag = autoExpandedNames.length > 0 ? ` autoExpanded="${autoExpandedNames.join(',')}"` : '';
1534
- const subPathTag = subPath ? ` subPath="${subPath}"` : '';
1535
- return `<context_slice root="${root}" version="0.3.5"${subPathTag} budget="${budget}" used="${used}"${expandTag}>${headerTag}\n<skeletons>\n${finalSkelChunks.join('\n')}\n</skeletons>\n<focal>\n${fullChunks.join('\n\n')}\n</focal>${footerTag}${omittedTag}\n</context_slice>`;
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>`;
1536
1839
  } catch (err) {
1537
1840
  return `Error: ${err.message}`;
1538
1841
  }
@@ -1551,7 +1854,7 @@ rl.on('line', async (line) => {
1551
1854
  return send({
1552
1855
  protocolVersion: req.params?.protocolVersion || '2024-11-05',
1553
1856
  capabilities: { tools: {} },
1554
- serverInfo: { name: 'ctxslice-thin', version: '0.3.5' }
1857
+ serverInfo: { name: 'ctxslice-thin', version: '0.4.0' }
1555
1858
  });
1556
1859
  }
1557
1860
  if (req.method === 'ping') return send({});