@grundy40/contextslice 0.3.4 → 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/bin/ctxslice.mjs CHANGED
@@ -1,11 +1,132 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ctxslice.mjs — Zero-Config Multi-Language Local AST Context Pre-Compiler (v0.3.4)
4
- * Features: Multi-Language AST Extractors, State-Machine Brace Matcher, True Call Graph (BFS), TF-IDF, Directory Quota Cap
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, '&amp;')
34
+ .replace(/"/g, '&quot;')
35
+ .replace(/</g, '&lt;')
36
+ .replace(/>/g, '&gt;');
37
+ }
38
+
39
+ function escapeXmlText(value) {
40
+ return String(value || '')
41
+ .replace(/&/g, '&amp;')
42
+ .replace(/</g, '&lt;')
43
+ .replace(/>/g, '&gt;');
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 q = String(query || '').toLowerCase();
357
- const terms = new Set(q.split(/\s+/).filter(Boolean));
358
- const asciiParts = q.match(/[a-z0-9_]+/g) || [];
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) terms.add(p);
361
- for (const t of bilingualLookup(p)) terms.add(t);
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(q)) {
364
- for (const gram of tokenizeCJK2gram(q)) {
365
- terms.add(gram);
366
- for (const t of bilingualLookup(gram)) terms.add(t);
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
- for (const run of q.match(CJK_RUN_RE) || []) terms.add(run);
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.3.4\n');
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.3.4 — Zero-Config Multi-Language AST Slicer\n\n' +
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([rootFlag, rootFlag + 1, budgetFlag, budgetFlag + 1]);
394
- const query = args.find((a, idx) => !skipIdx.has(idx) && !a.startsWith('--')) || 'fix bug';
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,9 +580,6 @@ function walk(dir, acc = []) {
436
580
  return acc;
437
581
  }
438
582
 
439
- function estimateTokens(str) {
440
- return Math.max(1, Math.round(str.length / 3.8));
441
- }
442
583
 
443
584
  function maskCommentsAndStrings(code) {
444
585
  return code
@@ -961,34 +1102,71 @@ function extractFileFooter(content, tailLines = 20) {
961
1102
 
962
1103
 
963
1104
  const files = walk(targetRoot);
964
- const terms = expandQueryTerms(query);
965
- const allRawBlocks = [];
966
- const fileHeaders = new Map();
967
- const fileFooters = new Map();
968
1105
  const fileLineCounts = new Map();
1106
+ const fileEntries = [];
1107
+ const textRecords = [];
969
1108
  for (const filePath of files) {
970
1109
  try {
971
1110
  const buf = fs.readFileSync(filePath);
972
1111
  if (isBinaryBuffer(buf)) continue;
973
1112
  const content = buf.toString('utf8');
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);
980
- const items = extractBlocks(content, path.extname(filePath), relPath);
981
- for (const b of items) {
982
- allRawBlocks.push({
983
- ...b,
984
- filePath: relPath,
985
- rawTokens: estimateTokens(b.full),
986
- skelTokens: estimateTokens(b.skeleton),
987
- });
988
- }
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 });
989
1118
  } catch {}
990
1119
  }
991
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
+
992
1170
  const totalBlocks = Math.max(1, allRawBlocks.length);
993
1171
  const termDF = {};
994
1172
  for (const t of terms) {
@@ -1078,53 +1256,66 @@ while (qHead < bfsQ.length) {
1078
1256
  }
1079
1257
 
1080
1258
  let remaining = budget;
1081
- const out = ['<context_slice root="' + path.basename(targetRoot) + '" version="0.3.4" budget="' + budget + '">'];
1082
1259
  const includedIds = new Set();
1083
- const includedFiles = new Set();
1260
+ const includedFiles = [];
1261
+ const includedFilesSet = new Set();
1084
1262
  const fullStart1EndLine = new Map();
1085
1263
  const coveredRangesByFile = new Map();
1086
1264
  const partialFiles = new Set();
1265
+ const selectedByFile = new Map();
1087
1266
  const addCoveredRange = (fp, s, e) => {
1088
1267
  if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
1089
1268
  coveredRangesByFile.get(fp).push([s, e]);
1090
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
+ };
1091
1278
  const dirBudgetUsed = {};
1092
1279
  const maxDirBudget = budget * 0.65;
1093
1280
 
1094
1281
  const candidateItems = [];
1095
1282
  for (let i = 0; i < scored.length; i++) {
1096
1283
  const item = scored[i];
1097
- const topDir = item.filePath.split(path.sep)[0] || 'root';
1284
+ const topDir = item.filePath.split('/')[0] || 'root';
1098
1285
  const curDir = dirBudgetUsed[topDir] || 0;
1099
1286
  const hop = hopDistances.get(i);
1100
1287
  const isFocal = hop === 0 || (i < 2 && item.score > 0);
1101
1288
  const key = item.filePath + ':' + item.startLine;
1289
+ const win = configWindowByKey.get(key);
1102
1290
 
1103
- if (isFocal && item.rawTokens <= remaining && curDir + item.rawTokens <= maxDirBudget) {
1104
- remaining -= item.rawTokens;
1291
+ if (isFocal && (item.rawTokens <= remaining || remaining === budget) && (curDir + item.rawTokens <= maxDirBudget || remaining === budget)) {
1292
+ remaining = Math.max(0, remaining - item.rawTokens);
1105
1293
  dirBudgetUsed[topDir] = curDir + item.rawTokens;
1106
1294
  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));
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
+ }
1111
1305
  }
1112
- out.push(` <!-- FULL: ${item.filePath}:${item.startLine}-${item.endLine} (${item.rawTokens} tokens) -->`);
1113
- out.push(item.full);
1306
+ addSelectedBlock(item.filePath, { tier: 'full', item, win });
1114
1307
  } else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
1115
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);
1116
1309
  const linked = (hop !== undefined && hop <= 2) || item.score > 0 || sameFileConst;
1117
- if (linked || i < 12) {
1310
+ if (linked) {
1118
1311
  remaining -= item.skelTokens;
1119
1312
  dirBudgetUsed[topDir] = curDir + item.skelTokens;
1120
1313
  includedIds.add(key);
1121
- includedFiles.add(item.filePath);
1122
1314
  partialFiles.add(item.filePath);
1123
1315
  if (item.skeleton === item.full) {
1124
1316
  addCoveredRange(item.filePath, item.startLine, item.endLine);
1125
1317
  }
1126
- out.push(` <!-- SKELETON: ${item.filePath}:${item.startLine}-${item.endLine} (${item.skelTokens} tokens) -->`);
1127
- out.push(item.skeleton);
1318
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop });
1128
1319
  } else {
1129
1320
  partialFiles.add(item.filePath);
1130
1321
  candidateItems.push(item);
@@ -1135,7 +1326,22 @@ for (let i = 0; i < scored.length; i++) {
1135
1326
  }
1136
1327
  }
1137
1328
 
1138
- const headerChunks = [];
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();
1139
1345
  const headerEndByFile = new Map();
1140
1346
  for (const fp of includedFiles) {
1141
1347
  const hdr = fileHeaders.get(fp);
@@ -1143,14 +1349,10 @@ for (const fp of includedFiles) {
1143
1349
  const coveredEnd = fullStart1EndLine.get(fp) || 0;
1144
1350
  if (coveredEnd >= hdr.endLine) continue;
1145
1351
  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>');
1352
+ headerByFile.set(fp, hdr);
1151
1353
  }
1152
1354
 
1153
- const footerChunks = [];
1355
+ const footerByFile = new Map();
1154
1356
  for (const fp of includedFiles) {
1155
1357
  const ftr = fileFooters.get(fp);
1156
1358
  if (!ftr) continue;
@@ -1161,21 +1363,68 @@ for (const fp of includedFiles) {
1161
1363
  const hdrEnd = headerEndByFile.get(fp) || 0;
1162
1364
  const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1163
1365
  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'));
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
+ });
1166
1372
  }
1167
1373
  }
1168
- if (footerChunks.length > 0) {
1169
- out.push('<file_footers>', ...footerChunks, '</file_footers>');
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>');
1170
1419
  }
1171
1420
 
1172
1421
  const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
1173
1422
  if (omitted.length > 0) {
1174
- out.push('<omitted_top_matches>');
1423
+ out.push(' <omitted_top_matches>');
1175
1424
  for (const o of omitted) {
1176
- out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
1425
+ out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
1177
1426
  }
1178
- out.push('</omitted_top_matches>');
1427
+ out.push(' </omitted_top_matches>');
1179
1428
  }
1180
1429
 
1181
1430
  out.push('</context_slice>');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@grundy40/contextslice",
3
- "version": "0.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).",
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
- "ast",
17
+ "structural-parsing",
18
18
  "mcp",
19
19
  "context-slice",
20
20
  "ai-coding",