@grundy40/contextslice 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/bin/ctxslice-mcp.mjs +179 -10
- package/bin/ctxslice.mjs +158 -4
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -33,13 +33,15 @@ npx @grundy40/contextslice --version
|
|
|
33
33
|
npx @grundy40/contextslice --help
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
Or install globally if you prefer short commands (`ctxslice
|
|
36
|
+
Or install globally (`npm install -g @grundy40/contextslice`) if you prefer short commands (`contextslice`, `ctxslice`, and `ctxslice-mcp`):
|
|
37
37
|
|
|
38
38
|
```bash
|
|
39
39
|
npm install -g @grundy40/contextslice
|
|
40
|
-
|
|
40
|
+
contextslice "retry queue" --budget 32768
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
+
Prefer a visual browser UI? Try the **Live Demo** at [https://grundy40.github.io/ContextSlice/](https://grundy40.github.io/ContextSlice/).
|
|
44
|
+
|
|
43
45
|
---
|
|
44
46
|
|
|
45
47
|
## Connect 1-Tool MCP to AI Coding Agents
|
package/bin/ctxslice-mcp.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.3.
|
|
3
|
+
* ctxslice-mcp.mjs — Global Multi-Language MCP Server v0.3.3
|
|
4
4
|
* Features: Embedded Base64 Tree-sitter WASM + Lazy Cache (~/.contextslice/parsers),
|
|
5
5
|
* State-Machine Brace Matcher Fallback, True Call Graph (BFS), TF-IDF, subPath Sandbox, mtime Cache
|
|
6
6
|
*/
|
|
@@ -11,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.
|
|
14
|
+
process.stdout.write('ctxslice-mcp v0.3.3\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.
|
|
384
|
+
description: 'PRIMARY code-reading tool (v0.3.3) 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',
|
|
@@ -823,7 +823,139 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
823
823
|
}
|
|
824
824
|
}
|
|
825
825
|
|
|
826
|
+
|
|
827
|
+
function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
|
|
828
|
+
if (!content) return null;
|
|
829
|
+
const lines = String(content).replace(/\r\n/g, '\n').split('\n');
|
|
830
|
+
const limit = Math.min(lines.length, maxLines);
|
|
831
|
+
const funcOrClassStartRe =
|
|
832
|
+
/^(?: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+/;
|
|
833
|
+
const importOrTypeOrVarRe =
|
|
834
|
+
/^(?: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)/;
|
|
835
|
+
const stripLineNoise = (line) =>
|
|
836
|
+
line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
|
|
837
|
+
|
|
838
|
+
const countBlockSpan = (startIdx) => {
|
|
839
|
+
let depth = 0;
|
|
840
|
+
let opened = false;
|
|
841
|
+
const scanMax = Math.min(lines.length, startIdx + maxObjectLines + 5);
|
|
842
|
+
for (let j = startIdx; j < scanMax; j++) {
|
|
843
|
+
const clean = stripLineNoise(lines[j]);
|
|
844
|
+
for (let k = 0; k < clean.length; k++) {
|
|
845
|
+
const ch = clean[k];
|
|
846
|
+
if (ch === '{' || ch === '[') {
|
|
847
|
+
depth++;
|
|
848
|
+
opened = true;
|
|
849
|
+
} else if (ch === '}' || ch === ']') {
|
|
850
|
+
depth--;
|
|
851
|
+
if (opened && depth <= 0) return j - startIdx + 1;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return opened ? maxObjectLines + 1 : 1;
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
let inBlockComment = false;
|
|
859
|
+
let lastSafeEnd = 0;
|
|
860
|
+
let i = 0;
|
|
861
|
+
|
|
862
|
+
while (i < limit) {
|
|
863
|
+
const raw = lines[i];
|
|
864
|
+
const trimmed = raw.trim();
|
|
865
|
+
|
|
866
|
+
if (inBlockComment) {
|
|
867
|
+
if (trimmed.includes('*/')) inBlockComment = false;
|
|
868
|
+
i++;
|
|
869
|
+
continue;
|
|
870
|
+
}
|
|
871
|
+
if (trimmed === '' || trimmed.startsWith('//') || trimmed.startsWith('#')) {
|
|
872
|
+
i++;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
if (trimmed.startsWith('/*')) {
|
|
876
|
+
if (!trimmed.includes('*/')) inBlockComment = true;
|
|
877
|
+
i++;
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
if (funcOrClassStartRe.test(trimmed)) break;
|
|
882
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+[^;\n]*=>/.test(trimmed)) break;
|
|
883
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\([^)]*$/.test(trimmed)) {
|
|
884
|
+
const lookahead = lines.slice(i, Math.min(lines.length, i + 6)).join(' ');
|
|
885
|
+
if (lookahead.includes('=>')) break;
|
|
886
|
+
}
|
|
887
|
+
if (
|
|
888
|
+
!importOrTypeOrVarRe.test(trimmed) &&
|
|
889
|
+
/^(?:[\w<>[\],*&:.]+\s+)+[A-Za-z_][A-Za-z0-9_]*\s*\([^;]*\)\s*(?:const|override|throws\s+[\w,\s]+)?\s*\{?$/.test(trimmed)
|
|
890
|
+
) {
|
|
891
|
+
break;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const cleanLine = stripLineNoise(raw);
|
|
895
|
+
let netDelta = 0;
|
|
896
|
+
let hasOpener = false;
|
|
897
|
+
for (let k = 0; k < cleanLine.length; k++) {
|
|
898
|
+
if (cleanLine[k] === '{' || cleanLine[k] === '[') {
|
|
899
|
+
netDelta++;
|
|
900
|
+
hasOpener = true;
|
|
901
|
+
} else if (cleanLine[k] === '}' || cleanLine[k] === ']') {
|
|
902
|
+
netDelta--;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
if (hasOpener && netDelta > 0) {
|
|
907
|
+
const span = countBlockSpan(i);
|
|
908
|
+
const isImport = /^(?:import|export\s+type\s*\{)/.test(trimmed);
|
|
909
|
+
if ((!isImport && span > maxObjectLines) || i + span > limit) break;
|
|
910
|
+
i += span;
|
|
911
|
+
lastSafeEnd = i;
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (
|
|
916
|
+
/^(?:import|export\s+type|type|const|let|var)\b/.test(trimmed) &&
|
|
917
|
+
(trimmed.endsWith('(') || trimmed.endsWith('=')) &&
|
|
918
|
+
i + 1 < limit
|
|
919
|
+
) {
|
|
920
|
+
let j = i + 1;
|
|
921
|
+
while (j < limit) {
|
|
922
|
+
const nextT = lines[j].trim();
|
|
923
|
+
if (nextT.endsWith(')') || nextT.endsWith(';')) {
|
|
924
|
+
j++;
|
|
925
|
+
break;
|
|
926
|
+
}
|
|
927
|
+
if (
|
|
928
|
+
nextT === '' ||
|
|
929
|
+
(!nextT.startsWith('|') && !nextT.startsWith('&') && !nextT.startsWith('"') && !nextT.startsWith("'"))
|
|
930
|
+
) {
|
|
931
|
+
break;
|
|
932
|
+
}
|
|
933
|
+
j++;
|
|
934
|
+
}
|
|
935
|
+
if (j <= limit) {
|
|
936
|
+
i = j;
|
|
937
|
+
lastSafeEnd = i;
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
break;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
i++;
|
|
944
|
+
lastSafeEnd = i;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
if (lastSafeEnd <= 0) return null;
|
|
948
|
+
const headerLines = lines.slice(0, lastSafeEnd);
|
|
949
|
+
while (headerLines.length > 0 && headerLines[headerLines.length - 1].trim() === '') {
|
|
950
|
+
headerLines.pop();
|
|
951
|
+
}
|
|
952
|
+
if (headerLines.length === 0) return null;
|
|
953
|
+
return { header: headerLines.join('\n'), endLine: headerLines.length };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
|
|
826
957
|
const allBlocks = [];
|
|
958
|
+
const headerMap = new Map();
|
|
827
959
|
for (const f of files) {
|
|
828
960
|
const rel = path.relative(root, f);
|
|
829
961
|
let stat;
|
|
@@ -837,13 +969,16 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
837
969
|
|
|
838
970
|
let items;
|
|
839
971
|
let parserMode = 'regex';
|
|
972
|
+
let fileHeader = null;
|
|
840
973
|
if (cached && cached.mtime === mtime) {
|
|
841
974
|
items = cached.items;
|
|
842
975
|
parserMode = cached.parserMode || 'regex';
|
|
976
|
+
fileHeader = cached.header ?? null;
|
|
843
977
|
} else {
|
|
844
978
|
const rawBuf = fs.readFileSync(f);
|
|
845
979
|
if (isBinaryBuffer(rawBuf)) continue;
|
|
846
980
|
const raw = rawBuf.toString('utf8');
|
|
981
|
+
fileHeader = extractFileHeader(raw);
|
|
847
982
|
const ext = path.extname(f);
|
|
848
983
|
const tsBlocks = await extractBlocksWithTreeSitter(raw, ext, rel);
|
|
849
984
|
if (tsBlocks && tsBlocks.length > 0) {
|
|
@@ -853,8 +988,9 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
853
988
|
items = extractBlocks(raw, ext, rel);
|
|
854
989
|
parserMode = 'state-machine-regex';
|
|
855
990
|
}
|
|
856
|
-
FILE_CACHE.set(f, { mtime, parserMode, items });
|
|
991
|
+
FILE_CACHE.set(f, { mtime, parserMode, items, header: fileHeader });
|
|
857
992
|
}
|
|
993
|
+
if (fileHeader) headerMap.set(rel, fileHeader);
|
|
858
994
|
|
|
859
995
|
for (const b of items) {
|
|
860
996
|
allBlocks.push({
|
|
@@ -867,7 +1003,7 @@ async function collectProjectBlocks(root, scanRoot) {
|
|
|
867
1003
|
});
|
|
868
1004
|
}
|
|
869
1005
|
}
|
|
870
|
-
return allBlocks;
|
|
1006
|
+
return { blocks: allBlocks, headerMap };
|
|
871
1007
|
}
|
|
872
1008
|
|
|
873
1009
|
function resolveScanRoot(projectPath, subPath) {
|
|
@@ -891,17 +1027,31 @@ async function expandSkeletonCluster(symbols, projectPath, budget = 32768, subPa
|
|
|
891
1027
|
try {
|
|
892
1028
|
const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
|
|
893
1029
|
const wanted = new Set((symbols || []).map((s) => String(s).toLowerCase()));
|
|
894
|
-
const blocks = await collectProjectBlocks(root, scanRoot);
|
|
1030
|
+
const { blocks, headerMap } = await collectProjectBlocks(root, scanRoot);
|
|
895
1031
|
let used = 0;
|
|
896
1032
|
const expanded = [];
|
|
1033
|
+
const expandedFiles = new Set();
|
|
1034
|
+
const fullStart1EndLine = new Map();
|
|
897
1035
|
for (const b of blocks) {
|
|
898
1036
|
const match = wanted.has(b.name.toLowerCase()) || [...wanted].some((w) => b.name.toLowerCase().includes(w) || b.rel.toLowerCase().includes(w));
|
|
899
1037
|
if (match && used + b.rawTk <= budget) {
|
|
900
1038
|
used += b.rawTk;
|
|
1039
|
+
expandedFiles.add(b.rel);
|
|
1040
|
+
if (b.startLine === 1) {
|
|
1041
|
+
fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
|
|
1042
|
+
}
|
|
901
1043
|
expanded.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [MCP: expand_skeleton_cluster]\n${b.full}`);
|
|
902
1044
|
}
|
|
903
1045
|
}
|
|
904
|
-
|
|
1046
|
+
const headerChunks = [];
|
|
1047
|
+
for (const rel of expandedFiles) {
|
|
1048
|
+
const hdr = headerMap.get(rel);
|
|
1049
|
+
if (!hdr) continue;
|
|
1050
|
+
if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
|
|
1051
|
+
headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
|
|
1052
|
+
}
|
|
1053
|
+
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>`;
|
|
905
1055
|
} catch (err) {
|
|
906
1056
|
return `Error: ${err.message}`;
|
|
907
1057
|
}
|
|
@@ -911,7 +1061,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
911
1061
|
try {
|
|
912
1062
|
const { root, scanRoot } = resolveScanRoot(projectPath, subPath);
|
|
913
1063
|
const terms = expandQueryTerms(String(query));
|
|
914
|
-
const blocks = await collectProjectBlocks(root, scanRoot);
|
|
1064
|
+
const { blocks, headerMap } = await collectProjectBlocks(root, scanRoot);
|
|
915
1065
|
const totalBlocks = Math.max(1, blocks.length);
|
|
916
1066
|
const termDF = {};
|
|
917
1067
|
for (const t of terms) {
|
|
@@ -1000,6 +1150,8 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1000
1150
|
const skelCandidates = [];
|
|
1001
1151
|
const focalNames = new Set();
|
|
1002
1152
|
const includedIds = new Set();
|
|
1153
|
+
const includedFiles = new Set();
|
|
1154
|
+
const fullStart1EndLine = new Map();
|
|
1003
1155
|
const candidateItems = [];
|
|
1004
1156
|
const dirBudgetUsed = {};
|
|
1005
1157
|
const maxDirBudget = budget * 0.65;
|
|
@@ -1016,6 +1168,10 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1016
1168
|
dirBudgetUsed[topDir] = curDir + b.rawTk;
|
|
1017
1169
|
focalNames.add(b.name);
|
|
1018
1170
|
includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
|
|
1171
|
+
includedFiles.add(b.rel);
|
|
1172
|
+
if (b.startLine === 1) {
|
|
1173
|
+
fullStart1EndLine.set(b.rel, Math.max(fullStart1EndLine.get(b.rel) || 0, b.endLine));
|
|
1174
|
+
}
|
|
1019
1175
|
fullChunks.push(`// [${b.rel}:${b.startLine}-${b.endLine}] [${b.parserMode}]\n${b.full}`);
|
|
1020
1176
|
} else if (used + b.skelTk <= budget && curDir + b.skelTk <= maxDirBudget) {
|
|
1021
1177
|
const linked = (hop !== undefined && hop <= 2) || b.score > 0;
|
|
@@ -1024,6 +1180,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1024
1180
|
dirBudgetUsed[topDir] = curDir + b.skelTk;
|
|
1025
1181
|
skelCandidates.push({ ...b, linked, hop: hop ?? null });
|
|
1026
1182
|
includedIds.add(b.rel + ':' + b.name + '@' + b.startLine);
|
|
1183
|
+
includedFiles.add(b.rel);
|
|
1027
1184
|
} else {
|
|
1028
1185
|
candidateItems.push(b);
|
|
1029
1186
|
}
|
|
@@ -1044,6 +1201,9 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1044
1201
|
used += delta;
|
|
1045
1202
|
dirBudgetUsed[topDir] = curDir + delta;
|
|
1046
1203
|
autoExpandedNames.push(item.name);
|
|
1204
|
+
if (item.startLine === 1) {
|
|
1205
|
+
fullStart1EndLine.set(item.rel, Math.max(fullStart1EndLine.get(item.rel) || 0, item.endLine));
|
|
1206
|
+
}
|
|
1047
1207
|
fullChunks.push(`// [${item.rel}:${item.startLine}-${item.endLine}] [MCP auto-expanded: ${item.lineCount} lines]\n${item.full}`);
|
|
1048
1208
|
} else {
|
|
1049
1209
|
const hopNote = item.hop ? ` | ${item.hop}-hop` : '';
|
|
@@ -1051,6 +1211,15 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1051
1211
|
}
|
|
1052
1212
|
}
|
|
1053
1213
|
|
|
1214
|
+
const headerChunks = [];
|
|
1215
|
+
for (const rel of includedFiles) {
|
|
1216
|
+
const hdr = headerMap.get(rel);
|
|
1217
|
+
if (!hdr) continue;
|
|
1218
|
+
if ((fullStart1EndLine.get(rel) || 0) >= hdr.endLine) continue;
|
|
1219
|
+
headerChunks.push(`// [${rel}:1-${hdr.endLine}] (file header)\n${hdr.header}`);
|
|
1220
|
+
}
|
|
1221
|
+
const headerTag = headerChunks.length > 0 ? `\n<file_headers>\n${headerChunks.join('\n\n')}\n</file_headers>` : '';
|
|
1222
|
+
|
|
1054
1223
|
const omitted = candidateItems.filter(b => b.score > 0 && !includedIds.has(b.rel + ':' + b.name + '@' + b.startLine)).slice(0, 3);
|
|
1055
1224
|
const omittedTag = omitted.length > 0
|
|
1056
1225
|
? `\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 +1227,7 @@ async function sliceProject(query, projectPath, budget = 32768, autoExpand = tru
|
|
|
1058
1227
|
|
|
1059
1228
|
const expandTag = autoExpandedNames.length > 0 ? ` autoExpanded="${autoExpandedNames.join(',')}"` : '';
|
|
1060
1229
|
const subPathTag = subPath ? ` subPath="${subPath}"` : '';
|
|
1061
|
-
return `<context_slice root="${root}" version="0.3.
|
|
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>`;
|
|
1062
1231
|
} catch (err) {
|
|
1063
1232
|
return `Error: ${err.message}`;
|
|
1064
1233
|
}
|
|
@@ -1077,7 +1246,7 @@ rl.on('line', async (line) => {
|
|
|
1077
1246
|
return send({
|
|
1078
1247
|
protocolVersion: req.params?.protocolVersion || '2024-11-05',
|
|
1079
1248
|
capabilities: { tools: {} },
|
|
1080
|
-
serverInfo: { name: 'ctxslice-thin', version: '0.3.
|
|
1249
|
+
serverInfo: { name: 'ctxslice-thin', version: '0.3.3' }
|
|
1081
1250
|
});
|
|
1082
1251
|
}
|
|
1083
1252
|
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
|
+
* ctxslice.mjs — Zero-Config Multi-Language Local AST Context Pre-Compiler (v0.3.3)
|
|
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.
|
|
375
|
+
process.stdout.write('ctxslice v0.3.3\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.
|
|
380
|
+
'ContextSlice CLI v0.3.3 — 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' +
|
|
@@ -597,15 +597,149 @@ function extractBlocks(code, ext, fileName) {
|
|
|
597
597
|
return blocks;
|
|
598
598
|
}
|
|
599
599
|
|
|
600
|
+
|
|
601
|
+
function extractFileHeader(content, maxLines = 50, maxObjectLines = 60) {
|
|
602
|
+
if (!content) return null;
|
|
603
|
+
const lines = String(content).replace(/\r\n/g, '\n').split('\n');
|
|
604
|
+
const limit = Math.min(lines.length, maxLines);
|
|
605
|
+
const funcOrClassStartRe =
|
|
606
|
+
/^(?: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+/;
|
|
607
|
+
const importOrTypeOrVarRe =
|
|
608
|
+
/^(?: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)/;
|
|
609
|
+
const stripLineNoise = (line) =>
|
|
610
|
+
line.replace(/(['"\x60])(?:\\.|(?!\1).)*\1/g, '""').replace(/\/\/.*$|#.*$/g, '');
|
|
611
|
+
|
|
612
|
+
const countBlockSpan = (startIdx) => {
|
|
613
|
+
let depth = 0;
|
|
614
|
+
let opened = false;
|
|
615
|
+
const scanMax = Math.min(lines.length, startIdx + maxObjectLines + 5);
|
|
616
|
+
for (let j = startIdx; j < scanMax; j++) {
|
|
617
|
+
const clean = stripLineNoise(lines[j]);
|
|
618
|
+
for (let k = 0; k < clean.length; k++) {
|
|
619
|
+
const ch = clean[k];
|
|
620
|
+
if (ch === '{' || ch === '[') {
|
|
621
|
+
depth++;
|
|
622
|
+
opened = true;
|
|
623
|
+
} else if (ch === '}' || ch === ']') {
|
|
624
|
+
depth--;
|
|
625
|
+
if (opened && depth <= 0) return j - startIdx + 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return opened ? maxObjectLines + 1 : 1;
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
let inBlockComment = false;
|
|
633
|
+
let lastSafeEnd = 0;
|
|
634
|
+
let i = 0;
|
|
635
|
+
|
|
636
|
+
while (i < limit) {
|
|
637
|
+
const raw = lines[i];
|
|
638
|
+
const trimmed = raw.trim();
|
|
639
|
+
|
|
640
|
+
if (inBlockComment) {
|
|
641
|
+
if (trimmed.includes('*/')) inBlockComment = false;
|
|
642
|
+
i++;
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
if (trimmed === '' || trimmed.startsWith('//') || trimmed.startsWith('#')) {
|
|
646
|
+
i++;
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
if (trimmed.startsWith('/*')) {
|
|
650
|
+
if (!trimmed.includes('*/')) inBlockComment = true;
|
|
651
|
+
i++;
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
if (funcOrClassStartRe.test(trimmed)) break;
|
|
656
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+[^;\n]*=>/.test(trimmed)) break;
|
|
657
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\([^)]*$/.test(trimmed)) {
|
|
658
|
+
const lookahead = lines.slice(i, Math.min(lines.length, i + 6)).join(' ');
|
|
659
|
+
if (lookahead.includes('=>')) break;
|
|
660
|
+
}
|
|
661
|
+
if (
|
|
662
|
+
!importOrTypeOrVarRe.test(trimmed) &&
|
|
663
|
+
/^(?:[\w<>[\],*&:.]+\s+)+[A-Za-z_][A-Za-z0-9_]*\s*\([^;]*\)\s*(?:const|override|throws\s+[\w,\s]+)?\s*\{?$/.test(trimmed)
|
|
664
|
+
) {
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const cleanLine = stripLineNoise(raw);
|
|
669
|
+
let netDelta = 0;
|
|
670
|
+
let hasOpener = false;
|
|
671
|
+
for (let k = 0; k < cleanLine.length; k++) {
|
|
672
|
+
if (cleanLine[k] === '{' || cleanLine[k] === '[') {
|
|
673
|
+
netDelta++;
|
|
674
|
+
hasOpener = true;
|
|
675
|
+
} else if (cleanLine[k] === '}' || cleanLine[k] === ']') {
|
|
676
|
+
netDelta--;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
if (hasOpener && netDelta > 0) {
|
|
681
|
+
const span = countBlockSpan(i);
|
|
682
|
+
const isImport = /^(?:import|export\s+type\s*\{)/.test(trimmed);
|
|
683
|
+
if ((!isImport && span > maxObjectLines) || i + span > limit) break;
|
|
684
|
+
i += span;
|
|
685
|
+
lastSafeEnd = i;
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (
|
|
690
|
+
/^(?:import|export\s+type|type|const|let|var)\b/.test(trimmed) &&
|
|
691
|
+
(trimmed.endsWith('(') || trimmed.endsWith('=')) &&
|
|
692
|
+
i + 1 < limit
|
|
693
|
+
) {
|
|
694
|
+
let j = i + 1;
|
|
695
|
+
while (j < limit) {
|
|
696
|
+
const nextT = lines[j].trim();
|
|
697
|
+
if (nextT.endsWith(')') || nextT.endsWith(';')) {
|
|
698
|
+
j++;
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
701
|
+
if (
|
|
702
|
+
nextT === '' ||
|
|
703
|
+
(!nextT.startsWith('|') && !nextT.startsWith('&') && !nextT.startsWith('"') && !nextT.startsWith("'"))
|
|
704
|
+
) {
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
707
|
+
j++;
|
|
708
|
+
}
|
|
709
|
+
if (j <= limit) {
|
|
710
|
+
i = j;
|
|
711
|
+
lastSafeEnd = i;
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
break;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
i++;
|
|
718
|
+
lastSafeEnd = i;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if (lastSafeEnd <= 0) return null;
|
|
722
|
+
const headerLines = lines.slice(0, lastSafeEnd);
|
|
723
|
+
while (headerLines.length > 0 && headerLines[headerLines.length - 1].trim() === '') {
|
|
724
|
+
headerLines.pop();
|
|
725
|
+
}
|
|
726
|
+
if (headerLines.length === 0) return null;
|
|
727
|
+
return { header: headerLines.join('\n'), endLine: headerLines.length };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
|
|
600
731
|
const files = walk(targetRoot);
|
|
601
732
|
const terms = expandQueryTerms(query);
|
|
602
733
|
const allRawBlocks = [];
|
|
734
|
+
const fileHeaders = new Map();
|
|
603
735
|
for (const filePath of files) {
|
|
604
736
|
try {
|
|
605
737
|
const buf = fs.readFileSync(filePath);
|
|
606
738
|
if (isBinaryBuffer(buf)) continue;
|
|
607
739
|
const content = buf.toString('utf8');
|
|
608
740
|
const relPath = path.relative(targetRoot, filePath);
|
|
741
|
+
const hdr = extractFileHeader(content);
|
|
742
|
+
if (hdr) fileHeaders.set(relPath, hdr);
|
|
609
743
|
const items = extractBlocks(content, path.extname(filePath), relPath);
|
|
610
744
|
for (const b of items) {
|
|
611
745
|
allRawBlocks.push({
|
|
@@ -696,8 +830,10 @@ while (qHead < bfsQ.length) {
|
|
|
696
830
|
}
|
|
697
831
|
|
|
698
832
|
let remaining = budget;
|
|
699
|
-
const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.
|
|
833
|
+
const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.3" budget="' + budget + '">'];
|
|
700
834
|
const includedIds = new Set();
|
|
835
|
+
const includedFiles = new Set();
|
|
836
|
+
const fullStart1EndLine = new Map();
|
|
701
837
|
const dirBudgetUsed = {};
|
|
702
838
|
const maxDirBudget = budget * 0.65;
|
|
703
839
|
|
|
@@ -714,6 +850,10 @@ for (let i = 0; i < scored.length; i++) {
|
|
|
714
850
|
remaining -= item.rawTokens;
|
|
715
851
|
dirBudgetUsed[topDir] = curDir + item.rawTokens;
|
|
716
852
|
includedIds.add(key);
|
|
853
|
+
includedFiles.add(item.filePath);
|
|
854
|
+
if (item.startLine === 1) {
|
|
855
|
+
fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
|
|
856
|
+
}
|
|
717
857
|
out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
|
|
718
858
|
out.push(item.full);
|
|
719
859
|
} else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
|
|
@@ -722,6 +862,7 @@ for (let i = 0; i < scored.length; i++) {
|
|
|
722
862
|
remaining -= item.skelTokens;
|
|
723
863
|
dirBudgetUsed[topDir] = curDir + item.skelTokens;
|
|
724
864
|
includedIds.add(key);
|
|
865
|
+
includedFiles.add(item.filePath);
|
|
725
866
|
out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
|
|
726
867
|
out.push(item.skeleton);
|
|
727
868
|
} else {
|
|
@@ -732,6 +873,19 @@ for (let i = 0; i < scored.length; i++) {
|
|
|
732
873
|
}
|
|
733
874
|
}
|
|
734
875
|
|
|
876
|
+
const headerChunks = [];
|
|
877
|
+
for (const fp of includedFiles) {
|
|
878
|
+
const hdr = fileHeaders.get(fp);
|
|
879
|
+
if (!hdr) continue;
|
|
880
|
+
const coveredEnd = fullStart1EndLine.get(fp) || 0;
|
|
881
|
+
if (coveredEnd >= hdr.endLine) continue;
|
|
882
|
+
headerChunks.push(` <!-- FILE_HEADER: ${fp}:1-${hdr.endLine} -->`);
|
|
883
|
+
headerChunks.push(hdr.header);
|
|
884
|
+
}
|
|
885
|
+
if (headerChunks.length > 0) {
|
|
886
|
+
out.splice(1, 0, '<file_headers>', ...headerChunks, '</file_headers>');
|
|
887
|
+
}
|
|
888
|
+
|
|
735
889
|
const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
|
|
736
890
|
if (omitted.length > 0) {
|
|
737
891
|
out.push('<omitted_top_matches>');
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grundy40/contextslice",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
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": {
|
|
7
|
+
"contextslice": "./bin/ctxslice.mjs",
|
|
7
8
|
"ctxslice": "./bin/ctxslice.mjs",
|
|
8
9
|
"ctxslice-mcp": "./bin/ctxslice-mcp.mjs"
|
|
9
10
|
},
|