@grundy40/contextslice 0.3.2 → 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.2
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.2\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.2) 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,6 +812,361 @@ function extractBlocks(code, ext, fileName) {
804
812
  return blocks;
805
813
  }
806
814
 
815
+
816
+ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
817
+ if (!content) return null;
818
+ const lines = String(content).replace(/\r\n/g, '\n').split('\n');
819
+ const limit = Math.min(lines.length, maxLines);
820
+ const funcOrClassStartRe =
821
+ /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:async\s+)?(?:function\*?\s+|class\s+)|^(?:async\s+)?def\s+|^func\s+|^(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?(?:fn|struct|impl|trait)\s+|^(?:public|private|protected|internal|static|final|abstract|async|override|\s)*(?:class|record)\s+/;
822
+ const importOrTypeOrVarRe =
823
+ /^(?:import\b|export\s+(?:type|interface|const|let|var|enum)\b|type\s+|interface\s+|const\s+|let\s+|var\s+|package\s+|using\s+|from\s+\S+\s+import\b|#include\b|#define\b)/;
824
+ const stripLineNoise = (line) =>
825
+ line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
826
+
827
+ const countBlockSpan = (startIdx) => {
828
+ let depth = 0;
829
+ let opened = false;
830
+ const scanMax = Math.min(lines.length, startIdx + maxObjectLines + 5);
831
+ for (let j = startIdx; j < scanMax; j++) {
832
+ const clean = stripLineNoise(lines[j]);
833
+ for (let k = 0; k < clean.length; k++) {
834
+ const ch = clean[k];
835
+ if (ch === '{' || ch === '[') {
836
+ depth++;
837
+ opened = true;
838
+ } else if (ch === '}' || ch === ']') {
839
+ depth--;
840
+ if (opened && depth <= 0) return j - startIdx + 1;
841
+ }
842
+ }
843
+ }
844
+ return opened ? maxObjectLines + 1 : 1;
845
+ };
846
+
847
+ let inBlockComment = false;
848
+ let lastSafeEnd = 0;
849
+ let i = 0;
850
+
851
+ while (i < limit) {
852
+ const raw = lines[i];
853
+ const trimmed = raw.trim();
854
+
855
+ if (inBlockComment) {
856
+ if (trimmed.includes('*/')) inBlockComment = false;
857
+ i++;
858
+ continue;
859
+ }
860
+ if (trimmed === '' || trimmed.startsWith('//') || trimmed.startsWith('#')) {
861
+ i++;
862
+ continue;
863
+ }
864
+ if (trimmed.startsWith('/*')) {
865
+ if (!trimmed.includes('*/')) inBlockComment = true;
866
+ i++;
867
+ continue;
868
+ }
869
+
870
+ if (funcOrClassStartRe.test(trimmed)) break;
871
+ if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+[^;\n]*=>/.test(trimmed)) break;
872
+ if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\([^)]*$/.test(trimmed)) {
873
+ const lookahead = lines.slice(i, Math.min(lines.length, i + 6)).join(' ');
874
+ if (lookahead.includes('=>')) break;
875
+ }
876
+ if (
877
+ !importOrTypeOrVarRe.test(trimmed) &&
878
+ /^(?:[\w<>[\],*&:.]+\s+)+[A-Za-z_][A-Za-z0-9_]*\s*\([^;]*\)\s*(?:const|override|throws\s+[\w,\s]+)?\s*\{?$/.test(trimmed)
879
+ ) {
880
+ break;
881
+ }
882
+
883
+ const cleanLine = stripLineNoise(raw);
884
+ let netDelta = 0;
885
+ let hasOpener = false;
886
+ for (let k = 0; k < cleanLine.length; k++) {
887
+ if (cleanLine[k] === '{' || cleanLine[k] === '[') {
888
+ netDelta++;
889
+ hasOpener = true;
890
+ } else if (cleanLine[k] === '}' || cleanLine[k] === ']') {
891
+ netDelta--;
892
+ }
893
+ }
894
+
895
+ if (hasOpener && netDelta > 0) {
896
+ const span = countBlockSpan(i);
897
+ const isImport = /^(?:import|export\s+type\s*\{)/.test(trimmed);
898
+ if ((!isImport && span > maxObjectLines) || i + span > limit) break;
899
+ i += span;
900
+ lastSafeEnd = i;
901
+ continue;
902
+ }
903
+
904
+ if (
905
+ /^(?:import|export\s+type|type|const|let|var)\b/.test(trimmed) &&
906
+ (trimmed.endsWith('(') || trimmed.endsWith('=')) &&
907
+ i + 1 < limit
908
+ ) {
909
+ let j = i + 1;
910
+ while (j < limit) {
911
+ const nextT = lines[j].trim();
912
+ if (nextT.endsWith(')') || nextT.endsWith(';')) {
913
+ j++;
914
+ break;
915
+ }
916
+ if (
917
+ nextT === '' ||
918
+ (!nextT.startsWith('|') && !nextT.startsWith('&') && !nextT.startsWith('"') && !nextT.startsWith("'"))
919
+ ) {
920
+ break;
921
+ }
922
+ j++;
923
+ }
924
+ if (j <= limit) {
925
+ i = j;
926
+ lastSafeEnd = i;
927
+ continue;
928
+ }
929
+ break;
930
+ }
931
+
932
+ i++;
933
+ lastSafeEnd = i;
934
+ }
935
+
936
+ if (lastSafeEnd <= 0) return null;
937
+ const headerLines = lines.slice(0, lastSafeEnd);
938
+ while (headerLines.length > 0 && headerLines[headerLines.length - 1].trim() === '') {
939
+ headerLines.pop();
940
+ }
941
+ if (headerLines.length === 0) return null;
942
+ return { header: headerLines.join('\n'), endLine: headerLines.length };
943
+ }
944
+
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
+
807
1170
  async function collectProjectBlocks(root, scanRoot) {
808
1171
  const files = [];
809
1172
  const walk = (d) => {
@@ -824,6 +1187,9 @@ async function collectProjectBlocks(root, scanRoot) {
824
1187
  }
825
1188
 
826
1189
  const allBlocks = [];
1190
+ const headerMap = new Map();
1191
+ const footerMap = new Map();
1192
+ const lineCountMap = new Map();
827
1193
  for (const f of files) {
828
1194
  const rel = path.relative(root, f);
829
1195
  let stat;
@@ -837,24 +1203,37 @@ async function collectProjectBlocks(root, scanRoot) {
837
1203
 
838
1204
  let items;
839
1205
  let parserMode = 'regex';
1206
+ let fileHeader = null;
1207
+ let fileFooter = null;
1208
+ let fileLines = 0;
840
1209
  if (cached && cached.mtime === mtime) {
841
1210
  items = cached.items;
842
1211
  parserMode = cached.parserMode || 'regex';
1212
+ fileHeader = cached.header ?? null;
1213
+ fileFooter = cached.footer ?? null;
1214
+ fileLines = cached.lineCount || 0;
843
1215
  } else {
844
1216
  const rawBuf = fs.readFileSync(f);
845
1217
  if (isBinaryBuffer(rawBuf)) continue;
846
1218
  const raw = rawBuf.toString('utf8');
1219
+ fileLines = raw.split('\n').length;
1220
+ fileHeader = extractFileHeader(raw);
1221
+ fileFooter = extractFileFooter(raw);
847
1222
  const ext = path.extname(f);
848
1223
  const tsBlocks = await extractBlocksWithTreeSitter(raw, ext, rel);
849
1224
  if (tsBlocks && tsBlocks.length > 0) {
850
- items = tsBlocks;
1225
+ const extraConsts = extractTopLevelConstants(raw, ext, tsBlocks);
1226
+ items = extraConsts.length > 0 ? [...tsBlocks, ...extraConsts].sort((a, b) => a.startLine - b.startLine) : tsBlocks;
851
1227
  parserMode = 'tree-sitter-wasm';
852
1228
  } else {
853
1229
  items = extractBlocks(raw, ext, rel);
854
1230
  parserMode = 'state-machine-regex';
855
1231
  }
856
- FILE_CACHE.set(f, { mtime, parserMode, items });
1232
+ FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader, footer: fileFooter, lineCount: fileLines });
857
1233
  }
1234
+ if (fileHeader) headerMap.set(rel, fileHeader);
1235
+ if (fileFooter) footerMap.set(rel, fileFooter);
1236
+ lineCountMap.set(rel, fileLines);
858
1237
 
859
1238
  for (const b of items) {
860
1239
  allBlocks.push({
@@ -867,7 +1246,7 @@ async function collectProjectBlocks(root, scanRoot) {
867
1246
  });
868
1247
  }
869
1248
  }
870
- return allBlocks;
1249
+ return { blocks: allBlocks, headerMap, footerMap, lineCountMap };
871
1250
  }
872
1251
 
873
1252
  function resolveScanRoot(projectPath, subPath) {
@@ -891,17 +1270,50 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
891
1270
  try {
892
1271
  const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
893
1272
  const wanted = new Set((symbols || []).map((s) => String(s).toLowerCase()));
894
- const blocks = await collectProjectBlocks(root, scanRoot);
1273
+ const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
895
1274
  let used = 0;
896
1275
  const expanded = [];
1276
+ const expandedFiles = new Set();
1277
+ const fullStart1EndLine = new Map();
1278
+ const coveredRangesByFile = new Map();
897
1279
  for (const b of blocks) {
898
1280
  const match = wanted.has(b.name.toLowerCase()) || [...wanted].some((w) => b.name.toLowerCase().includes(w) || b.rel.toLowerCase().includes(w));
899
1281
  if (match && used + b.rawTk <= budget) {
900
1282
  used += b.rawTk;
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]);
1286
+ if (b.startLine === 1) {
1287
+ fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
1288
+ }
901
1289
  expanded.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [MCP: expand_skeleton_cluster]\n${b.full}`);
902
1290
  }
903
1291
  }
904
- return `<skeleton_expansion root="${root}" subPath="${subPath || ''}" expanded="${expanded.length}" used="${used}">\n${expanded.join('\n\n')}\n</skeleton_expansion>`;
1292
+ const headerChunks = [];
1293
+ const headerEndByFile = new Map();
1294
+ for (const rel of expandedFiles) {
1295
+ 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) {
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
+ }
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>`;
905
1317
  } catch (err) {
906
1318
  return `Error: ${err.message}`;
907
1319
  }
@@ -911,7 +1323,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
911
1323
  try {
912
1324
  const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
913
1325
  const terms = expandQueryTerms(String(query));
914
- const blocks = await collectProjectBlocks(root, scanRoot);
1326
+ const { blocks, headerMap, footerMap, lineCountMap } = await collectProjectBlocks(root, scanRoot);
915
1327
  const totalBlocks = Math.max(1, blocks.length);
916
1328
  const termDF = {};
917
1329
  for (const t of terms) {
@@ -941,13 +1353,20 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
941
1353
  return { ...b, score };
942
1354
  }).sort((a, b) => b.score - a.score);
943
1355
 
944
- // 構建專案 SymbolMap 與基於單字邊界正則 (\bname\s*\() 的真實函式呼叫依賴圖 (True Call Graph)
1356
+ // 構建專案 SymbolMap 與真實依賴圖 (True Call Graph + Constants)
945
1357
  const symbolMap = new Map();
1358
+ const constSymbolNames = new Set();
946
1359
  for (let idx = 0; idx < allBlocks.length; idx++) {
947
1360
  const b = allBlocks[idx];
948
1361
  if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
949
- if (!symbolMap.has(b.name)) symbolMap.set(b.name, []);
950
- 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
+ }
951
1370
  }
952
1371
  }
953
1372
 
@@ -960,7 +1379,8 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
960
1379
  if (sym === caller.name) continue;
961
1380
  if (maskedCaller.includes(sym)) {
962
1381
  const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
963
- 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');
964
1384
  if (callRe.test(maskedCaller)) {
965
1385
  for (const t of (symbolMap.get(sym) || [])) {
966
1386
  callAdj[i].add(t);
@@ -973,11 +1393,13 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
973
1393
 
974
1394
  // 計算自頂部修改重點 (Focal) 出發的 1 層 (1-hop) 與 2 層 (2-hop) 關聯距離
975
1395
  const focalIndices = [];
1396
+ const focalFiles = new Set();
976
1397
  const hopDistances = new Map();
977
1398
  for (let i = 0; i < allBlocks.length; i++) {
978
1399
  if (allBlocks[i].score > 0 && focalIndices.length < 3) {
979
1400
  focalIndices.push(i);
980
1401
  hopDistances.set(i, 0);
1402
+ focalFiles.add(allBlocks[i].rel);
981
1403
  }
982
1404
  }
983
1405
 
@@ -1000,6 +1422,14 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1000
1422
  const skelCandidates = [];
1001
1423
  const focalNames = new Set();
1002
1424
  const includedIds = new Set();
1425
+ const includedFiles = new Set();
1426
+ const partialFiles = new Set();
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
+ };
1003
1433
  const candidateItems = [];
1004
1434
  const dirBudgetUsed = {};
1005
1435
  const maxDirBudget = budget * 0.65;
@@ -1016,18 +1446,31 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1016
1446
  dirBudgetUsed[topDir] = curDir + b.rawTk;
1017
1447
  focalNames.add(b.name);
1018
1448
  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));
1453
+ }
1019
1454
  fullChunks.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [${b.parserMode}]\n${b.full}`);
1020
1455
  } else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
1021
- 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;
1022
1458
  if (linked || i < 12) {
1023
1459
  used += b.skelTk;
1024
1460
  dirBudgetUsed[topDir] = curDir + b.skelTk;
1025
1461
  skelCandidates.push({ ...b, linked, hop: hop ?? null });
1026
1462
  includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
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
+ }
1027
1468
  } else {
1469
+ partialFiles.add(b.rel);
1028
1470
  candidateItems.push(b);
1029
1471
  }
1030
1472
  } else {
1473
+ partialFiles.add(b.rel);
1031
1474
  candidateItems.push(b);
1032
1475
  }
1033
1476
  }
@@ -1044,6 +1487,10 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1044
1487
  used += delta;
1045
1488
  dirBudgetUsed[topDir] = curDir + delta;
1046
1489
  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));
1493
+ }
1047
1494
  fullChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] [MCP auto-expanded: ${item.lineCount} lines]\n${item.full}`);
1048
1495
  } else {
1049
1496
  const hopNote = item.hop ? ` | ${item.hop}-hop` : '';
@@ -1051,6 +1498,33 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1051
1498
  }
1052
1499
  }
1053
1500
 
1501
+ const headerChunks = [];
1502
+ const headerEndByFile = new Map();
1503
+ for (const rel of includedFiles) {
1504
+ const hdr = headerMap.get(rel);
1505
+ if (!hdr) continue;
1506
+ if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
1507
+ headerEndByFile.set(rel, hdr.endLine);
1508
+ headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
1509
+ }
1510
+ const headerTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
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
+
1054
1528
  const omitted = candidateItems.filter(b => b.score > 0 && !includedIds.has(b.rel + ':' + b.name + '@' + b.startLine)).slice(0, 3);
1055
1529
  const omittedTag = omitted.length > 0
1056
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>`
@@ -1058,7 +1532,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
1058
1532
 
1059
1533
  const expandTag = autoExpandedNames.length > 0 ? ` autoExpanded="${autoExpandedNames.join(',')}"` : '';
1060
1534
  const subPathTag = subPath ? ` subPath="${subPath}"` : '';
1061
- return `<context_slice root="${root}" version="0.3.2"${subPathTag} budget="${budget}" used="${used}"${expandTag}>\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>`;
1062
1536
  } catch (err) {
1063
1537
  return `Error: ${err.message}`;
1064
1538
  }
@@ -1077,7 +1551,7 @@ rl.on('line', async (line) => {
1077
1551
  return send({
1078
1552
  protocolVersion: req.params?.protocolVersion || '2024-11-05',
1079
1553
  capabilities: { tools: {} },
1080
- serverInfo: { name: 'ctxslice-thin', version: '0.3.2' }
1554
+ serverInfo: { name: 'ctxslice-thin', version: '0.3.4' }
1081
1555
  });
1082
1556
  }
1083
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.2)
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.2\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.2 — 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;
@@ -597,15 +605,378 @@ function extractBlocks(code, ext, fileName) {
597
605
  return blocks;
598
606
  }
599
607
 
608
+
609
+ function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
610
+ if (!content) return null;
611
+ const lines = String(content).replace(/\r\n/g, '\n').split('\n');
612
+ const limit = Math.min(lines.length, maxLines);
613
+ const funcOrClassStartRe =
614
+ /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:async\s+)?(?:function\*?\s+|class\s+)|^(?:async\s+)?def\s+|^func\s+|^(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?(?:fn|struct|impl|trait)\s+|^(?:public|private|protected|internal|static|final|abstract|async|override|\s)*(?:class|record)\s+/;
615
+ const importOrTypeOrVarRe =
616
+ /^(?:import\b|export\s+(?:type|interface|const|let|var|enum)\b|type\s+|interface\s+|const\s+|let\s+|var\s+|package\s+|using\s+|from\s+\S+\s+import\b|#include\b|#define\b)/;
617
+ const stripLineNoise = (line) =>
618
+ line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
619
+
620
+ const countBlockSpan = (startIdx) => {
621
+ let depth = 0;
622
+ let opened = false;
623
+ const scanMax = Math.min(lines.length, startIdx + maxObjectLines + 5);
624
+ for (let j = startIdx; j < scanMax; j++) {
625
+ const clean = stripLineNoise(lines[j]);
626
+ for (let k = 0; k < clean.length; k++) {
627
+ const ch = clean[k];
628
+ if (ch === '{' || ch === '[') {
629
+ depth++;
630
+ opened = true;
631
+ } else if (ch === '}' || ch === ']') {
632
+ depth--;
633
+ if (opened && depth <= 0) return j - startIdx + 1;
634
+ }
635
+ }
636
+ }
637
+ return opened ? maxObjectLines + 1 : 1;
638
+ };
639
+
640
+ let inBlockComment = false;
641
+ let lastSafeEnd = 0;
642
+ let i = 0;
643
+
644
+ while (i < limit) {
645
+ const raw = lines[i];
646
+ const trimmed = raw.trim();
647
+
648
+ if (inBlockComment) {
649
+ if (trimmed.includes('*/')) inBlockComment = false;
650
+ i++;
651
+ continue;
652
+ }
653
+ if (trimmed === '' || trimmed.startsWith('//') || trimmed.startsWith('#')) {
654
+ i++;
655
+ continue;
656
+ }
657
+ if (trimmed.startsWith('/*')) {
658
+ if (!trimmed.includes('*/')) inBlockComment = true;
659
+ i++;
660
+ continue;
661
+ }
662
+
663
+ if (funcOrClassStartRe.test(trimmed)) break;
664
+ if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+[^;\n]*=>/.test(trimmed)) break;
665
+ if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\([^)]*$/.test(trimmed)) {
666
+ const lookahead = lines.slice(i, Math.min(lines.length, i + 6)).join(' ');
667
+ if (lookahead.includes('=>')) break;
668
+ }
669
+ if (
670
+ !importOrTypeOrVarRe.test(trimmed) &&
671
+ /^(?:[\w<>[\],*&:.]+\s+)+[A-Za-z_][A-Za-z0-9_]*\s*\([^;]*\)\s*(?:const|override|throws\s+[\w,\s]+)?\s*\{?$/.test(trimmed)
672
+ ) {
673
+ break;
674
+ }
675
+
676
+ const cleanLine = stripLineNoise(raw);
677
+ let netDelta = 0;
678
+ let hasOpener = false;
679
+ for (let k = 0; k < cleanLine.length; k++) {
680
+ if (cleanLine[k] === '{' || cleanLine[k] === '[') {
681
+ netDelta++;
682
+ hasOpener = true;
683
+ } else if (cleanLine[k] === '}' || cleanLine[k] === ']') {
684
+ netDelta--;
685
+ }
686
+ }
687
+
688
+ if (hasOpener && netDelta > 0) {
689
+ const span = countBlockSpan(i);
690
+ const isImport = /^(?:import|export\s+type\s*\{)/.test(trimmed);
691
+ if ((!isImport && span > maxObjectLines) || i + span > limit) break;
692
+ i += span;
693
+ lastSafeEnd = i;
694
+ continue;
695
+ }
696
+
697
+ if (
698
+ /^(?:import|export\s+type|type|const|let|var)\b/.test(trimmed) &&
699
+ (trimmed.endsWith('(') || trimmed.endsWith('=')) &&
700
+ i + 1 < limit
701
+ ) {
702
+ let j = i + 1;
703
+ while (j < limit) {
704
+ const nextT = lines[j].trim();
705
+ if (nextT.endsWith(')') || nextT.endsWith(';')) {
706
+ j++;
707
+ break;
708
+ }
709
+ if (
710
+ nextT === '' ||
711
+ (!nextT.startsWith('|') && !nextT.startsWith('&') && !nextT.startsWith('"') && !nextT.startsWith("'"))
712
+ ) {
713
+ break;
714
+ }
715
+ j++;
716
+ }
717
+ if (j <= limit) {
718
+ i = j;
719
+ lastSafeEnd = i;
720
+ continue;
721
+ }
722
+ break;
723
+ }
724
+
725
+ i++;
726
+ lastSafeEnd = i;
727
+ }
728
+
729
+ if (lastSafeEnd <= 0) return null;
730
+ const headerLines = lines.slice(0, lastSafeEnd);
731
+ while (headerLines.length > 0 && headerLines[headerLines.length - 1].trim() === '') {
732
+ headerLines.pop();
733
+ }
734
+ if (headerLines.length === 0) return null;
735
+ return { header: headerLines.join('\n'), endLine: headerLines.length };
736
+ }
737
+
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
+
600
963
  const files = walk(targetRoot);
601
964
  const terms = expandQueryTerms(query);
602
965
  const allRawBlocks = [];
966
+ const fileHeaders = new Map();
967
+ const fileFooters = new Map();
968
+ const fileLineCounts = new Map();
603
969
  for (const filePath of files) {
604
970
  try {
605
971
  const buf = fs.readFileSync(filePath);
606
972
  if (isBinaryBuffer(buf)) continue;
607
973
  const content = buf.toString('utf8');
608
974
  const relPath = path.relative(targetRoot, filePath);
975
+ fileLineCounts.set(relPath, content.split('\n').length);
976
+ const hdr = extractFileHeader(content);
977
+ if (hdr) fileHeaders.set(relPath, hdr);
978
+ const ftr = extractFileFooter(content);
979
+ if (ftr) fileFooters.set(relPath, ftr);
609
980
  const items = extractBlocks(content, path.extname(filePath), relPath);
610
981
  for (const b of items) {
611
982
  allRawBlocks.push({
@@ -647,13 +1018,20 @@ const scored = allRawBlocks.map((b) => {
647
1018
  return { ...b, score };
648
1019
  }).sort((a, b) => b.score - a.score);
649
1020
 
650
- // True Call Graph (SymbolMap + Word-Boundary Call Matching + BFS maxHops)
1021
+ // True Call Graph (SymbolMap + Word-Boundary Call/Constant Matching + BFS maxHops)
651
1022
  const symbolMap = new Map();
1023
+ const constSymbolNames = new Set();
652
1024
  for (let i = 0; i < scored.length; i++) {
653
1025
  const b = scored[i];
654
1026
  if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
655
- if (!symbolMap.has(b.name)) symbolMap.set(b.name, []);
656
- 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
+ }
657
1035
  }
658
1036
  }
659
1037
  const callAdj = Array.from({ length: scored.length }, () => new Set());
@@ -665,7 +1043,9 @@ for (let i = 0; i < scored.length; i++) {
665
1043
  if (sym === caller.name) continue;
666
1044
  if (maskedCaller.includes(sym)) {
667
1045
  const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
668
- 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)) {
669
1049
  for (const t of (symbolMap.get(sym) || [])) {
670
1050
  callAdj[i].add(t);
671
1051
  callAdj[t].add(i);
@@ -675,11 +1055,13 @@ for (let i = 0; i < scored.length; i++) {
675
1055
  }
676
1056
  }
677
1057
  const hopDistances = new Map();
1058
+ const focalFiles = new Set();
678
1059
  const bfsQ = [];
679
1060
  for (let i = 0; i < scored.length; i++) {
680
1061
  if (scored[i].score > 0 && bfsQ.length < 3) {
681
1062
  bfsQ.push(i);
682
1063
  hopDistances.set(i, 0);
1064
+ focalFiles.add(scored[i].filePath);
683
1065
  }
684
1066
  }
685
1067
  let qHead = 0;
@@ -696,8 +1078,16 @@ while (qHead < bfsQ.length) {
696
1078
  }
697
1079
 
698
1080
  let remaining = budget;
699
- const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.2" budget="' + budget + '">'];
1081
+ const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.4" budget="' + budget + '">'];
700
1082
  const includedIds = new Set();
1083
+ const includedFiles = new Set();
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
+ };
701
1091
  const dirBudgetUsed = {};
702
1092
  const maxDirBudget = budget * 0.65;
703
1093
 
@@ -714,24 +1104,71 @@ for (let i = 0; i < scored.length; i++) {
714
1104
  remaining -= item.rawTokens;
715
1105
  dirBudgetUsed[topDir] = curDir + item.rawTokens;
716
1106
  includedIds.add(key);
1107
+ includedFiles.add(item.filePath);
1108
+ addCoveredRange(item.filePath, item.startLine, item.endLine);
1109
+ if (item.startLine === 1) {
1110
+ fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
1111
+ }
717
1112
  out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
718
1113
  out.push(item.full);
719
1114
  } else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
720
- 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;
721
1117
  if (linked || i < 12) {
722
1118
  remaining -= item.skelTokens;
723
1119
  dirBudgetUsed[topDir] = curDir + item.skelTokens;
724
1120
  includedIds.add(key);
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
+ }
725
1126
  out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
726
1127
  out.push(item.skeleton);
727
1128
  } else {
1129
+ partialFiles.add(item.filePath);
728
1130
  candidateItems.push(item);
729
1131
  }
730
1132
  } else {
1133
+ partialFiles.add(item.filePath);
731
1134
  candidateItems.push(item);
732
1135
  }
733
1136
  }
734
1137
 
1138
+ const headerChunks = [];
1139
+ const headerEndByFile = new Map();
1140
+ for (const fp of includedFiles) {
1141
+ const hdr = fileHeaders.get(fp);
1142
+ if (!hdr) continue;
1143
+ const coveredEnd = fullStart1EndLine.get(fp) || 0;
1144
+ if (coveredEnd >= hdr.endLine) continue;
1145
+ headerEndByFile.set(fp, hdr.endLine);
1146
+ headerChunks.push(` <!-- FILE_HEADER: ${fp}:1-${hdr.endLine} -->`);
1147
+ headerChunks.push(hdr.header);
1148
+ }
1149
+ if (headerChunks.length > 0) {
1150
+ out.splice(1, 0, '<file_headers>', ...headerChunks, '</file_headers>');
1151
+ }
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
+
735
1172
  const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
736
1173
  if (omitted.length > 0) {
737
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.2",
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": {