@grundy40/contextslice 0.3.3 → 0.3.4

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.3
3
+ * ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.3.4
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.3.3\n');
14
+ process.stdout.write('ctxslice-mcp v0.3.4\n');
15
15
  process.exit(0);
16
16
  }
17
17
 
@@ -381,7 +381,7 @@ function expandQueryTerms(query) {
381
381
 
382
382
  const TOOL_DEF = {
383
383
  name: 'get_context_slice',
384
- description: 'PRIMARY code-reading tool (v0.3.3) with Tree-sitter WASM / State-Machine AST parsing, True Call Graph, TF-IDF & omitted summary.',
384
+ description: 'PRIMARY code-reading tool (v0.3.4) with Tree-sitter WASM / State-Machine AST parsing, True Call Graph, TF-IDF & omitted summary.',
385
385
  annotations: { readOnlyHint: true },
386
386
  inputSchema: {
387
387
  type: 'object',
@@ -781,17 +781,25 @@ function extractBlocks(code, ext, fileName) {
781
781
  }
782
782
 
783
783
  if (name) {
784
- const end = findBraceEnd(lines, i);
784
+ const isStmtOnly = kind === 'const' || (kind === 'type' && !line.includes('{'));
785
+ const end = isStmtOnly ? findStatementEndLine(lines, i, 'ts') : findBraceEnd(lines, i);
785
786
  const full = lines.slice(i, end + 1).join('\n');
786
787
  const sigIdx = full.indexOf('{');
787
- const skeleton = (kind === 'interface' || kind === 'type' || sigIdx === -1 || end - i < 4)
788
+ const isShortConst = kind === 'const' && (end - i + 1) <= 10 && !full.includes('=>');
789
+ const skeleton = (kind === 'interface' || kind === 'type' || isShortConst || sigIdx === -1 || end - i < 4)
788
790
  ? full
789
791
  : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
790
- blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
792
+ blocks.push({ name, kind, exported: line.startsWith('export '), startLine: i + 1, endLine: end + 1, full, skeleton });
791
793
  if (kind !== 'class' && kind !== 'module') i = end;
792
794
  }
793
795
  }
794
796
 
797
+ const topConsts = extractTopLevelConstants(code, e, blocks);
798
+ if (topConsts.length > 0) {
799
+ blocks.push(...topConsts);
800
+ blocks.sort((a, b) => a.startLine - b.startLine);
801
+ }
802
+
795
803
  if (blocks.length === 0 && lines.length > 0) {
796
804
  const name = path.basename(fileName || ('file' + e));
797
805
  const full = code;
@@ -804,26 +812,7 @@ function extractBlocks(code, ext, fileName) {
804
812
  return blocks;
805
813
  }
806
814
 
807
- async function collectProjectBlocks(root, scanRoot) {
808
- const files = [];
809
- const walk = (d) => {
810
- if (!fs.existsSync(d)) return;
811
- for (const e of fs.readdirSync(d, { withFileTypes: true })) {
812
- if (IGNORE_DIRS.has(e.name)) continue;
813
- const full = path.join(d, e.name);
814
- if (e.isDirectory()) walk(full);
815
- else if (isAcceptedFile(e.name)) files.push(full);
816
- }
817
- };
818
- walk(scanRoot);
819
-
820
- for (const cachedPath of FILE_CACHE.keys()) {
821
- if (!fs.existsSync(cachedPath)) {
822
- FILE_CACHE.delete(cachedPath);
823
- }
824
- }
825
815
 
826
-
827
816
  function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
828
817
  if (!content) return null;
829
818
  const lines = String(content).replace(/\r\n/g, '\n').split('\n');
@@ -954,8 +943,253 @@ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
954
943
  }
955
944
 
956
945
 
946
+ function findStatementEndLine(lines, startIdx, mode) {
947
+ let parenDepth = 0;
948
+ let bracketDepth = 0;
949
+ let braceDepth = 0;
950
+ let inBlockComment = false;
951
+ let pyTripleQuote = null;
952
+ const maxScan = Math.min(lines.length - 1, startIdx + 120);
953
+
954
+ for (let j = startIdx; j <= maxScan; j++) {
955
+ const raw = lines[j];
956
+ const len = raw.length;
957
+ let k = 0;
958
+ while (k < len) {
959
+ const ch = raw[k];
960
+ const next = raw[k + 1];
961
+ const next3 = mode === 'py' ? raw.slice(k, k + 3) : '';
962
+ if (pyTripleQuote) {
963
+ if (next3 === pyTripleQuote) { pyTripleQuote = null; k += 3; continue; }
964
+ k++; continue;
965
+ }
966
+ if (inBlockComment) {
967
+ if (ch === '*' && next === '/') { inBlockComment = false; k += 2; continue; }
968
+ k++; continue;
969
+ }
970
+ if (mode === 'py' && ch === '#') break;
971
+ if (mode !== 'py' && ch === '/' && next === '/') break;
972
+ if (mode !== 'py' && ch === '/' && next === '*') { inBlockComment = true; k += 2; continue; }
973
+ if (mode === 'py' && (next3 === '"""' || next3 === "'''")) { pyTripleQuote = next3; k += 3; continue; }
974
+ if (ch === '"' || ch === "'" || (mode === 'ts' && ch === '\x60') || (mode === 'go' && ch === '\x60')) {
975
+ const quote = ch;
976
+ k++;
977
+ while (k < len) {
978
+ if (quote !== '\x60' && raw[k] === '\\') { k += 2; continue; }
979
+ if (raw[k] === quote) { k++; break; }
980
+ k++;
981
+ }
982
+ continue;
983
+ }
984
+ if (ch === '(') parenDepth++;
985
+ else if (ch === ')') parenDepth = Math.max(0, parenDepth - 1);
986
+ else if (ch === '[') bracketDepth++;
987
+ else if (ch === ']') bracketDepth = Math.max(0, bracketDepth - 1);
988
+ else if (ch === '{') braceDepth++;
989
+ else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
990
+ k++;
991
+ }
992
+ if (!inBlockComment && !pyTripleQuote && parenDepth <= 0 && bracketDepth <= 0 && braceDepth <= 0) {
993
+ const trimmedEnd = raw.trimEnd();
994
+ if (trimmedEnd.endsWith('\\')) continue;
995
+ if (trimmedEnd.endsWith('=') && !trimmedEnd.endsWith('=>')) continue;
996
+ return j;
997
+ }
998
+ }
999
+ return maxScan;
1000
+ }
1001
+
1002
+ function extractTopLevelConstants(code, ext, existingBlocks) {
1003
+ const e = (ext || '').toLowerCase();
1004
+ const lines = String(code || '').replace(/\r\n/g, '\n').split('\n');
1005
+ const covered = (existingBlocks || []).map((b) => [b.startLine, b.endLine]);
1006
+ const isCovered = (ln) => covered.some(([s, en]) => ln >= s && ln <= en);
1007
+ const out = [];
1008
+
1009
+ if (e === '.py' || e === '.pyw') {
1010
+ for (let i = 0; i < lines.length; i++) {
1011
+ const ln = i + 1;
1012
+ if (isCovered(ln)) continue;
1013
+ const line = lines[i];
1014
+ const m = line.match(/^([A-Z][A-Z0-9_]+|__all__|__version__)\s*(?::\s*[^=\n]+)?=\s*(?!=)/);
1015
+ if (!m) continue;
1016
+ const endIdx = findStatementEndLine(lines, i, 'py');
1017
+ const endLine = endIdx + 1;
1018
+ covered.push([ln, endLine]);
1019
+ const full = lines.slice(i, endLine).join('\n');
1020
+ const lineCount = endLine - ln + 1;
1021
+ const skeleton = lineCount <= 8 ? full : line + '\n # ... ' + (lineCount - 1) + ' lines folded';
1022
+ out.push({ name: m[1], kind: 'const', exported: !m[1].startsWith('_') || m[1] === '__all__', startLine: ln, endLine, full, skeleton });
1023
+ i = endIdx;
1024
+ }
1025
+ return out;
1026
+ }
1027
+
1028
+ if (e === '.go') {
1029
+ for (let i = 0; i < lines.length; i++) {
1030
+ const ln = i + 1;
1031
+ if (isCovered(ln)) continue;
1032
+ const line = lines[i];
1033
+ const gm = line.match(/^(const|var)\s*\(/);
1034
+ if (gm) {
1035
+ const endIdx = findStatementEndLine(lines, i, 'go');
1036
+ const endLine = endIdx + 1;
1037
+ covered.push([ln, endLine]);
1038
+ const names = [];
1039
+ for (let j = i + 1; j <= endIdx; j++) {
1040
+ const im = lines[j].match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\b/);
1041
+ if (im && im[1] !== '_' && im[1] !== 'iota') names.push(im[1]);
1042
+ }
1043
+ const name = names.length > 0 ? names.slice(0, 4).join(', ') : gm[1] + '_block';
1044
+ const full = lines.slice(i, endLine).join('\n');
1045
+ const lineCount = endLine - ln + 1;
1046
+ const skeleton = lineCount <= 12 ? full : line + '\n\t// ... ' + (lineCount - 2) + ' lines folded\n)';
1047
+ out.push({ name, kind: 'const', exported: names.some((n) => /^[A-Z]/.test(n)), startLine: ln, endLine, full, skeleton });
1048
+ i = endIdx;
1049
+ continue;
1050
+ }
1051
+ const sm = line.match(/^(const|var)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
1052
+ if (sm) {
1053
+ const endIdx = findStatementEndLine(lines, i, 'go');
1054
+ const endLine = endIdx + 1;
1055
+ covered.push([ln, endLine]);
1056
+ const full = lines.slice(i, endLine).join('\n');
1057
+ const lineCount = endLine - ln + 1;
1058
+ const skeleton = lineCount <= 8 ? full : line + '\n\t// ... ' + (lineCount - 1) + ' lines folded';
1059
+ out.push({ name: sm[2], kind: 'const', exported: /^[A-Z]/.test(sm[2]), startLine: ln, endLine, full, skeleton });
1060
+ i = endIdx;
1061
+ }
1062
+ }
1063
+ return out;
1064
+ }
1065
+
1066
+ if (e === '.rs') {
1067
+ for (let i = 0; i < lines.length; i++) {
1068
+ const ln = i + 1;
1069
+ if (isCovered(ln)) continue;
1070
+ const line = lines[i];
1071
+ const rm = line.match(/^(?:pub(?:\([^)]+\))?\s+)?(?:const|static)\s+([A-Z][A-Z0-9_]*)\b/);
1072
+ if (!rm) continue;
1073
+ const endIdx = findStatementEndLine(lines, i, 'rs');
1074
+ const endLine = endIdx + 1;
1075
+ covered.push([ln, endLine]);
1076
+ const full = lines.slice(i, endLine).join('\n');
1077
+ const lineCount = endLine - ln + 1;
1078
+ const skeleton = lineCount <= 8 ? full : line + '\n /* ... ' + (lineCount - 1) + ' lines folded */';
1079
+ out.push({ name: rm[1], kind: 'const', exported: line.startsWith('pub'), startLine: ln, endLine, full, skeleton });
1080
+ i = endIdx;
1081
+ }
1082
+ return out;
1083
+ }
1084
+
1085
+ if (['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'].includes(e)) {
1086
+ for (let i = 0; i < lines.length; i++) {
1087
+ const ln = i + 1;
1088
+ if (isCovered(ln)) continue;
1089
+ const line = lines[i];
1090
+ let name = null;
1091
+ let exported = false;
1092
+ const cm = line.match(/^(export\s+)?(?:declare\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/);
1093
+ if (cm) {
1094
+ exported = Boolean(cm[1]);
1095
+ if (exported || /^[A-Z][A-Z0-9_]+$/.test(cm[2])) name = cm[2];
1096
+ } else {
1097
+ const tm = line.match(/^(?:export\s+(default)\s+(?!(?:async\s+)?(?:function|class|abstract\s+class|interface)\b)|(module\.exports)\s*=)/);
1098
+ if (tm) { name = tm[1] ? 'default' : 'module.exports'; exported = true; }
1099
+ }
1100
+ if (!name) continue;
1101
+ const endIdx = findStatementEndLine(lines, i, 'ts');
1102
+ const endLine = endIdx + 1;
1103
+ const full = lines.slice(i, endLine).join('\n');
1104
+ if (full.includes('=>') && !name.startsWith('default')) continue;
1105
+ covered.push([ln, endLine]);
1106
+ const lineCount = endLine - ln + 1;
1107
+ const skeleton = lineCount <= 10 ? full : line + '\n /* ... ' + (lineCount - 1) + ' lines folded */';
1108
+ out.push({ name, kind: 'const', exported, startLine: ln, endLine, full, skeleton });
1109
+ i = endIdx;
1110
+ }
1111
+ }
1112
+ return out;
1113
+ }
1114
+
1115
+ function extractFileFooter(content, tailLines = 20) {
1116
+ if (!content) return null;
1117
+ const lines = String(content).replace(/\r\n/g, '\n').split('\n');
1118
+ let lastNonEmpty = lines.length - 1;
1119
+ while (lastNonEmpty >= 0 && lines[lastNonEmpty].trim() === '') lastNonEmpty--;
1120
+ if (lastNonEmpty < 0) return null;
1121
+ const windowStart = Math.max(0, lastNonEmpty - tailLines + 1);
1122
+ const stripFooterNoise = (line) =>
1123
+ line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
1124
+ const findTailStmtEnd = (startIdx) => {
1125
+ let paren = 0, bracket = 0, brace = 0;
1126
+ for (let j = startIdx; j <= lastNonEmpty; j++) {
1127
+ const clean = stripFooterNoise(lines[j]);
1128
+ for (let k = 0; k < clean.length; k++) {
1129
+ const ch = clean[k];
1130
+ if (ch === '(') paren++;
1131
+ else if (ch === ')') paren = Math.max(0, paren - 1);
1132
+ else if (ch === '[') bracket++;
1133
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
1134
+ else if (ch === '{') brace++;
1135
+ else if (ch === '}') brace = Math.max(0, brace - 1);
1136
+ }
1137
+ if (paren <= 0 && bracket <= 0 && brace <= 0) {
1138
+ const t = lines[j].trimEnd();
1139
+ if (t.endsWith('\\') || (t.endsWith('=') && !t.endsWith('=>'))) continue;
1140
+ return j;
1141
+ }
1142
+ }
1143
+ return lastNonEmpty;
1144
+ };
1145
+ const footerStartRe =
1146
+ /^(?:export\s+default\s+(?!(?:async\s+)?(?:function|class|abstract\s+class|interface)\b)|export\s+(?:type\s+)?\{|export\s+\*\s+from\b|export\s+(?:const|let|var)\s+|module\.exports\s*=|exports\.[A-Za-z_$][A-Za-z0-9_$]*\s*=|(?:pub(?:\([^)]+\))?\s+)?(?:const|static)\s+[A-Za-z_][A-Za-z0-9_]*|(?:const|var)\s*\(|(?:const|var)\s+[A-Z][A-Za-z0-9_]*\b|(?:[A-Z][A-Z0-9_]+|__all__|__version__)\s*(?::\s*[^=\n]+)?=\s*(?!=))/;
1147
+ const chunks = [];
1148
+ let i = windowStart;
1149
+ while (i <= lastNonEmpty) {
1150
+ const raw = lines[i];
1151
+ if (!raw || /^\s/.test(raw)) { i++; continue; }
1152
+ const trimmed = raw.trim();
1153
+ if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('/*') || !footerStartRe.test(raw)) {
1154
+ i++; continue;
1155
+ }
1156
+ const endIdx = findTailStmtEnd(i);
1157
+ chunks.push({ startLine: i + 1, endLine: endIdx + 1, text: lines.slice(i, endIdx + 1).join('\n') });
1158
+ i = endIdx + 1;
1159
+ }
1160
+ if (chunks.length === 0) return null;
1161
+ return {
1162
+ footer: chunks.map((c) => c.text).join('\n'),
1163
+ startLine: chunks[0].startLine,
1164
+ endLine: chunks[chunks.length - 1].endLine,
1165
+ chunks
1166
+ };
1167
+ }
1168
+
1169
+
1170
+ async function collectProjectBlocks(root, scanRoot) {
1171
+ const files = [];
1172
+ const walk = (d) => {
1173
+ if (!fs.existsSync(d)) return;
1174
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
1175
+ if (IGNORE_DIRS.has(e.name)) continue;
1176
+ const full = path.join(d, e.name);
1177
+ if (e.isDirectory()) walk(full);
1178
+ else if (isAcceptedFile(e.name)) files.push(full);
1179
+ }
1180
+ };
1181
+ walk(scanRoot);
1182
+
1183
+ for (const cachedPath of FILE_CACHE.keys()) {
1184
+ if (!fs.existsSync(cachedPath)) {
1185
+ FILE_CACHE.delete(cachedPath);
1186
+ }
1187
+ }
1188
+
957
1189
  const allBlocks = [];
958
1190
  const headerMap = new Map();
1191
+ const footerMap = new Map();
1192
+ const lineCountMap = new Map();
959
1193
  for (const f of files) {
960
1194
  const rel = path.relative(root, f);
961
1195
  let stat;
@@ -970,27 +1204,36 @@ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
970
1204
  let items;
971
1205
  let parserMode = 'regex';
972
1206
  let fileHeader = null;
1207
+ let fileFooter = null;
1208
+ let fileLines = 0;
973
1209
  if (cached && cached.mtime === mtime) {
974
1210
  items = cached.items;
975
1211
  parserMode = cached.parserMode || 'regex';
976
1212
  fileHeader = cached.header ?? null;
1213
+ fileFooter = cached.footer ?? null;
1214
+ fileLines = cached.lineCount || 0;
977
1215
  } else {
978
1216
  const rawBuf = fs.readFileSync(f);
979
1217
  if (isBinaryBuffer(rawBuf)) continue;
980
1218
  const raw = rawBuf.toString('utf8');
1219
+ fileLines = raw.split('\n').length;
981
1220
  fileHeader = extractFileHeader(raw);
1221
+ fileFooter = extractFileFooter(raw);
982
1222
  const ext = path.extname(f);
983
1223
  const tsBlocks = await extractBlocksWithTreeSitter(raw, ext, rel);
984
1224
  if (tsBlocks && tsBlocks.length > 0) {
985
- items = tsBlocks;
1225
+ const extraConsts = extractTopLevelConstants(raw, ext, tsBlocks);
1226
+ items = extraConsts.length > 0 ? [...tsBlocks, ...extraConsts].sort((a, b) => a.startLine - b.startLine) : tsBlocks;
986
1227
  parserMode = 'tree-sitter-wasm';
987
1228
  } else {
988
1229
  items = extractBlocks(raw, ext, rel);
989
1230
  parserMode = 'state-machine-regex';
990
1231
  }
991
- FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader });
1232
+ FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
992
1233
  }
993
1234
  if (fileHeader) headerMap.set(rel, fileHeader);
1235
+ if (fileFooter) footerMap.set(rel, fileFooter);
1236
+ lineCountMap.set(rel, fileLines);
994
1237
 
995
1238
  for (const b of items) {
996
1239
  allBlocks.push({
@@ -1003,7 +1246,7 @@ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
1003
1246
  });
1004
1247
  }
1005
1248
  }
1006
- return { blocks: allBlocks, headerMap };
1249
+ return { blocks: allBlocks, headerMap, footerMap, lineCountMap };
1007
1250
  }
1008
1251
 
1009
1252
  function resolveScanRoot(projectPath, subPath) {
@@ -1027,16 +1270,19 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
1027
1270
  try {
1028
1271
  const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
1029
1272
  const wanted = new Set((symbols || []).map((s) => String(s).toLowerCase()));
1030
- const { blocks, headerMap } = await collectProjectBlocks(root, scanRoot);
1273
+ const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
1031
1274
  let used = 0;
1032
1275
  const expanded = [];
1033
1276
  const expandedFiles = new Set();
1034
1277
  const fullStart1EndLine = new Map();
1278
+ const coveredRangesByFile = new Map();
1035
1279
  for (const b of blocks) {
1036
1280
  const match = wanted.has(b.name.toLowerCase()) || [...wanted].some((w) => b.name.toLowerCase().includes(w) || b.rel.toLowerCase().includes(w));
1037
1281
  if (match && used + b.rawTk <= budget) {
1038
1282
  used += b.rawTk;
1039
1283
  expandedFiles.add(b.rel);
1284
+ if (!coveredRangesByFile.has(b.rel)) coveredRangesByFile.set(b.rel, []);
1285
+ coveredRangesByFile.get(b.rel).push([b.startLine, b.endLine]);
1040
1286
  if (b.startLine === 1) {
1041
1287
  fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
1042
1288
  }
@@ -1044,14 +1290,30 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
1044
1290
  }
1045
1291
  }
1046
1292
  const headerChunks = [];
1293
+ const headerEndByFile = new Map();
1047
1294
  for (const rel of expandedFiles) {
1048
1295
  const hdr = headerMap.get(rel);
1049
1296
  if (!hdr) continue;
1050
1297
  if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1298
+ headerEndByFile.set(rel, hdr.endLine);
1051
1299
  headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
1052
1300
  }
1301
+ const footerChunks = [];
1302
+ for (const rel of expandedFiles) {
1303
+ const ftr = footerMap.get(rel);
1304
+ if (!ftr) continue;
1305
+ const ranges = coveredRangesByFile.get(rel) || [];
1306
+ 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')}`);
1312
+ }
1313
+ }
1053
1314
  const hdrTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
1054
- return `<skeleton_expansion root="${root}" subPath="${subPath || ''}" expanded="${expanded.length}" used="${used}">${hdrTag}\n${expanded.join('\n\n')}\n</skeleton_expansion>`;
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>`;
1055
1317
  } catch (err) {
1056
1318
  return `Error: ${err.message}`;
1057
1319
  }
@@ -1061,7 +1323,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1061
1323
  try {
1062
1324
  const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
1063
1325
  const terms = expandQueryTerms(String(query));
1064
- const { blocks, headerMap } = await collectProjectBlocks(root, scanRoot);
1326
+ const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
1065
1327
  const totalBlocks = Math.max(1, blocks.length);
1066
1328
  const termDF = {};
1067
1329
  for (const t of terms) {
@@ -1091,13 +1353,20 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1091
1353
  return { ...b, score };
1092
1354
  }).sort((a, b) => b.score - a.score);
1093
1355
 
1094
- // 構建專案 SymbolMap 與基於單字邊界正則 (\bname\s*\() 的真實函式呼叫依賴圖 (True Call Graph)
1356
+ // 構建專案 SymbolMap 與真實依賴圖 (True Call Graph + Constants)
1095
1357
  const symbolMap = new Map();
1358
+ const constSymbolNames = new Set();
1096
1359
  for (let idx = 0; idx < allBlocks.length; idx++) {
1097
1360
  const b = allBlocks[idx];
1098
1361
  if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
1099
- if (!symbolMap.has(b.name)) symbolMap.set(b.name, []);
1100
- symbolMap.get(b.name).push(idx);
1362
+ const names = (b.kind === 'const' && b.name.includes(','))
1363
+ ? b.name.split(',').map((s) => s.trim()).filter(Boolean)
1364
+ : [b.name];
1365
+ for (const sn of names) {
1366
+ if (!symbolMap.has(sn)) symbolMap.set(sn, []);
1367
+ symbolMap.get(sn).push(idx);
1368
+ if (b.kind === 'const') constSymbolNames.add(sn);
1369
+ }
1101
1370
  }
1102
1371
  }
1103
1372
 
@@ -1110,7 +1379,8 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1110
1379
  if (sym === caller.name) continue;
1111
1380
  if (maskedCaller.includes(sym)) {
1112
1381
  const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1113
- const callRe = new RegExp('\\b' + esc + '\\s*\\(', 'm');
1382
+ const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
1383
+ const callRe = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
1114
1384
  if (callRe.test(maskedCaller)) {
1115
1385
  for (const t of (symbolMap.get(sym) || [])) {
1116
1386
  callAdj[i].add(t);
@@ -1123,11 +1393,13 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1123
1393
 
1124
1394
  // 計算自頂部修改重點 (Focal) 出發的 1 層 (1-hop) 與 2 層 (2-hop) 關聯距離
1125
1395
  const focalIndices = [];
1396
+ const focalFiles = new Set();
1126
1397
  const hopDistances = new Map();
1127
1398
  for (let i = 0; i < allBlocks.length; i++) {
1128
1399
  if (allBlocks[i].score > 0 && focalIndices.length < 3) {
1129
1400
  focalIndices.push(i);
1130
1401
  hopDistances.set(i, 0);
1402
+ focalFiles.add(allBlocks[i].rel);
1131
1403
  }
1132
1404
  }
1133
1405
 
@@ -1151,7 +1423,13 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1151
1423
  const focalNames = new Set();
1152
1424
  const includedIds = new Set();
1153
1425
  const includedFiles = new Set();
1426
+ const partialFiles = new Set();
1154
1427
  const fullStart1EndLine = new Map();
1428
+ const coveredRangesByFile = new Map();
1429
+ const addCoveredRange = (rel, s, e) => {
1430
+ if (!coveredRangesByFile.has(rel)) coveredRangesByFile.set(rel, []);
1431
+ coveredRangesByFile.get(rel).push([s, e]);
1432
+ };
1155
1433
  const candidateItems = [];
1156
1434
  const dirBudgetUsed = {};
1157
1435
  const maxDirBudget = budget * 0.65;
@@ -1169,22 +1447,30 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1169
1447
  focalNames.add(b.name);
1170
1448
  includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1171
1449
  includedFiles.add(b.rel);
1450
+ addCoveredRange(b.rel, b.startLine, b.endLine);
1172
1451
  if (b.startLine === 1) {
1173
1452
  fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
1174
1453
  }
1175
1454
  fullChunks.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [${b.parserMode}]\n${b.full}`);
1176
1455
  } else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
1177
- const linked = (hop !== undefined && hop <= 2) || b.score > 0;
1456
+ const sameFileConst = b.kind === 'const' && (b.exported || /^[A-Z][A-Z0-9_]+$/.test(b.name)) && b.lineCount <= 25 && focalFiles.has(b.rel);
1457
+ const linked = (hop !== undefined && hop <= 2) || b.score > 0 || sameFileConst;
1178
1458
  if (linked || i < 12) {
1179
1459
  used += b.skelTk;
1180
1460
  dirBudgetUsed[topDir] = curDir + b.skelTk;
1181
1461
  skelCandidates.push({ ...b, linked, hop: hop ?? null });
1182
1462
  includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
1183
1463
  includedFiles.add(b.rel);
1464
+ partialFiles.add(b.rel);
1465
+ if (b.skeleton === b.full) {
1466
+ addCoveredRange(b.rel, b.startLine, b.endLine);
1467
+ }
1184
1468
  } else {
1469
+ partialFiles.add(b.rel);
1185
1470
  candidateItems.push(b);
1186
1471
  }
1187
1472
  } else {
1473
+ partialFiles.add(b.rel);
1188
1474
  candidateItems.push(b);
1189
1475
  }
1190
1476
  }
@@ -1201,6 +1487,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1201
1487
  used += delta;
1202
1488
  dirBudgetUsed[topDir] = curDir + delta;
1203
1489
  autoExpandedNames.push(item.name);
1490
+ addCoveredRange(item.rel, item.startLine, item.endLine);
1204
1491
  if (item.startLine === 1) {
1205
1492
  fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, item.endLine));
1206
1493
  }
@@ -1212,14 +1499,32 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1212
1499
  }
1213
1500
 
1214
1501
  const headerChunks = [];
1502
+ const headerEndByFile = new Map();
1215
1503
  for (const rel of includedFiles) {
1216
1504
  const hdr = headerMap.get(rel);
1217
1505
  if (!hdr) continue;
1218
1506
  if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1507
+ headerEndByFile.set(rel, hdr.endLine);
1219
1508
  headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
1220
1509
  }
1221
1510
  const headerTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
1222
1511
 
1512
+ const footerChunks = [];
1513
+ for (const rel of includedFiles) {
1514
+ const ftr = footerMap.get(rel);
1515
+ if (!ftr) continue;
1516
+ const ranges = coveredRangesByFile.get(rel) || [];
1517
+ const totalLines = lineCountMap.get(rel) || 0;
1518
+ const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
1519
+ if (!partialFiles.has(rel) && wholeFileCovered) continue;
1520
+ const hdrEnd = headerEndByFile.get(rel) || 0;
1521
+ const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1522
+ 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')}`);
1524
+ }
1525
+ }
1526
+ const footerTag = footerChunks.length > 0 ? `\n<file_footers>\n${footerChunks.join('\n\n')}\n</file_footers>` : '';
1527
+
1223
1528
  const omitted = candidateItems.filter(b => b.score > 0 && !includedIds.has(b.rel + ':' + b.name + '@' + b.startLine)).slice(0, 3);
1224
1529
  const omittedTag = omitted.length > 0
1225
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>`
@@ -1227,7 +1532,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1227
1532
 
1228
1533
  const expandTag = autoExpandedNames.length > 0 ? ` autoExpanded="${autoExpandedNames.join(',')}"` : '';
1229
1534
  const subPathTag = subPath ? ` subPath="${subPath}"` : '';
1230
- return `<context_slice root="${root}" version="0.3.3"${subPathTag} budget="${budget}" used="${used}"${expandTag}>${headerTag}\n<skeletons>\n${finalSkelChunks.join('\n')}\n</skeletons>\n<focal>\n${fullChunks.join('\n\n')}\n</focal>${omittedTag}\n</context_slice>`;
1535
+ return `<context_slice root="${root}" version="0.3.4"${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>`;
1231
1536
  } catch (err) {
1232
1537
  return `Error: ${err.message}`;
1233
1538
  }
@@ -1246,7 +1551,7 @@ rl.on('line', async (line) => {
1246
1551
  return send({
1247
1552
  protocolVersion: req.params?.protocolVersion || '2024-11-05',
1248
1553
  capabilities: { tools: {} },
1249
- serverInfo: { name: 'ctxslice-thin', version: '0.3.3' }
1554
+ serverInfo: { name: 'ctxslice-thin', version: '0.3.4' }
1250
1555
  });
1251
1556
  }
1252
1557
  if (req.method === 'ping') return send({});
package/bin/ctxslice.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ctxslice.mjs — Zero-Config Multi-Language Local AST Context Pre-Compiler (v0.3.3)
3
+ * ctxslice.mjs — Zero-Config Multi-Language Local AST Context Pre-Compiler (v0.3.4)
4
4
  * Features: Multi-Language AST Extractors, State-Machine Brace Matcher, True Call Graph (BFS), TF-IDF, Directory Quota Cap
5
5
  */
6
6
  import fs from 'node:fs';
@@ -372,12 +372,12 @@ function expandQueryTerms(query) {
372
372
 
373
373
  const args = process.argv.slice(2);
374
374
  if (args.includes('--version') || args.includes('-v')) {
375
- process.stdout.write('ctxslice v0.3.3\n');
375
+ process.stdout.write('ctxslice v0.3.4\n');
376
376
  process.exit(0);
377
377
  }
378
378
  if (args.includes('--help') || args.includes('-h')) {
379
379
  process.stdout.write(
380
- 'ContextSlice CLI v0.3.3 — Zero-Config Multi-Language AST Slicer\n\n' +
380
+ 'ContextSlice CLI v0.3.4 — Zero-Config Multi-Language AST Slicer\n\n' +
381
381
  'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
382
382
  'Options:\n --root <dir> Target repository path (default: current directory)\n' +
383
383
  ' --budget <num> Max token budget (default: 32768)\n' +
@@ -577,17 +577,25 @@ function extractBlocks(code, ext, fileName) {
577
577
  }
578
578
 
579
579
  if (name) {
580
- const end = findBraceEnd(lines, i);
580
+ const isStmtOnly = kind === 'const' || (kind === 'type' && !line.includes('{'));
581
+ const end = isStmtOnly ? findStatementEndLine(lines, i, 'ts') : findBraceEnd(lines, i);
581
582
  const full = lines.slice(i, end + 1).join('\n');
582
583
  const sigIdx = full.indexOf('{');
583
- const skeleton = (kind === 'interface' || kind === 'type' || sigIdx === -1 || end - i < 4)
584
+ const isShortConst = kind === 'const' && (end - i + 1) <= 10 && !full.includes('=>');
585
+ const skeleton = (kind === 'interface' || kind === 'type' || isShortConst || sigIdx === -1 || end - i < 4)
584
586
  ? full
585
587
  : full.slice(0, sigIdx).trim() + ` { /* ... ${end - i - 1} lines folded */ }`;
586
- blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
588
+ blocks.push({ name, kind, exported: line.startsWith('export '), startLine: i + 1, endLine: end + 1, full, skeleton });
587
589
  if (kind !== 'class' && kind !== 'module') i = end;
588
590
  }
589
591
  }
590
592
 
593
+ const topConsts = extractTopLevelConstants(code, e, blocks);
594
+ if (topConsts.length > 0) {
595
+ blocks.push(...topConsts);
596
+ blocks.sort((a, b) => a.startLine - b.startLine);
597
+ }
598
+
591
599
  if (blocks.length === 0 && lines.length > 0) {
592
600
  const name = path.basename(fileName || ('file' + e));
593
601
  const full = code;
@@ -728,18 +736,247 @@ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
728
736
  }
729
737
 
730
738
 
739
+ function findStatementEndLine(lines, startIdx, mode) {
740
+ let parenDepth = 0;
741
+ let bracketDepth = 0;
742
+ let braceDepth = 0;
743
+ let inBlockComment = false;
744
+ let pyTripleQuote = null;
745
+ const maxScan = Math.min(lines.length - 1, startIdx + 120);
746
+
747
+ for (let j = startIdx; j <= maxScan; j++) {
748
+ const raw = lines[j];
749
+ const len = raw.length;
750
+ let k = 0;
751
+ while (k < len) {
752
+ const ch = raw[k];
753
+ const next = raw[k + 1];
754
+ const next3 = mode === 'py' ? raw.slice(k, k + 3) : '';
755
+ if (pyTripleQuote) {
756
+ if (next3 === pyTripleQuote) { pyTripleQuote = null; k += 3; continue; }
757
+ k++; continue;
758
+ }
759
+ if (inBlockComment) {
760
+ if (ch === '*' && next === '/') { inBlockComment = false; k += 2; continue; }
761
+ k++; continue;
762
+ }
763
+ if (mode === 'py' && ch === '#') break;
764
+ if (mode !== 'py' && ch === '/' && next === '/') break;
765
+ if (mode !== 'py' && ch === '/' && next === '*') { inBlockComment = true; k += 2; continue; }
766
+ if (mode === 'py' && (next3 === '"""' || next3 === "'''")) { pyTripleQuote = next3; k += 3; continue; }
767
+ if (ch === '"' || ch === "'" || (mode === 'ts' && ch === '\x60') || (mode === 'go' && ch === '\x60')) {
768
+ const quote = ch;
769
+ k++;
770
+ while (k < len) {
771
+ if (quote !== '\x60' && raw[k] === '\\') { k += 2; continue; }
772
+ if (raw[k] === quote) { k++; break; }
773
+ k++;
774
+ }
775
+ continue;
776
+ }
777
+ if (ch === '(') parenDepth++;
778
+ else if (ch === ')') parenDepth = Math.max(0, parenDepth - 1);
779
+ else if (ch === '[') bracketDepth++;
780
+ else if (ch === ']') bracketDepth = Math.max(0, bracketDepth - 1);
781
+ else if (ch === '{') braceDepth++;
782
+ else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
783
+ k++;
784
+ }
785
+ if (!inBlockComment && !pyTripleQuote && parenDepth <= 0 && bracketDepth <= 0 && braceDepth <= 0) {
786
+ const trimmedEnd = raw.trimEnd();
787
+ if (trimmedEnd.endsWith('\\')) continue;
788
+ if (trimmedEnd.endsWith('=') && !trimmedEnd.endsWith('=>')) continue;
789
+ return j;
790
+ }
791
+ }
792
+ return maxScan;
793
+ }
794
+
795
+ function extractTopLevelConstants(code, ext, existingBlocks) {
796
+ const e = (ext || '').toLowerCase();
797
+ const lines = String(code || '').replace(/\r\n/g, '\n').split('\n');
798
+ const covered = (existingBlocks || []).map((b) => [b.startLine, b.endLine]);
799
+ const isCovered = (ln) => covered.some(([s, en]) => ln >= s && ln <= en);
800
+ const out = [];
801
+
802
+ if (e === '.py' || e === '.pyw') {
803
+ for (let i = 0; i < lines.length; i++) {
804
+ const ln = i + 1;
805
+ if (isCovered(ln)) continue;
806
+ const line = lines[i];
807
+ const m = line.match(/^([A-Z][A-Z0-9_]+|__all__|__version__)\s*(?::\s*[^=\n]+)?=\s*(?!=)/);
808
+ if (!m) continue;
809
+ const endIdx = findStatementEndLine(lines, i, 'py');
810
+ const endLine = endIdx + 1;
811
+ covered.push([ln, endLine]);
812
+ const full = lines.slice(i, endLine).join('\n');
813
+ const lineCount = endLine - ln + 1;
814
+ const skeleton = lineCount <= 8 ? full : line + '\n # ... ' + (lineCount - 1) + ' lines folded';
815
+ out.push({ name: m[1], kind: 'const', exported: !m[1].startsWith('_') || m[1] === '__all__', startLine: ln, endLine, full, skeleton });
816
+ i = endIdx;
817
+ }
818
+ return out;
819
+ }
820
+
821
+ if (e === '.go') {
822
+ for (let i = 0; i < lines.length; i++) {
823
+ const ln = i + 1;
824
+ if (isCovered(ln)) continue;
825
+ const line = lines[i];
826
+ const gm = line.match(/^(const|var)\s*\(/);
827
+ if (gm) {
828
+ const endIdx = findStatementEndLine(lines, i, 'go');
829
+ const endLine = endIdx + 1;
830
+ covered.push([ln, endLine]);
831
+ const names = [];
832
+ for (let j = i + 1; j <= endIdx; j++) {
833
+ const im = lines[j].match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\b/);
834
+ if (im && im[1] !== '_' && im[1] !== 'iota') names.push(im[1]);
835
+ }
836
+ const name = names.length > 0 ? names.slice(0, 4).join(', ') : gm[1] + '_block';
837
+ const full = lines.slice(i, endLine).join('\n');
838
+ const lineCount = endLine - ln + 1;
839
+ const skeleton = lineCount <= 12 ? full : line + '\n\t// ... ' + (lineCount - 2) + ' lines folded\n)';
840
+ out.push({ name, kind: 'const', exported: names.some((n) => /^[A-Z]/.test(n)), startLine: ln, endLine, full, skeleton });
841
+ i = endIdx;
842
+ continue;
843
+ }
844
+ const sm = line.match(/^(const|var)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
845
+ if (sm) {
846
+ const endIdx = findStatementEndLine(lines, i, 'go');
847
+ const endLine = endIdx + 1;
848
+ covered.push([ln, endLine]);
849
+ const full = lines.slice(i, endLine).join('\n');
850
+ const lineCount = endLine - ln + 1;
851
+ const skeleton = lineCount <= 8 ? full : line + '\n\t// ... ' + (lineCount - 1) + ' lines folded';
852
+ out.push({ name: sm[2], kind: 'const', exported: /^[A-Z]/.test(sm[2]), startLine: ln, endLine, full, skeleton });
853
+ i = endIdx;
854
+ }
855
+ }
856
+ return out;
857
+ }
858
+
859
+ if (e === '.rs') {
860
+ for (let i = 0; i < lines.length; i++) {
861
+ const ln = i + 1;
862
+ if (isCovered(ln)) continue;
863
+ const line = lines[i];
864
+ const rm = line.match(/^(?:pub(?:\([^)]+\))?\s+)?(?:const|static)\s+([A-Z][A-Z0-9_]*)\b/);
865
+ if (!rm) continue;
866
+ const endIdx = findStatementEndLine(lines, i, 'rs');
867
+ const endLine = endIdx + 1;
868
+ covered.push([ln, endLine]);
869
+ const full = lines.slice(i, endLine).join('\n');
870
+ const lineCount = endLine - ln + 1;
871
+ const skeleton = lineCount <= 8 ? full : line + '\n /* ... ' + (lineCount - 1) + ' lines folded */';
872
+ out.push({ name: rm[1], kind: 'const', exported: line.startsWith('pub'), startLine: ln, endLine, full, skeleton });
873
+ i = endIdx;
874
+ }
875
+ return out;
876
+ }
877
+
878
+ if (['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'].includes(e)) {
879
+ for (let i = 0; i < lines.length; i++) {
880
+ const ln = i + 1;
881
+ if (isCovered(ln)) continue;
882
+ const line = lines[i];
883
+ let name = null;
884
+ let exported = false;
885
+ const cm = line.match(/^(export\s+)?(?:declare\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/);
886
+ if (cm) {
887
+ exported = Boolean(cm[1]);
888
+ if (exported || /^[A-Z][A-Z0-9_]+$/.test(cm[2])) name = cm[2];
889
+ } else {
890
+ const tm = line.match(/^(?:export\s+(default)\s+(?!(?:async\s+)?(?:function|class|abstract\s+class|interface)\b)|(module\.exports)\s*=)/);
891
+ if (tm) { name = tm[1] ? 'default' : 'module.exports'; exported = true; }
892
+ }
893
+ if (!name) continue;
894
+ const endIdx = findStatementEndLine(lines, i, 'ts');
895
+ const endLine = endIdx + 1;
896
+ const full = lines.slice(i, endLine).join('\n');
897
+ if (full.includes('=>') && !name.startsWith('default')) continue;
898
+ covered.push([ln, endLine]);
899
+ const lineCount = endLine - ln + 1;
900
+ const skeleton = lineCount <= 10 ? full : line + '\n /* ... ' + (lineCount - 1) + ' lines folded */';
901
+ out.push({ name, kind: 'const', exported, startLine: ln, endLine, full, skeleton });
902
+ i = endIdx;
903
+ }
904
+ }
905
+ return out;
906
+ }
907
+
908
+ function extractFileFooter(content, tailLines = 20) {
909
+ if (!content) return null;
910
+ const lines = String(content).replace(/\r\n/g, '\n').split('\n');
911
+ let lastNonEmpty = lines.length - 1;
912
+ while (lastNonEmpty >= 0 && lines[lastNonEmpty].trim() === '') lastNonEmpty--;
913
+ if (lastNonEmpty < 0) return null;
914
+ const windowStart = Math.max(0, lastNonEmpty - tailLines + 1);
915
+ const stripFooterNoise = (line) =>
916
+ line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
917
+ const findTailStmtEnd = (startIdx) => {
918
+ let paren = 0, bracket = 0, brace = 0;
919
+ for (let j = startIdx; j <= lastNonEmpty; j++) {
920
+ const clean = stripFooterNoise(lines[j]);
921
+ for (let k = 0; k < clean.length; k++) {
922
+ const ch = clean[k];
923
+ if (ch === '(') paren++;
924
+ else if (ch === ')') paren = Math.max(0, paren - 1);
925
+ else if (ch === '[') bracket++;
926
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
927
+ else if (ch === '{') brace++;
928
+ else if (ch === '}') brace = Math.max(0, brace - 1);
929
+ }
930
+ if (paren <= 0 && bracket <= 0 && brace <= 0) {
931
+ const t = lines[j].trimEnd();
932
+ if (t.endsWith('\\') || (t.endsWith('=') && !t.endsWith('=>'))) continue;
933
+ return j;
934
+ }
935
+ }
936
+ return lastNonEmpty;
937
+ };
938
+ const footerStartRe =
939
+ /^(?:export\s+default\s+(?!(?:async\s+)?(?:function|class|abstract\s+class|interface)\b)|export\s+(?:type\s+)?\{|export\s+\*\s+from\b|export\s+(?:const|let|var)\s+|module\.exports\s*=|exports\.[A-Za-z_$][A-Za-z0-9_$]*\s*=|(?:pub(?:\([^)]+\))?\s+)?(?:const|static)\s+[A-Za-z_][A-Za-z0-9_]*|(?:const|var)\s*\(|(?:const|var)\s+[A-Z][A-Za-z0-9_]*\b|(?:[A-Z][A-Z0-9_]+|__all__|__version__)\s*(?::\s*[^=\n]+)?=\s*(?!=))/;
940
+ const chunks = [];
941
+ let i = windowStart;
942
+ while (i <= lastNonEmpty) {
943
+ const raw = lines[i];
944
+ if (!raw || /^\s/.test(raw)) { i++; continue; }
945
+ const trimmed = raw.trim();
946
+ if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('/*') || !footerStartRe.test(raw)) {
947
+ i++; continue;
948
+ }
949
+ const endIdx = findTailStmtEnd(i);
950
+ chunks.push({ startLine: i + 1, endLine: endIdx + 1, text: lines.slice(i, endIdx + 1).join('\n') });
951
+ i = endIdx + 1;
952
+ }
953
+ if (chunks.length === 0) return null;
954
+ return {
955
+ footer: chunks.map((c) => c.text).join('\n'),
956
+ startLine: chunks[0].startLine,
957
+ endLine: chunks[chunks.length - 1].endLine,
958
+ chunks
959
+ };
960
+ }
961
+
962
+
731
963
  const files = walk(targetRoot);
732
964
  const terms = expandQueryTerms(query);
733
965
  const allRawBlocks = [];
734
966
  const fileHeaders = new Map();
967
+ const fileFooters = new Map();
968
+ const fileLineCounts = new Map();
735
969
  for (const filePath of files) {
736
970
  try {
737
971
  const buf = fs.readFileSync(filePath);
738
972
  if (isBinaryBuffer(buf)) continue;
739
973
  const content = buf.toString('utf8');
740
974
  const relPath = path.relative(targetRoot, filePath);
975
+ fileLineCounts.set(relPath, content.split('\n').length);
741
976
  const hdr = extractFileHeader(content);
742
977
  if (hdr) fileHeaders.set(relPath, hdr);
978
+ const ftr = extractFileFooter(content);
979
+ if (ftr) fileFooters.set(relPath, ftr);
743
980
  const items = extractBlocks(content, path.extname(filePath), relPath);
744
981
  for (const b of items) {
745
982
  allRawBlocks.push({
@@ -781,13 +1018,20 @@ const scored = allRawBlocks.map((b) => {
781
1018
  return { ...b, score };
782
1019
  }).sort((a, b) => b.score - a.score);
783
1020
 
784
- // True Call Graph (SymbolMap + Word-Boundary Call Matching + BFS maxHops)
1021
+ // True Call Graph (SymbolMap + Word-Boundary Call/Constant Matching + BFS maxHops)
785
1022
  const symbolMap = new Map();
1023
+ const constSymbolNames = new Set();
786
1024
  for (let i = 0; i < scored.length; i++) {
787
1025
  const b = scored[i];
788
1026
  if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
789
- if (!symbolMap.has(b.name)) symbolMap.set(b.name, []);
790
- symbolMap.get(b.name).push(i);
1027
+ const names = (b.kind === 'const' && b.name.includes(','))
1028
+ ? b.name.split(',').map((s) => s.trim()).filter(Boolean)
1029
+ : [b.name];
1030
+ for (const sn of names) {
1031
+ if (!symbolMap.has(sn)) symbolMap.set(sn, []);
1032
+ symbolMap.get(sn).push(i);
1033
+ if (b.kind === 'const') constSymbolNames.add(sn);
1034
+ }
791
1035
  }
792
1036
  }
793
1037
  const callAdj = Array.from({ length: scored.length }, () => new Set());
@@ -799,7 +1043,9 @@ for (let i = 0; i < scored.length; i++) {
799
1043
  if (sym === caller.name) continue;
800
1044
  if (maskedCaller.includes(sym)) {
801
1045
  const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
802
- if (new RegExp('\\b' + esc + '\\s*\\(', 'm').test(maskedCaller)) {
1046
+ const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
1047
+ const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
1048
+ if (re.test(maskedCaller)) {
803
1049
  for (const t of (symbolMap.get(sym) || [])) {
804
1050
  callAdj[i].add(t);
805
1051
  callAdj[t].add(i);
@@ -809,11 +1055,13 @@ for (let i = 0; i < scored.length; i++) {
809
1055
  }
810
1056
  }
811
1057
  const hopDistances = new Map();
1058
+ const focalFiles = new Set();
812
1059
  const bfsQ = [];
813
1060
  for (let i = 0; i < scored.length; i++) {
814
1061
  if (scored[i].score > 0 && bfsQ.length < 3) {
815
1062
  bfsQ.push(i);
816
1063
  hopDistances.set(i, 0);
1064
+ focalFiles.add(scored[i].filePath);
817
1065
  }
818
1066
  }
819
1067
  let qHead = 0;
@@ -830,10 +1078,16 @@ while (qHead < bfsQ.length) {
830
1078
  }
831
1079
 
832
1080
  let remaining = budget;
833
- const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.3" budget="' + budget + '">'];
1081
+ const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.4" budget="' + budget + '">'];
834
1082
  const includedIds = new Set();
835
1083
  const includedFiles = new Set();
836
1084
  const fullStart1EndLine = new Map();
1085
+ const coveredRangesByFile = new Map();
1086
+ const partialFiles = new Set();
1087
+ const addCoveredRange = (fp, s, e) => {
1088
+ if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
1089
+ coveredRangesByFile.get(fp).push([s, e]);
1090
+ };
837
1091
  const dirBudgetUsed = {};
838
1092
  const maxDirBudget = budget * 0.65;
839
1093
 
@@ -851,34 +1105,44 @@ for (let i = 0; i < scored.length; i++) {
851
1105
  dirBudgetUsed[topDir] = curDir + item.rawTokens;
852
1106
  includedIds.add(key);
853
1107
  includedFiles.add(item.filePath);
1108
+ addCoveredRange(item.filePath, item.startLine, item.endLine);
854
1109
  if (item.startLine === 1) {
855
1110
  fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
856
1111
  }
857
1112
  out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
858
1113
  out.push(item.full);
859
1114
  } else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
860
- const linked = (hop !== undefined && hop <= 2) || item.score > 0;
1115
+ const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && (item.endLine - item.startLine + 1) <= 25 && focalFiles.has(item.filePath);
1116
+ const linked = (hop !== undefined && hop <= 2) || item.score > 0 || sameFileConst;
861
1117
  if (linked || i < 12) {
862
1118
  remaining -= item.skelTokens;
863
1119
  dirBudgetUsed[topDir] = curDir + item.skelTokens;
864
1120
  includedIds.add(key);
865
1121
  includedFiles.add(item.filePath);
1122
+ partialFiles.add(item.filePath);
1123
+ if (item.skeleton === item.full) {
1124
+ addCoveredRange(item.filePath, item.startLine, item.endLine);
1125
+ }
866
1126
  out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
867
1127
  out.push(item.skeleton);
868
1128
  } else {
1129
+ partialFiles.add(item.filePath);
869
1130
  candidateItems.push(item);
870
1131
  }
871
1132
  } else {
1133
+ partialFiles.add(item.filePath);
872
1134
  candidateItems.push(item);
873
1135
  }
874
1136
  }
875
1137
 
876
1138
  const headerChunks = [];
1139
+ const headerEndByFile = new Map();
877
1140
  for (const fp of includedFiles) {
878
1141
  const hdr = fileHeaders.get(fp);
879
1142
  if (!hdr) continue;
880
1143
  const coveredEnd = fullStart1EndLine.get(fp) || 0;
881
1144
  if (coveredEnd >= hdr.endLine) continue;
1145
+ headerEndByFile.set(fp, hdr.endLine);
882
1146
  headerChunks.push(` <!-- FILE_HEADER: ${fp}:1-${hdr.endLine} -->`);
883
1147
  headerChunks.push(hdr.header);
884
1148
  }
@@ -886,6 +1150,25 @@ if (headerChunks.length > 0) {
886
1150
  out.splice(1, 0, '<file_headers>', ...headerChunks, '</file_headers>');
887
1151
  }
888
1152
 
1153
+ const footerChunks = [];
1154
+ for (const fp of includedFiles) {
1155
+ const ftr = fileFooters.get(fp);
1156
+ if (!ftr) continue;
1157
+ const ranges = coveredRangesByFile.get(fp) || [];
1158
+ const totalLines = fileLineCounts.get(fp) || 0;
1159
+ const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
1160
+ if (!partialFiles.has(fp) && wholeFileCovered) continue;
1161
+ const hdrEnd = headerEndByFile.get(fp) || 0;
1162
+ const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1163
+ if (uncovered.length > 0) {
1164
+ footerChunks.push(` <!-- FILE_FOOTER: ${fp}:${uncovered[0].startLine}-${uncovered[uncovered.length - 1].endLine} -->`);
1165
+ footerChunks.push(uncovered.map((c) => c.text).join('\n'));
1166
+ }
1167
+ }
1168
+ if (footerChunks.length > 0) {
1169
+ out.push('<file_footers>', ...footerChunks, '</file_footers>');
1170
+ }
1171
+
889
1172
  const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
890
1173
  if (omitted.length > 0) {
891
1174
  out.push('<omitted_top_matches>');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grundy40/contextslice",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Zero-dependency multi-language AST code slicer & 1-Tool MCP server for AI coding assistants (Claude Code, OpenCode, Pi Agent, Cursor).",
5
5
  "type": "module",
6
6
  "bin": {