@grundy40/contextslice 0.3.5 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -38
- package/bin/ctxslice-mcp.mjs +391 -88
- package/bin/ctxslice.mjs +317 -72
- package/package.json +3 -3
package/bin/ctxslice.mjs
CHANGED
|
@@ -1,11 +1,132 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* ctxslice.mjs — Zero-Config Multi-Language Local
|
|
4
|
-
* Features: Multi-Language
|
|
3
|
+
* ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.0)
|
|
4
|
+
* Features: Multi-Language Structural Extractors, State-Machine Brace Matcher, True Call Graph (BFS), TF-IDF, Dual-State File Tree
|
|
5
5
|
*/
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
|
|
9
|
+
|
|
10
|
+
const PLAIN_TEXT_CONFIG_EXT_RE = /\.(json|jsonc|json5|yaml|yml|toml|ini|cfg|conf|xml|properties|txt)$/i;
|
|
11
|
+
const EN_CONVERSATIONAL_STOPWORDS = new Set([
|
|
12
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',
|
|
13
|
+
'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'into', 'about',
|
|
14
|
+
'how', 'why', 'what', 'when', 'where', 'who', 'which', 'whom', 'whose',
|
|
15
|
+
'can', 'could', 'would', 'should', 'will', 'shall', 'may', 'might', 'must',
|
|
16
|
+
'do', 'does', 'did', 'done', 'doing', 'have', 'has', 'had', 'having',
|
|
17
|
+
'please', 'pls', 'help', 'me', 'my', 'we', 'our', 'you', 'your', 'they', 'their',
|
|
18
|
+
'it', 'its', 'this', 'that', 'these', 'those', 'there', 'here',
|
|
19
|
+
'and', 'or', 'but', 'so', 'than', 'too', 'very', 'just', 'only', 'also',
|
|
20
|
+
'fix', 'modify', 'want', 'need', 'tell'
|
|
21
|
+
]);
|
|
22
|
+
const ZH_CONVERSATIONAL_STOPWORDS_RE = /為什麼|为什么|怎麼樣|怎么样|怎麼|怎么|如何|請幫我|请帮我|幫我|帮我|請問|请问|修改|更改|調整|调整|一下|什麼|什么|這個|这个|那個|那个|哪裡|哪里|[的了嗎呢啊吧著着過把被給跟與及]/g;
|
|
23
|
+
|
|
24
|
+
function estimateTokens(str) {
|
|
25
|
+
if (!str) return 0;
|
|
26
|
+
let cjk = 0;
|
|
27
|
+
for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
|
|
28
|
+
return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function escapeXmlAttr(value) {
|
|
32
|
+
return String(value || '')
|
|
33
|
+
.replace(/&/g, '&')
|
|
34
|
+
.replace(/"/g, '"')
|
|
35
|
+
.replace(/</g, '<')
|
|
36
|
+
.replace(/>/g, '>');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function escapeXmlText(value) {
|
|
40
|
+
return String(value || '')
|
|
41
|
+
.replace(/&/g, '&')
|
|
42
|
+
.replace(/</g, '<')
|
|
43
|
+
.replace(/>/g, '>');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function mergeLineRanges(ranges) {
|
|
47
|
+
if (!ranges || ranges.length === 0) return [];
|
|
48
|
+
const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
49
|
+
const merged = [];
|
|
50
|
+
for (const r of sorted) {
|
|
51
|
+
const s = Math.max(1, r[0]);
|
|
52
|
+
const e = Math.max(s, r[1]);
|
|
53
|
+
if (merged.length === 0) {
|
|
54
|
+
merged.push([s, e]);
|
|
55
|
+
} else {
|
|
56
|
+
const prev = merged[merged.length - 1];
|
|
57
|
+
if (s <= prev[1] + 1) prev[1] = Math.max(prev[1], e);
|
|
58
|
+
else merged.push([s, e]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return merged;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function formatShownLines(ranges) {
|
|
65
|
+
const merged = mergeLineRanges(ranges);
|
|
66
|
+
if (merged.length === 0) return 'none';
|
|
67
|
+
return merged.map((r) => (r[0] === r[1] ? String(r[0]) : r[0] + '-' + r[1])).join(', ');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function slicePlainTextConfigWindow(content, queryTerms) {
|
|
71
|
+
const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
|
|
72
|
+
if (lines.length <= 200) return null;
|
|
73
|
+
|
|
74
|
+
const matchedLines = [];
|
|
75
|
+
if (queryTerms && queryTerms.length > 0) {
|
|
76
|
+
for (let i = 0; i < lines.length; i++) {
|
|
77
|
+
const lower = lines[i].toLowerCase();
|
|
78
|
+
if (queryTerms.some((t) => lower.includes(t))) {
|
|
79
|
+
matchedLines.push(i + 1);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const rawRanges = matchedLines.length > 0
|
|
85
|
+
? matchedLines.map((ln) => [Math.max(1, ln - 40), Math.min(lines.length, ln + 40)])
|
|
86
|
+
: [[1, Math.min(lines.length, 81)]];
|
|
87
|
+
|
|
88
|
+
const merged = mergeLineRanges(rawRanges);
|
|
89
|
+
const parts = [];
|
|
90
|
+
for (let idx = 0; idx < merged.length; idx++) {
|
|
91
|
+
const s = merged[idx][0];
|
|
92
|
+
const e = merged[idx][1];
|
|
93
|
+
if (idx > 0) {
|
|
94
|
+
const prevEnd = merged[idx - 1][1];
|
|
95
|
+
parts.push('// ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ...');
|
|
96
|
+
}
|
|
97
|
+
parts.push(lines.slice(s - 1, e).join('\n'));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const windowedCode = parts.join('\n');
|
|
101
|
+
return {
|
|
102
|
+
windowedCode,
|
|
103
|
+
ranges: merged,
|
|
104
|
+
tokens: estimateTokens(windowedCode)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
|
|
109
|
+
const sorted = [...fileEntries].sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
110
|
+
const out = [];
|
|
111
|
+
let usedTokens = 0;
|
|
112
|
+
let omittedCount = 0;
|
|
113
|
+
for (const f of sorted) {
|
|
114
|
+
const line = ' ' + f.relPath + ' (' + f.lineCount + ' lines)';
|
|
115
|
+
const tk = estimateTokens(line);
|
|
116
|
+
if (usedTokens + tk > maxTokens && out.length > 0) {
|
|
117
|
+
omittedCount++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
usedTokens += tk;
|
|
121
|
+
out.push(line);
|
|
122
|
+
}
|
|
123
|
+
if (omittedCount > 0) {
|
|
124
|
+
out.push(' ... (' + omittedCount + ' more files omitted to keep overview within ~1.8K tokens)');
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
9
130
|
const CJK_RE = /[一-鿿-ゟ゠-ヿ가-]/;
|
|
10
131
|
const CJK_RUN_RE = new RegExp('[一-鿿-ゟ゠-ヿ가-]+', 'g');
|
|
11
132
|
const CJK_WORDS = {
|
|
@@ -353,31 +474,51 @@ function bilingualLookup(term) {
|
|
|
353
474
|
return out;
|
|
354
475
|
}
|
|
355
476
|
function expandQueryTerms(query) {
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
const
|
|
477
|
+
const trimmed = String(query || '').trim();
|
|
478
|
+
if (!trimmed) return [];
|
|
479
|
+
const q = trimmed.toLowerCase();
|
|
480
|
+
const terms = new Set();
|
|
481
|
+
const asciiParts = q.match(/[a-z0-9_]+(?:[.-][a-z0-9_]+)*/g) || [];
|
|
359
482
|
for (const p of asciiParts) {
|
|
360
|
-
if (p.length >= 2
|
|
361
|
-
|
|
483
|
+
if (p.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(p)) {
|
|
484
|
+
terms.add(p);
|
|
485
|
+
if (/^v\d/.test(p) && p.length >= 3) terms.add(p.slice(1));
|
|
486
|
+
if (p.includes('.') || p.includes('-')) {
|
|
487
|
+
for (const sub of p.split(/[.-]/)) {
|
|
488
|
+
if (sub.length >= 2 && !EN_CONVERSATIONAL_STOPWORDS.has(sub)) terms.add(sub);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
for (const t of bilingualLookup(p)) terms.add(t);
|
|
492
|
+
}
|
|
362
493
|
}
|
|
363
|
-
if (containsCJK(
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
for (const
|
|
494
|
+
if (containsCJK(trimmed)) {
|
|
495
|
+
const cleanedCjk = trimmed.replace(ZH_CONVERSATIONAL_STOPWORDS_RE, ' ');
|
|
496
|
+
if (containsCJK(cleanedCjk)) {
|
|
497
|
+
for (const gram of tokenizeCJK2gram(cleanedCjk)) {
|
|
498
|
+
terms.add(gram);
|
|
499
|
+
for (const t of bilingualLookup(gram)) terms.add(t);
|
|
500
|
+
}
|
|
501
|
+
for (const run of cleanedCjk.match(CJK_RUN_RE) || []) {
|
|
502
|
+
terms.add(run);
|
|
503
|
+
for (const t of bilingualLookup(run)) terms.add(t);
|
|
504
|
+
}
|
|
367
505
|
}
|
|
368
|
-
|
|
506
|
+
}
|
|
507
|
+
const snapshot = [...terms];
|
|
508
|
+
for (const term of snapshot) {
|
|
509
|
+
for (const t of bilingualLookup(term)) terms.add(t);
|
|
369
510
|
}
|
|
370
511
|
return [...terms].filter(Boolean);
|
|
371
512
|
}
|
|
372
513
|
|
|
373
514
|
const args = process.argv.slice(2);
|
|
374
515
|
if (args.includes('--version') || args.includes('-v')) {
|
|
375
|
-
process.stdout.write('ctxslice v0.
|
|
516
|
+
process.stdout.write('ctxslice v0.4.0\n');
|
|
376
517
|
process.exit(0);
|
|
377
518
|
}
|
|
378
519
|
if (args.includes('--help') || args.includes('-h')) {
|
|
379
520
|
process.stdout.write(
|
|
380
|
-
'ContextSlice CLI v0.
|
|
521
|
+
'ContextSlice CLI v0.4.0 — Zero-Config Multi-Language Structural Code Slicer\n\n' +
|
|
381
522
|
'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
|
|
382
523
|
'Options:\n --root <dir> Target repository path (default: current directory)\n' +
|
|
383
524
|
' --budget <num> Max token budget (default: 32768)\n' +
|
|
@@ -390,8 +531,11 @@ const rootFlag = args.indexOf('--root');
|
|
|
390
531
|
const targetRoot = rootFlag !== -1 && args[rootFlag + 1] ? path.resolve(args[rootFlag + 1]) : process.cwd();
|
|
391
532
|
const budgetFlag = args.indexOf('--budget');
|
|
392
533
|
const budget = budgetFlag !== -1 ? Number(args[budgetFlag + 1]) : 32768;
|
|
393
|
-
const skipIdx = new Set(
|
|
394
|
-
|
|
534
|
+
const skipIdx = new Set();
|
|
535
|
+
if (rootFlag !== -1) { skipIdx.add(rootFlag); skipIdx.add(rootFlag + 1); }
|
|
536
|
+
if (budgetFlag !== -1) { skipIdx.add(budgetFlag); skipIdx.add(budgetFlag + 1); }
|
|
537
|
+
const queryArg = args.find((a, idx) => !skipIdx.has(idx) && !a.startsWith('--'));
|
|
538
|
+
const query = queryArg !== undefined ? queryArg : '';
|
|
395
539
|
const IGNORE = new Set([
|
|
396
540
|
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
397
541
|
'venv', '.venv', '__pycache__', 'vendor', 'target', '.build', '.swiftpm', 'DerivedData', 'Pods', 'bin', 'obj'
|
|
@@ -405,7 +549,7 @@ const BINARY_EXT = new Set([
|
|
|
405
549
|
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods', '.odp', '.rtf',
|
|
406
550
|
'.db', '.sqlite', '.sqlite3', '.mdb', '.psd', '.ai', '.sketch', '.fig', '.xd', '.blend'
|
|
407
551
|
]);
|
|
408
|
-
const NOISE_FILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock|Gemfile\.lock|composer\.lock|go\.sum|Podfile\.lock|packages\.lock\.json|\.env(\..*)?|\.pem|\.key|credentials\.json|service-account.*\.json|secrets\.json)$|\.min\.(js|mjs|cjs|css)$|\.map$/i;
|
|
552
|
+
const NOISE_FILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.lock|poetry\.lock|Gemfile\.lock|composer\.lock|go\.sum|Podfile\.lock|packages\.lock\.json|\.env(\..*)?|\.pem|\.key|credentials\.json|service-account.*\.json|secrets\.json)$|\.min\.(js|mjs|cjs|css)$|\.map$/i;
|
|
409
553
|
const CONTROL_WORDS = new Set(['if', 'else', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'typeof', 'do', 'try']);
|
|
410
554
|
|
|
411
555
|
function isTextCandidate(full) {
|
|
@@ -436,13 +580,6 @@ function walk(dir, acc = []) {
|
|
|
436
580
|
return acc;
|
|
437
581
|
}
|
|
438
582
|
|
|
439
|
-
function estimateTokens(str) {
|
|
440
|
-
if (!str) return 0;
|
|
441
|
-
let cjk = 0;
|
|
442
|
-
for (let i = 0; i < str.length; i++) if (str.charCodeAt(i) >= 128) cjk++;
|
|
443
|
-
return Math.max(1, Math.round((str.length - cjk) / 2.1 + cjk * 1.6));
|
|
444
|
-
}
|
|
445
|
-
|
|
446
583
|
|
|
447
584
|
function maskCommentsAndStrings(code) {
|
|
448
585
|
return code
|
|
@@ -965,34 +1102,71 @@ function extractFileFooter(content, tailLines = 20) {
|
|
|
965
1102
|
|
|
966
1103
|
|
|
967
1104
|
const files = walk(targetRoot);
|
|
968
|
-
const terms = expandQueryTerms(query);
|
|
969
|
-
const allRawBlocks = [];
|
|
970
|
-
const fileHeaders = new Map();
|
|
971
|
-
const fileFooters = new Map();
|
|
972
1105
|
const fileLineCounts = new Map();
|
|
1106
|
+
const fileEntries = [];
|
|
1107
|
+
const textRecords = [];
|
|
973
1108
|
for (const filePath of files) {
|
|
974
1109
|
try {
|
|
975
1110
|
const buf = fs.readFileSync(filePath);
|
|
976
1111
|
if (isBinaryBuffer(buf)) continue;
|
|
977
1112
|
const content = buf.toString('utf8');
|
|
978
|
-
const relPath = path.relative(targetRoot, filePath);
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
if (ftr) fileFooters.set(relPath, ftr);
|
|
984
|
-
const items = extractBlocks(content, path.extname(filePath), relPath);
|
|
985
|
-
for (const b of items) {
|
|
986
|
-
allRawBlocks.push({
|
|
987
|
-
...b,
|
|
988
|
-
filePath: relPath,
|
|
989
|
-
rawTokens: estimateTokens(b.full),
|
|
990
|
-
skelTokens: estimateTokens(b.skeleton),
|
|
991
|
-
});
|
|
992
|
-
}
|
|
1113
|
+
const relPath = path.relative(targetRoot, filePath).replace(/\\/g, '/');
|
|
1114
|
+
const lineCount = content.replace(/\r\n/g, '\n').split('\n').length;
|
|
1115
|
+
fileLineCounts.set(relPath, lineCount);
|
|
1116
|
+
fileEntries.push({ relPath, lineCount });
|
|
1117
|
+
textRecords.push({ filePath, relPath, content });
|
|
993
1118
|
} catch {}
|
|
994
1119
|
}
|
|
995
1120
|
|
|
1121
|
+
// State A: Empty query -> return repository file tree overview (~1K-2K tokens)
|
|
1122
|
+
if (!query.trim()) {
|
|
1123
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
1124
|
+
const treeOut = [
|
|
1125
|
+
'<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(path.basename(targetRoot)) + '" version="0.4.0" total_files="' + fileEntries.length + '">',
|
|
1126
|
+
' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
|
|
1127
|
+
' <repository_file_tree>',
|
|
1128
|
+
...treeLines,
|
|
1129
|
+
' </repository_file_tree>',
|
|
1130
|
+
'</context_slice>'
|
|
1131
|
+
];
|
|
1132
|
+
process.stdout.write(treeOut.join('\n') + '\n');
|
|
1133
|
+
process.exit(0);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const terms = expandQueryTerms(query);
|
|
1137
|
+
const allRawBlocks = [];
|
|
1138
|
+
const fileHeaders = new Map();
|
|
1139
|
+
const fileFooters = new Map();
|
|
1140
|
+
const configWindowByKey = new Map();
|
|
1141
|
+
|
|
1142
|
+
for (const rec of textRecords) {
|
|
1143
|
+
const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rec.relPath);
|
|
1144
|
+
if (!isConfigFile) {
|
|
1145
|
+
const hdr = extractFileHeader(rec.content);
|
|
1146
|
+
if (hdr) fileHeaders.set(rec.relPath, hdr);
|
|
1147
|
+
const ftr = extractFileFooter(rec.content);
|
|
1148
|
+
if (ftr) fileFooters.set(rec.relPath, ftr);
|
|
1149
|
+
}
|
|
1150
|
+
const items = extractBlocks(rec.content, path.extname(rec.filePath), rec.relPath);
|
|
1151
|
+
for (const b of items) {
|
|
1152
|
+
const key = rec.relPath + ':' + b.startLine;
|
|
1153
|
+
let rawTokens = estimateTokens(b.full);
|
|
1154
|
+
if (isConfigFile && b.kind === 'module' && (b.endLine - b.startLine + 1) > 200) {
|
|
1155
|
+
const win = slicePlainTextConfigWindow(b.full, terms);
|
|
1156
|
+
if (win) {
|
|
1157
|
+
configWindowByKey.set(key, win);
|
|
1158
|
+
rawTokens = win.tokens;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
allRawBlocks.push({
|
|
1162
|
+
...b,
|
|
1163
|
+
filePath: rec.relPath,
|
|
1164
|
+
rawTokens,
|
|
1165
|
+
skelTokens: estimateTokens(b.skeleton),
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
|
|
996
1170
|
const totalBlocks = Math.max(1, allRawBlocks.length);
|
|
997
1171
|
const termDF = {};
|
|
998
1172
|
for (const t of terms) {
|
|
@@ -1082,53 +1256,66 @@ while (qHead < bfsQ.length) {
|
|
|
1082
1256
|
}
|
|
1083
1257
|
|
|
1084
1258
|
let remaining = budget;
|
|
1085
|
-
const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.5" budget="' + budget + '">'];
|
|
1086
1259
|
const includedIds = new Set();
|
|
1087
|
-
const includedFiles =
|
|
1260
|
+
const includedFiles = [];
|
|
1261
|
+
const includedFilesSet = new Set();
|
|
1088
1262
|
const fullStart1EndLine = new Map();
|
|
1089
1263
|
const coveredRangesByFile = new Map();
|
|
1090
1264
|
const partialFiles = new Set();
|
|
1265
|
+
const selectedByFile = new Map();
|
|
1091
1266
|
const addCoveredRange = (fp, s, e) => {
|
|
1092
1267
|
if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
|
|
1093
1268
|
coveredRangesByFile.get(fp).push([s, e]);
|
|
1094
1269
|
};
|
|
1270
|
+
const addSelectedBlock = (fp, entry) => {
|
|
1271
|
+
if (!includedFilesSet.has(fp)) {
|
|
1272
|
+
includedFilesSet.add(fp);
|
|
1273
|
+
includedFiles.push(fp);
|
|
1274
|
+
}
|
|
1275
|
+
if (!selectedByFile.has(fp)) selectedByFile.set(fp, []);
|
|
1276
|
+
selectedByFile.get(fp).push(entry);
|
|
1277
|
+
};
|
|
1095
1278
|
const dirBudgetUsed = {};
|
|
1096
1279
|
const maxDirBudget = budget * 0.65;
|
|
1097
1280
|
|
|
1098
1281
|
const candidateItems = [];
|
|
1099
1282
|
for (let i = 0; i < scored.length; i++) {
|
|
1100
1283
|
const item = scored[i];
|
|
1101
|
-
const topDir = item.filePath.split(
|
|
1284
|
+
const topDir = item.filePath.split('/')[0] || 'root';
|
|
1102
1285
|
const curDir = dirBudgetUsed[topDir] || 0;
|
|
1103
1286
|
const hop = hopDistances.get(i);
|
|
1104
1287
|
const isFocal = hop === 0 || (i < 2 && item.score > 0);
|
|
1105
1288
|
const key = item.filePath + ':' + item.startLine;
|
|
1289
|
+
const win = configWindowByKey.get(key);
|
|
1106
1290
|
|
|
1107
|
-
if (isFocal && item.rawTokens <= remaining && curDir + item.rawTokens <= maxDirBudget) {
|
|
1108
|
-
remaining
|
|
1291
|
+
if (isFocal && (item.rawTokens <= remaining || remaining === budget) && (curDir + item.rawTokens <= maxDirBudget || remaining === budget)) {
|
|
1292
|
+
remaining = Math.max(0, remaining - item.rawTokens);
|
|
1109
1293
|
dirBudgetUsed[topDir] = curDir + item.rawTokens;
|
|
1110
1294
|
includedIds.add(key);
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1295
|
+
if (win) {
|
|
1296
|
+
for (const r of win.ranges) {
|
|
1297
|
+
addCoveredRange(item.filePath, r[0], r[1]);
|
|
1298
|
+
if (r[0] === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, r[1]));
|
|
1299
|
+
}
|
|
1300
|
+
} else {
|
|
1301
|
+
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
1302
|
+
if (item.startLine === 1) {
|
|
1303
|
+
fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
|
|
1304
|
+
}
|
|
1115
1305
|
}
|
|
1116
|
-
|
|
1117
|
-
out.push(item.full);
|
|
1306
|
+
addSelectedBlock(item.filePath, { tier: 'full', item, win });
|
|
1118
1307
|
} else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
|
|
1119
1308
|
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);
|
|
1120
1309
|
const linked = (hop !== undefined && hop <= 2) || item.score > 0 || sameFileConst;
|
|
1121
|
-
if (linked
|
|
1310
|
+
if (linked) {
|
|
1122
1311
|
remaining -= item.skelTokens;
|
|
1123
1312
|
dirBudgetUsed[topDir] = curDir + item.skelTokens;
|
|
1124
1313
|
includedIds.add(key);
|
|
1125
|
-
includedFiles.add(item.filePath);
|
|
1126
1314
|
partialFiles.add(item.filePath);
|
|
1127
1315
|
if (item.skeleton === item.full) {
|
|
1128
1316
|
addCoveredRange(item.filePath, item.startLine, item.endLine);
|
|
1129
1317
|
}
|
|
1130
|
-
|
|
1131
|
-
out.push(item.skeleton);
|
|
1318
|
+
addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop });
|
|
1132
1319
|
} else {
|
|
1133
1320
|
partialFiles.add(item.filePath);
|
|
1134
1321
|
candidateItems.push(item);
|
|
@@ -1139,7 +1326,22 @@ for (let i = 0; i < scored.length; i++) {
|
|
|
1139
1326
|
}
|
|
1140
1327
|
}
|
|
1141
1328
|
|
|
1142
|
-
|
|
1329
|
+
// State B: Non-empty query with 0 matches -> warn agent & return repository file tree
|
|
1330
|
+
if (includedFiles.length === 0) {
|
|
1331
|
+
const treeLines = buildRepositoryFileTree(fileEntries, 1800);
|
|
1332
|
+
const zeroOut = [
|
|
1333
|
+
'<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(path.basename(targetRoot)) + '" version="0.4.0" query="' + escapeXmlAttr(query) + '">',
|
|
1334
|
+
' <note>WARNING: 0 matches found for query "' + escapeXmlText(query) + '". Do NOT guess code from this file tree alone—pick valid file paths or symbol names from the tree below and call context_slice again.</note>',
|
|
1335
|
+
' <repository_file_tree>',
|
|
1336
|
+
...treeLines,
|
|
1337
|
+
' </repository_file_tree>',
|
|
1338
|
+
'</context_slice>'
|
|
1339
|
+
];
|
|
1340
|
+
process.stdout.write(zeroOut.join('\n') + '\n');
|
|
1341
|
+
process.exit(0);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const headerByFile = new Map();
|
|
1143
1345
|
const headerEndByFile = new Map();
|
|
1144
1346
|
for (const fp of includedFiles) {
|
|
1145
1347
|
const hdr = fileHeaders.get(fp);
|
|
@@ -1147,14 +1349,10 @@ for (const fp of includedFiles) {
|
|
|
1147
1349
|
const coveredEnd = fullStart1EndLine.get(fp) || 0;
|
|
1148
1350
|
if (coveredEnd >= hdr.endLine) continue;
|
|
1149
1351
|
headerEndByFile.set(fp, hdr.endLine);
|
|
1150
|
-
|
|
1151
|
-
headerChunks.push(hdr.header);
|
|
1152
|
-
}
|
|
1153
|
-
if (headerChunks.length > 0) {
|
|
1154
|
-
out.splice(1, 0, '<file_headers>', ...headerChunks, '</file_headers>');
|
|
1352
|
+
headerByFile.set(fp, hdr);
|
|
1155
1353
|
}
|
|
1156
1354
|
|
|
1157
|
-
const
|
|
1355
|
+
const footerByFile = new Map();
|
|
1158
1356
|
for (const fp of includedFiles) {
|
|
1159
1357
|
const ftr = fileFooters.get(fp);
|
|
1160
1358
|
if (!ftr) continue;
|
|
@@ -1165,21 +1363,68 @@ for (const fp of includedFiles) {
|
|
|
1165
1363
|
const hdrEnd = headerEndByFile.get(fp) || 0;
|
|
1166
1364
|
const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
|
|
1167
1365
|
if (uncovered.length > 0) {
|
|
1168
|
-
|
|
1169
|
-
|
|
1366
|
+
footerByFile.set(fp, {
|
|
1367
|
+
startLine: uncovered[0].startLine,
|
|
1368
|
+
endLine: uncovered[uncovered.length - 1].endLine,
|
|
1369
|
+
text: uncovered.map((c) => c.text).join('\n'),
|
|
1370
|
+
chunks: uncovered
|
|
1371
|
+
});
|
|
1170
1372
|
}
|
|
1171
1373
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1374
|
+
|
|
1375
|
+
const out = [
|
|
1376
|
+
'<context_slice mode="progressive-structural-slice" root="' + escapeXmlAttr(path.basename(targetRoot)) + '" version="0.4.0" budget="' + budget + '">'
|
|
1377
|
+
];
|
|
1378
|
+
|
|
1379
|
+
for (const fp of includedFiles) {
|
|
1380
|
+
const entries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
|
|
1381
|
+
const hdr = headerByFile.get(fp);
|
|
1382
|
+
const ftr = footerByFile.get(fp);
|
|
1383
|
+
const totalLines = fileLineCounts.get(fp) || 0;
|
|
1384
|
+
const shownRanges = [];
|
|
1385
|
+
if (hdr) shownRanges.push([1, hdr.endLine]);
|
|
1386
|
+
for (const ent of entries) {
|
|
1387
|
+
if (ent.win) shownRanges.push(...ent.win.ranges);
|
|
1388
|
+
else shownRanges.push([ent.item.startLine, ent.item.endLine]);
|
|
1389
|
+
}
|
|
1390
|
+
if (ftr) {
|
|
1391
|
+
for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
|
|
1392
|
+
}
|
|
1393
|
+
out.push(` <file path="${escapeXmlAttr(fp)}" total_lines="${totalLines}" shown_lines="${formatShownLines(shownRanges)}">`);
|
|
1394
|
+
if (hdr) {
|
|
1395
|
+
out.push(` <file_header lines="1-${hdr.endLine}">`);
|
|
1396
|
+
out.push(hdr.header);
|
|
1397
|
+
out.push(' </file_header>');
|
|
1398
|
+
}
|
|
1399
|
+
for (const ent of entries) {
|
|
1400
|
+
const it = ent.item;
|
|
1401
|
+
if (ent.tier === 'full') {
|
|
1402
|
+
const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : `${it.startLine}-${it.endLine}`;
|
|
1403
|
+
out.push(` <focal symbol="${escapeXmlAttr(it.name)}" lines="${linesAttr}">`);
|
|
1404
|
+
out.push(ent.win ? ent.win.windowedCode : it.full);
|
|
1405
|
+
out.push(' </focal>');
|
|
1406
|
+
} else {
|
|
1407
|
+
const hopAttr = ent.hop !== undefined ? ` hop="${ent.hop}"` : '';
|
|
1408
|
+
out.push(` <skeleton symbol="${escapeXmlAttr(it.name)}" lines="${it.startLine}-${it.endLine}"${hopAttr}>`);
|
|
1409
|
+
out.push(ent.win ? ent.win.windowedCode : it.skeleton);
|
|
1410
|
+
out.push(' </skeleton>');
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
if (ftr) {
|
|
1414
|
+
out.push(` <file_footer lines="${ftr.startLine}-${ftr.endLine}">`);
|
|
1415
|
+
out.push(ftr.text);
|
|
1416
|
+
out.push(' </file_footer>');
|
|
1417
|
+
}
|
|
1418
|
+
out.push(' </file>');
|
|
1174
1419
|
}
|
|
1175
1420
|
|
|
1176
1421
|
const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
|
|
1177
1422
|
if (omitted.length > 0) {
|
|
1178
|
-
out.push('<omitted_top_matches>');
|
|
1423
|
+
out.push(' <omitted_top_matches>');
|
|
1179
1424
|
for (const o of omitted) {
|
|
1180
|
-
out.push(`
|
|
1425
|
+
out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
|
|
1181
1426
|
}
|
|
1182
|
-
out.push('</omitted_top_matches>');
|
|
1427
|
+
out.push(' </omitted_top_matches>');
|
|
1183
1428
|
}
|
|
1184
1429
|
|
|
1185
1430
|
out.push('</context_slice>');
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grundy40/contextslice",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Zero-dependency multi-language
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Zero-dependency multi-language structural code slicer & 1-Tool MCP server for AI coding assistants (Claude Code, OpenCode, Pi Agent, Cursor).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"contextslice": "./bin/ctxslice.mjs",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"LICENSE"
|
|
15
15
|
],
|
|
16
16
|
"keywords": [
|
|
17
|
-
"
|
|
17
|
+
"structural-parsing",
|
|
18
18
|
"mcp",
|
|
19
19
|
"context-slice",
|
|
20
20
|
"ai-coding",
|