@grundy40/contextslice 0.4.0 → 0.4.2

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,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.0)
3
+ * ctxslice.mjs — Zero-Config Multi-Language Local Structural Context Pre-Compiler (v0.4.2)
4
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';
@@ -125,6 +125,832 @@ function buildRepositoryFileTree(fileEntries, maxTokens = 1800) {
125
125
  }
126
126
  return out;
127
127
  }
128
+ const DOC_EXT_RE = /\.(md|mdx|rst|adoc|asciidoc)$/i;
129
+ const DOC_PATH_RE = /(^|\/)(docs?|documentation|wiki|guides?)\/|(^|\/)(README|CHANGELOG|HISTORY|CONTRIBUTING|CHANGES|RELEASES|MIGRATION|UPGRADING|AUTHORS|NOTICE|LICENSE)([^/]*)$/i;
130
+ const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|specs|testing|fixtures?|benchmarks?|examples?|samples?)\/|(\.|_)(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.[^/]+$/i;
131
+ const SYNTAX_NOISE_WORDS = new Set([
132
+ 'class', 'def', 'function', 'func', 'fn', 'struct', 'interface', 'type', 'enum',
133
+ 'const', 'let', 'var', 'async', 'await', 'import', 'export', 'return',
134
+ 'public', 'private', 'protected', 'static'
135
+ ]);
136
+
137
+ function classifyFileRole(filePath) {
138
+ const norm = String(filePath || '').replace(/\\/g, '/');
139
+ if (DOC_EXT_RE.test(norm) || DOC_PATH_RE.test(norm)) return 'doc';
140
+ if (TEST_PATH_RE.test(norm)) return 'test';
141
+ return 'source';
142
+ }
143
+
144
+ function getQueryRoleIntents(query) {
145
+ const q = String(query || '').toLowerCase();
146
+ return {
147
+ wantsDocs: /\b(readme|changelog|docs|documentation|markdown|guide)\b|\.md\b|文件|說明/.test(q),
148
+ wantsTests: /\b(tests?|specs?|pytest|unittest|jest|vitest)\b|測試/.test(q)
149
+ };
150
+ }
151
+
152
+ function sliceDocWindow(content, queryTerms, radius = 16, maxTokens = 480) {
153
+ const lines = String(content || '').replace(/\r\n/g, '\n').split('\n');
154
+ if (lines.length <= 45) {
155
+ return {
156
+ windowedCode: content,
157
+ ranges: [[1, Math.max(1, lines.length)]],
158
+ tokens: estimateTokens(content)
159
+ };
160
+ }
161
+ const matchedLines = [];
162
+ if (queryTerms && queryTerms.length > 0) {
163
+ for (let i = 0; i < lines.length; i++) {
164
+ const lower = lines[i].toLowerCase();
165
+ if (queryTerms.some((t) => lower.includes(t))) {
166
+ matchedLines.push(i + 1);
167
+ if (matchedLines.length >= 3) break;
168
+ }
169
+ }
170
+ }
171
+ const rawRanges = matchedLines.length > 0
172
+ ? matchedLines.slice(0, 2).map((ln) => [Math.max(1, ln - radius), Math.min(lines.length, ln + radius)])
173
+ : [[1, Math.min(lines.length, 24)]];
174
+ const merged = mergeLineRanges(rawRanges);
175
+ const parts = [];
176
+ const usedRanges = [];
177
+ let accTokens = 0;
178
+ for (let idx = 0; idx < merged.length; idx++) {
179
+ const s = merged[idx][0];
180
+ const e = merged[idx][1];
181
+ const sliceLines = [];
182
+ let endWritten = s - 1;
183
+ for (let ln = s; ln <= e; ln++) {
184
+ const candidate = lines[ln - 1];
185
+ const tk = estimateTokens(candidate);
186
+ if (accTokens + tk > maxTokens && sliceLines.length > 0) break;
187
+ sliceLines.push(candidate);
188
+ accTokens += tk;
189
+ endWritten = ln;
190
+ }
191
+ if (sliceLines.length === 0) break;
192
+ if (idx > 0 && usedRanges.length > 0) {
193
+ const prevEnd = usedRanges[usedRanges.length - 1][1];
194
+ if (s > prevEnd + 1) parts.push('<!-- ... lines ' + (prevEnd + 1) + '-' + (s - 1) + ' omitted ... -->');
195
+ }
196
+ parts.push(sliceLines.join('\n'));
197
+ usedRanges.push([s, endWritten]);
198
+ if (accTokens >= maxTokens) break;
199
+ }
200
+ if (usedRanges.length > 0 && usedRanges[usedRanges.length - 1][1] < lines.length) {
201
+ parts.push('<!-- ... ' + (lines.length - usedRanges[usedRanges.length - 1][1]) + ' remaining doc lines omitted ... -->');
202
+ }
203
+ const windowedCode = parts.join('\n');
204
+ return {
205
+ windowedCode,
206
+ ranges: usedRanges.length > 0 ? usedRanges : [[1, Math.min(lines.length, 20)]],
207
+ tokens: estimateTokens(windowedCode)
208
+ };
209
+ }
210
+
211
+ function findPythonSignatureEndIdx(lines, startIdx) {
212
+ let paren = 0, bracket = 0, brace = 0;
213
+ const maxScan = Math.min(lines.length - 1, startIdx + 25);
214
+ for (let j = startIdx; j <= maxScan; j++) {
215
+ const raw = lines[j];
216
+ let k = 0;
217
+ while (k < raw.length) {
218
+ const ch = raw[k];
219
+ if (ch === '#') break;
220
+ if (ch === '"' || ch === "'") {
221
+ const quote = ch;
222
+ k++;
223
+ while (k < raw.length) {
224
+ if (raw[k] === '\\') { k += 2; continue; }
225
+ if (raw[k] === quote) { k++; break; }
226
+ k++;
227
+ }
228
+ continue;
229
+ }
230
+ if (ch === '(') paren++;
231
+ else if (ch === ')') paren = Math.max(0, paren - 1);
232
+ else if (ch === '[') bracket++;
233
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
234
+ else if (ch === '{') brace++;
235
+ else if (ch === '}') brace = Math.max(0, brace - 1);
236
+ k++;
237
+ }
238
+ const noComment = raw.replace(/#.*$/, '').trimEnd();
239
+ if (paren <= 0 && bracket <= 0 && brace <= 0 && noComment.endsWith(':')) return j;
240
+ }
241
+ return startIdx;
242
+ }
243
+
244
+ function findPythonBlockEndIdx(lines, sigEndIdx, baseIndent) {
245
+ let end = sigEndIdx;
246
+ let inTriple = null;
247
+ for (let j = sigEndIdx + 1; j < lines.length; j++) {
248
+ const raw = lines[j];
249
+ const trimmed = raw.trim();
250
+ if (inTriple) {
251
+ end = j;
252
+ if ((raw.split(inTriple).length - 1) % 2 === 1) inTriple = null;
253
+ continue;
254
+ }
255
+ if (trimmed === '') { end = j; continue; }
256
+ const indent = (raw.match(/^\s*/) || [''])[0].length;
257
+ if (indent <= baseIndent) break;
258
+ end = j;
259
+ const tm = trimmed.match(/^("""|''')/);
260
+ if (tm && (trimmed.split(tm[1]).length - 1) % 2 === 1) inTriple = tm[1];
261
+ }
262
+ while (end > sigEndIdx && lines[end].trim() === '') end--;
263
+ return end;
264
+ }
265
+
266
+ function buildPythonClassSkeleton(fullClassCode, classStartLine = 1, expandedMethodRanges = []) {
267
+ const lines = String(fullClassCode || '').split('\n');
268
+ if (lines.length <= 4) return fullClassCode;
269
+ let classDefRel = 0;
270
+ while (classDefRel < lines.length && lines[classDefRel].trimStart().startsWith('@')) classDefRel++;
271
+ if (classDefRel >= lines.length) return fullClassCode;
272
+
273
+ const classIndent = (lines[classDefRel].match(/^\s*/) || [''])[0].length;
274
+ const classSigEndRel = findPythonSignatureEndIdx(lines, classDefRel);
275
+ const out = [];
276
+ for (let i = 0; i <= classSigEndRel; i++) out.push(lines[i]);
277
+
278
+ let bodyIdx = classSigEndRel + 1;
279
+ while (bodyIdx < lines.length && lines[bodyIdx].trim() === '') bodyIdx++;
280
+ if (bodyIdx < lines.length) {
281
+ const t = lines[bodyIdx].trim();
282
+ if (t.startsWith('"""') || t.startsWith("'''")) {
283
+ const q = t.slice(0, 3);
284
+ if (t.length > 3 && t.slice(3).includes(q)) {
285
+ out.push(lines[bodyIdx]);
286
+ bodyIdx++;
287
+ } else {
288
+ let docEnd = bodyIdx;
289
+ for (let j = bodyIdx + 1; j < lines.length; j++) {
290
+ if (lines[j].includes(q)) { docEnd = j; break; }
291
+ }
292
+ if (docEnd - bodyIdx <= 4) {
293
+ for (let j = bodyIdx; j <= docEnd; j++) out.push(lines[j]);
294
+ } else {
295
+ out.push(lines[bodyIdx]);
296
+ out.push(lines[bodyIdx + 1]);
297
+ const indentStr = (lines[bodyIdx].match(/^\s*/) || [' '])[0];
298
+ out.push(indentStr + '... (' + (docEnd - bodyIdx - 1) + ' docstring lines folded)');
299
+ out.push(lines[docEnd]);
300
+ }
301
+ bodyIdx = docEnd + 1;
302
+ }
303
+ }
304
+ }
305
+
306
+ let methodIndent = null;
307
+ let memberCount = 0;
308
+ for (let i = bodyIdx; i < lines.length; i++) {
309
+ const raw = lines[i];
310
+ const trimmed = raw.trim();
311
+ if (!trimmed || trimmed.startsWith('#')) continue;
312
+ const indent = (raw.match(/^\s*/) || [''])[0].length;
313
+ if (indent <= classIndent) continue;
314
+
315
+ if (trimmed.startsWith('@') && (methodIndent === null || indent === methodIndent)) {
316
+ let k = i + 1;
317
+ while (k < lines.length && lines[k].trimStart().startsWith('@')) k++;
318
+ if (k < lines.length && /^(?:async\s+)?def\s+/.test(lines[k].trim())) {
319
+ if (methodIndent === null) methodIndent = indent;
320
+ for (let d = i; d < k; d++) out.push(lines[d]);
321
+ i = k - 1;
322
+ continue;
323
+ }
324
+ }
325
+
326
+ const dm = trimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
327
+ if (dm && (methodIndent === null || indent === methodIndent)) {
328
+ methodIndent = indent;
329
+ memberCount++;
330
+ const mSigEnd = findPythonSignatureEndIdx(lines, i);
331
+ const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
332
+ const absStart = classStartLine + i;
333
+ const absEnd = classStartLine + mEnd;
334
+ const hit = expandedMethodRanges.find((r) => r.startLine <= absEnd && r.endLine >= absStart);
335
+ for (let s = i; s <= mSigEnd; s++) {
336
+ if (s === mSigEnd) {
337
+ const folded = Math.max(1, mEnd - mSigEnd);
338
+ const note = hit
339
+ ? ' # [expanded in <focal symbol="' + hit.name + '"> below]'
340
+ : ' # ... ' + folded + ' lines folded';
341
+ out.push(lines[s] + note);
342
+ } else {
343
+ out.push(lines[s]);
344
+ }
345
+ }
346
+ i = mEnd;
347
+ continue;
348
+ }
349
+
350
+ if (methodIndent === null || indent <= methodIndent) {
351
+ if (/^[A-Za-z_][A-Za-z0-9_]*\s*(?::[^=]+)?(?:=.*)?$/.test(trimmed)) {
352
+ out.push(raw);
353
+ memberCount++;
354
+ }
355
+ }
356
+ }
357
+
358
+ if (memberCount === 0) {
359
+ return lines.length > 4
360
+ ? lines.slice(0, classSigEndRel + 1).join('\n') + '\n # ... ' + (lines.length - classSigEndRel - 1) + ' lines folded'
361
+ : fullClassCode;
362
+ }
363
+ return out.join('\n');
364
+ }
365
+
366
+ function extractPythonBlocks(lines, lineIdx) {
367
+ const line = lines[lineIdx];
368
+ const m = line.match(/^(async\s+def|def|class)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
369
+ if (!m) return null;
370
+
371
+ const kind = m[1] === 'class' ? 'class' : 'function';
372
+ const name = m[2];
373
+ let startIdx = lineIdx;
374
+ while (startIdx > 0 && /^@[A-Za-z_]/.test(lines[startIdx - 1])) startIdx--;
375
+ const startLine = startIdx + 1;
376
+ const sigEndIdx = findPythonSignatureEndIdx(lines, lineIdx);
377
+ const endIdx = findPythonBlockEndIdx(lines, sigEndIdx, 0);
378
+ const endLine = endIdx + 1;
379
+ const full = lines.slice(startIdx, endIdx + 1).join('\n');
380
+ const results = [];
381
+
382
+ if (kind === 'class') {
383
+ results.push({
384
+ name,
385
+ kind: 'class',
386
+ exported: !name.startsWith('_'),
387
+ startLine,
388
+ endLine,
389
+ full,
390
+ skeleton: buildPythonClassSkeleton(full, startLine)
391
+ });
392
+ let methodIndent = null;
393
+ for (let mIdx = sigEndIdx + 1; mIdx <= endIdx; mIdx++) {
394
+ const mLine = lines[mIdx];
395
+ const mTrimmed = mLine.trim();
396
+ if (!mTrimmed || mTrimmed.startsWith('#')) continue;
397
+ const indent = (mLine.match(/^\s*/) || [''])[0].length;
398
+ if (indent <= 0) continue;
399
+ const dm = mTrimmed.match(/^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
400
+ if (!dm) continue;
401
+ if (methodIndent === null) methodIndent = indent;
402
+ if (indent !== methodIndent) continue;
403
+ const methodName = dm[1];
404
+ let mStartIdx = mIdx;
405
+ while (
406
+ mStartIdx > sigEndIdx + 1 &&
407
+ lines[mStartIdx - 1].trimStart().startsWith('@') &&
408
+ (lines[mStartIdx - 1].match(/^\s*/) || [''])[0].length === indent
409
+ ) {
410
+ mStartIdx--;
411
+ }
412
+ const mSigEnd = findPythonSignatureEndIdx(lines, mIdx);
413
+ const mEnd = findPythonBlockEndIdx(lines, mSigEnd, indent);
414
+ const mFull = lines.slice(mStartIdx, mEnd + 1).join('\n');
415
+ const mFolded = Math.max(1, mEnd - mSigEnd);
416
+ const indentStr = (mLine.match(/^\s*/) || [' '])[0];
417
+ const mSigLines = lines.slice(mStartIdx, mSigEnd + 1).join('\n');
418
+ const mSkel = mEnd - mSigEnd > 2 ? mSigLines + '\n' + indentStr + ' # ... ' + mFolded + ' lines folded' : mFull;
419
+ results.push({
420
+ name: name + '.' + methodName,
421
+ kind: 'method',
422
+ exported: !name.startsWith('_') && !methodName.startsWith('_'),
423
+ startLine: mStartIdx + 1,
424
+ endLine: mEnd + 1,
425
+ full: mFull,
426
+ skeleton: mSkel
427
+ });
428
+ mIdx = mEnd;
429
+ }
430
+ } else {
431
+ const sigLines = lines.slice(startIdx, sigEndIdx + 1).join('\n');
432
+ const skeleton = endIdx - sigEndIdx > 2 ? sigLines + '\n # ... ' + (endIdx - sigEndIdx) + ' lines folded' : full;
433
+ results.push({
434
+ name,
435
+ kind: 'function',
436
+ exported: !name.startsWith('_'),
437
+ startLine,
438
+ endLine,
439
+ full,
440
+ skeleton
441
+ });
442
+ }
443
+ return { blocks: results, endIdx };
444
+ }
445
+
446
+ function assembleContextSliceXml(opts) {
447
+ const {
448
+ blocks,
449
+ fileEntries,
450
+ fileLineCounts,
451
+ fileHeaders,
452
+ fileFooters,
453
+ rawQuery,
454
+ terms,
455
+ budget,
456
+ maxHops,
457
+ autoExpand,
458
+ rootAttr,
459
+ version,
460
+ subPathTag,
461
+ includeParserAttr,
462
+ controlWords,
463
+ maskFn
464
+ } = opts;
465
+
466
+ if (!String(rawQuery || '').trim()) {
467
+ const treeLines = buildRepositoryFileTree(fileEntries, 1800);
468
+ return [
469
+ '<context_slice mode="file_tree_empty_query" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' total_files="' + fileEntries.length + '">',
470
+ ' <note>Empty query received. Returning repository file tree overview; call context_slice again with specific symbol or file keywords to retrieve code.</note>',
471
+ ' <repository_file_tree>',
472
+ ...treeLines,
473
+ ' </repository_file_tree>',
474
+ '</context_slice>'
475
+ ].join('\n');
476
+ }
477
+
478
+ const roleIntents = getQueryRoleIntents(rawQuery);
479
+ const configWindowByKey = new Map();
480
+ const preparedBlocks = blocks.map((b) => {
481
+ const rel = b.filePath;
482
+ const key = rel + ':' + b.startLine;
483
+ const lineCount = Math.max(1, b.endLine - b.startLine + 1);
484
+ const isConfigFile = PLAIN_TEXT_CONFIG_EXT_RE.test(rel);
485
+ const isDocExt = DOC_EXT_RE.test(rel);
486
+ let win = null;
487
+ if (b.kind === 'module') {
488
+ if (isConfigFile && lineCount > 200) {
489
+ win = slicePlainTextConfigWindow(b.full, terms);
490
+ } else if (isDocExt && lineCount > 45) {
491
+ win = sliceDocWindow(b.full, terms, 16, 480);
492
+ }
493
+ }
494
+ if (win) configWindowByKey.set(key, win);
495
+ const rawTk = win ? win.tokens : (b.rawTk !== undefined ? b.rawTk : estimateTokens(b.full));
496
+ const skelTk = isDocExt
497
+ ? Math.min(b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton), win ? win.tokens : 480)
498
+ : (b.skelTk !== undefined ? b.skelTk : estimateTokens(b.skeleton));
499
+ return {
500
+ ...b,
501
+ filePath: rel,
502
+ lineCount,
503
+ role: classifyFileRole(rel),
504
+ isDocExt,
505
+ rawTk,
506
+ skelTk
507
+ };
508
+ });
509
+
510
+ const totalBlocks = Math.max(1, preparedBlocks.length);
511
+ const termDF = {};
512
+ for (const t of terms) {
513
+ let df = 0;
514
+ for (const b of preparedBlocks) {
515
+ if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
516
+ df++;
517
+ }
518
+ }
519
+ termDF[t] = Math.max(1, df);
520
+ }
521
+
522
+ const scored = preparedBlocks.map((b) => {
523
+ const nameLower = b.name.toLowerCase();
524
+ const shortLower = nameLower.includes('.') ? nameLower.split('.').pop() : nameLower;
525
+ const relLower = b.filePath.toLowerCase();
526
+ const lowerBody = b.full.toLowerCase();
527
+ let score = 0;
528
+ let matchedTerms = 0;
529
+
530
+ for (const t of terms) {
531
+ const df = termDF[t] || 1;
532
+ const idf = Math.log(1 + (totalBlocks / df));
533
+ const scarcity = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
534
+ let termScore = 0;
535
+ let hit = false;
536
+ if (nameLower === t || shortLower === t) { termScore += 48; hit = true; }
537
+ else if (nameLower.includes(t)) { termScore += 24; hit = true; }
538
+ if (relLower.includes(t)) { termScore += 12; hit = true; }
539
+ const bodyOcc = lowerBody.split(t).length - 1;
540
+ if (bodyOcc > 0) { termScore += Math.min(12, 3 * Math.log1p(bodyOcc)); hit = true; }
541
+ if (hit) matchedTerms++;
542
+ score += termScore * idf * scarcity;
543
+ }
544
+
545
+ if (matchedTerms >= 2) {
546
+ score *= 1 + 0.35 * (matchedTerms - 1);
547
+ }
548
+ if (score > 0 && (b.kind === 'function' || b.kind === 'method')) score *= 1.18;
549
+ else if (score > 0 && (b.kind === 'class' || b.kind === 'interface' || b.kind === 'type' || b.kind === 'struct')) score *= 1.08;
550
+
551
+ if (score > 0) {
552
+ if (b.role === 'doc' && !roleIntents.wantsDocs) score *= 0.10;
553
+ else if (b.role === 'test' && !roleIntents.wantsTests) score *= 0.20;
554
+ else if (b.role === 'source') score *= 1.25;
555
+ }
556
+
557
+ return { ...b, score };
558
+ }).sort((a, b) => b.score - a.score);
559
+
560
+ // Build Call Graph with shortName + common dunder guard + parent/method loop avoidance
561
+ const symbolMap = new Map();
562
+ const constSymbolNames = new Set();
563
+ for (let i = 0; i < scored.length; i++) {
564
+ const b = scored[i];
565
+ if (b.name && b.kind !== 'module' && !controlWords.has(b.name)) {
566
+ const rawShort = b.name.includes('.') ? b.name.split('.').pop() : b.name;
567
+ const names = (b.kind === 'const' && rawShort.includes(','))
568
+ ? rawShort.split(',').map((s) => s.trim()).filter(Boolean)
569
+ : [rawShort];
570
+ for (const sn of names) {
571
+ if (!sn || /^__.*__$/.test(sn)) continue;
572
+ if (!symbolMap.has(sn)) symbolMap.set(sn, []);
573
+ symbolMap.get(sn).push(i);
574
+ if (b.kind === 'const') constSymbolNames.add(sn);
575
+ }
576
+ }
577
+ }
578
+
579
+ const callAdj = Array.from({ length: scored.length }, () => new Set());
580
+ const definedNames = Array.from(symbolMap.keys());
581
+ for (let i = 0; i < scored.length; i++) {
582
+ const caller = scored[i];
583
+ const maskedCaller = maskFn(caller.full);
584
+ for (const sym of definedNames) {
585
+ const callerShort = caller.name.includes('.') ? caller.name.split('.').pop() : caller.name;
586
+ if (sym === caller.name || sym === callerShort) continue;
587
+ if (maskedCaller.includes(sym)) {
588
+ const esc = sym.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&');
589
+ const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
590
+ const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
591
+ if (re.test(maskedCaller)) {
592
+ for (const t of (symbolMap.get(sym) || [])) {
593
+ const target = scored[t];
594
+ if (caller.filePath === target.filePath && (
595
+ (caller.kind === 'class' && target.kind === 'method' && target.name.startsWith(caller.name + '.')) ||
596
+ (target.kind === 'class' && caller.kind === 'method' && caller.name.startsWith(target.name + '.'))
597
+ )) continue;
598
+ callAdj[i].add(t);
599
+ callAdj[t].add(i);
600
+ }
601
+ }
602
+ }
603
+ }
604
+ }
605
+
606
+ // Focal selection: strictly prefer source matches over docs/tests + class/method smart deduplication
607
+ const hasSourceMatches = scored.some((b) => b.role === 'source' && b.score > 0);
608
+ const eligibleIndices = [];
609
+ for (let i = 0; i < scored.length; i++) {
610
+ if (scored[i].score <= 0) continue;
611
+ if (hasSourceMatches && scored[i].role !== 'source') continue;
612
+ eligibleIndices.push(i);
613
+ }
614
+ const focalSet = new Set();
615
+ const promotedParentClassSet = new Set();
616
+ if (eligibleIndices.length > 0) {
617
+ const topScore = scored[eligibleIndices[0]].score;
618
+ const candidateIdx = eligibleIndices
619
+ .filter((idx, rank) => (rank < 3 && scored[idx].score >= topScore * 0.3) || scored[idx].score >= topScore * 0.55)
620
+ .slice(0, 5);
621
+ const candidateChosen = new Set();
622
+ for (const idx of candidateIdx) {
623
+ const b = scored[idx];
624
+ if (b.kind === 'class' && b.lineCount > 35) {
625
+ const childIndices = [];
626
+ for (let ci = 0; ci < scored.length; ci++) {
627
+ const c = scored[ci];
628
+ if (c.filePath === b.filePath && c.kind === 'method' && c.name.startsWith(b.name + '.')) {
629
+ const cShort = c.name.split('.').pop().toLowerCase();
630
+ const explicitHit = terms.some((t) => cShort === t || cShort.includes(t));
631
+ if (explicitHit || c.score >= b.score * 0.55) {
632
+ childIndices.push(ci);
633
+ }
634
+ }
635
+ }
636
+ if (childIndices.length > 0) {
637
+ promotedParentClassSet.add(idx);
638
+ for (const ci of childIndices.slice(0, 3)) candidateChosen.add(ci);
639
+ continue;
640
+ }
641
+ }
642
+ candidateChosen.add(idx);
643
+ }
644
+ for (const idx of candidateChosen) {
645
+ const b = scored[idx];
646
+ if (b.kind === 'method') {
647
+ const clsName = b.name.split('.')[0];
648
+ const hasFullParent = [...candidateChosen].some((pIdx) => {
649
+ const p = scored[pIdx];
650
+ return p && p.kind === 'class' && p.filePath === b.filePath && p.name === clsName;
651
+ });
652
+ if (hasFullParent) continue;
653
+ }
654
+ focalSet.add(idx);
655
+ }
656
+ }
657
+
658
+ // BFS from final focalSet
659
+ const hopDistances = new Map();
660
+ const focalFiles = new Set();
661
+ const bfsQ = [...focalSet];
662
+ for (const fi of bfsQ) {
663
+ hopDistances.set(fi, 0);
664
+ focalFiles.add(scored[fi].filePath);
665
+ }
666
+ let qHead = 0;
667
+ while (qHead < bfsQ.length) {
668
+ const curr = bfsQ[qHead++];
669
+ const curHop = hopDistances.get(curr) ?? 0;
670
+ if (curHop >= maxHops) continue;
671
+ for (const nbr of callAdj[curr]) {
672
+ if (!hopDistances.has(nbr)) {
673
+ hopDistances.set(nbr, curHop + 1);
674
+ bfsQ.push(nbr);
675
+ }
676
+ }
677
+ }
678
+
679
+ // Two-pass allocation ordering: ALL focal targets first, then promoted parent classes, then 1/2-hop source -> test -> doc
680
+ const roleRank = (r) => (r === 'source' ? 0 : r === 'test' ? 1 : 2);
681
+ const allocOrder = Array.from({ length: scored.length }, (_, i) => i).sort((a, b) => {
682
+ const focA = focalSet.has(a) ? 0 : 1;
683
+ const focB = focalSet.has(b) ? 0 : 1;
684
+ if (focA !== focB) return focA - focB;
685
+ const parA = promotedParentClassSet.has(a) ? 0 : 1;
686
+ const parB = promotedParentClassSet.has(b) ? 0 : 1;
687
+ if (parA !== parB) return parA - parB;
688
+ const rrA = roleRank(scored[a].role);
689
+ const rrB = roleRank(scored[b].role);
690
+ if (rrA !== rrB) return rrA - rrB;
691
+ const hopA = hopDistances.get(a) ?? 99;
692
+ const hopB = hopDistances.get(b) ?? 99;
693
+ if (hopA !== hopB) return hopA - hopB;
694
+ return scored[b].score - scored[a].score;
695
+ });
696
+
697
+ let remaining = budget;
698
+ let docBudgetUsed = 0;
699
+ let testBudgetUsed = 0;
700
+ const docBudgetCap = hasSourceMatches ? Math.min(2048, Math.floor(budget * 0.12)) : Math.min(6144, Math.floor(budget * 0.5));
701
+ const testBudgetCap = hasSourceMatches ? Math.min(3072, Math.floor(budget * 0.2)) : Math.floor(budget * 0.65);
702
+ const dirBudgetUsed = {};
703
+ const maxDirBudget = budget * 0.72;
704
+
705
+ const includedIds = new Set();
706
+ const includedFiles = [];
707
+ const includedFilesSet = new Set();
708
+ const fullStart1EndLine = new Map();
709
+ const coveredRangesByFile = new Map();
710
+ const partialFiles = new Set();
711
+ const selectedByFile = new Map();
712
+ const fullParentClassesByFile = new Map();
713
+ const skelCandidates = [];
714
+ const candidateItems = [];
715
+
716
+ const addCoveredRange = (fp, s, e) => {
717
+ if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
718
+ coveredRangesByFile.get(fp).push([s, e]);
719
+ };
720
+ const addSelectedBlock = (fp, entry) => {
721
+ if (!includedFilesSet.has(fp)) {
722
+ includedFilesSet.add(fp);
723
+ includedFiles.push(fp);
724
+ }
725
+ if (!selectedByFile.has(fp)) selectedByFile.set(fp, []);
726
+ selectedByFile.get(fp).push(entry);
727
+ };
728
+ const canUseRoleBudget = (role, cost) => {
729
+ if (role === 'doc') return docBudgetUsed + cost <= docBudgetCap;
730
+ if (role === 'test') return testBudgetUsed + cost <= testBudgetCap;
731
+ return true;
732
+ };
733
+ const addRoleBudget = (role, cost) => {
734
+ if (role === 'doc') docBudgetUsed += cost;
735
+ else if (role === 'test') testBudgetUsed += cost;
736
+ };
737
+
738
+ for (const idx of allocOrder) {
739
+ const item = scored[idx];
740
+ if (item.kind === 'method') {
741
+ const clsName = item.name.split('.')[0];
742
+ const fullSet = fullParentClassesByFile.get(item.filePath);
743
+ if (fullSet && fullSet.has(clsName)) continue;
744
+ }
745
+
746
+ const topDir = item.filePath.split('/')[0] || 'root';
747
+ const curDir = dirBudgetUsed[topDir] || 0;
748
+ const hop = hopDistances.get(idx);
749
+ const isFocal = focalSet.has(idx);
750
+ const isPromotedParent = promotedParentClassSet.has(idx);
751
+ const key = item.filePath + ':' + item.startLine;
752
+ const win = configWindowByKey.get(key);
753
+
754
+ if (isFocal && (item.rawTk <= remaining || remaining === budget) && (!hasSourceMatches || item.role !== 'doc')) {
755
+ remaining = Math.max(0, remaining - item.rawTk);
756
+ dirBudgetUsed[topDir] = curDir + item.rawTk;
757
+ addRoleBudget(item.role, item.rawTk);
758
+ includedIds.add(key);
759
+ if (item.kind === 'class') {
760
+ if (!fullParentClassesByFile.has(item.filePath)) fullParentClassesByFile.set(item.filePath, new Set());
761
+ fullParentClassesByFile.get(item.filePath).add(item.name);
762
+ }
763
+ if (win) {
764
+ for (const r of win.ranges) {
765
+ addCoveredRange(item.filePath, r[0], r[1]);
766
+ if (r[0] === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, r[1]));
767
+ }
768
+ } else {
769
+ addCoveredRange(item.filePath, item.startLine, item.endLine);
770
+ if (item.startLine === 1) fullStart1EndLine.set(item.filePath, Math.max(fullStart1EndLine.get(item.filePath) || 0, item.endLine));
771
+ }
772
+ addSelectedBlock(item.filePath, { tier: 'full', item, win, autoExpanded: false });
773
+ } else if (isPromotedParent && item.skelTk <= remaining) {
774
+ remaining -= item.skelTk;
775
+ dirBudgetUsed[topDir] = curDir + item.skelTk;
776
+ includedIds.add(key);
777
+ partialFiles.add(item.filePath);
778
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: 1 });
779
+ } else if (item.skelTk <= remaining && (curDir + item.skelTk <= maxDirBudget || item.role === 'source') && canUseRoleBudget(item.role, item.skelTk)) {
780
+ const sameFileConst = item.kind === 'const' && (item.exported || /^[A-Z][A-Z0-9_]+$/.test(item.name)) && item.lineCount <= 25 && focalFiles.has(item.filePath);
781
+ const linked = (hop !== undefined && hop <= maxHops) || item.score > 0 || sameFileConst;
782
+ if (linked) {
783
+ remaining -= item.skelTk;
784
+ dirBudgetUsed[topDir] = curDir + item.skelTk;
785
+ addRoleBudget(item.role, item.skelTk);
786
+ includedIds.add(key);
787
+ partialFiles.add(item.filePath);
788
+ if (item.skeleton === item.full && !win) addCoveredRange(item.filePath, item.startLine, item.endLine);
789
+ if (autoExpand && item.role === 'source' && !isPromotedParent) {
790
+ skelCandidates.push({ idx, item, win, hop: hop ?? null, key });
791
+ } else {
792
+ addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop: hop ?? null });
793
+ }
794
+ } else {
795
+ partialFiles.add(item.filePath);
796
+ candidateItems.push(item);
797
+ }
798
+ } else {
799
+ partialFiles.add(item.filePath);
800
+ candidateItems.push(item);
801
+ }
802
+ }
803
+
804
+ const autoExpandedNames = [];
805
+ if (autoExpand && skelCandidates.length > 0) {
806
+ for (const cand of skelCandidates) {
807
+ const it = cand.item;
808
+ const delta = Math.max(0, it.rawTk - it.skelTk);
809
+ const isComplexCluster = (cand.hop !== null || it.score > 0) && (it.lineCount >= 16 || delta >= 45);
810
+ const canExpandClass = it.kind !== 'class' || !it.filePath.endsWith('.py');
811
+ if (canExpandClass && isComplexCluster && autoExpandedNames.length < 4 && delta <= remaining) {
812
+ remaining -= delta;
813
+ autoExpandedNames.push(it.name);
814
+ if (cand.win) {
815
+ for (const r of cand.win.ranges) {
816
+ addCoveredRange(it.filePath, r[0], r[1]);
817
+ if (r[0] === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, r[1]));
818
+ }
819
+ } else {
820
+ addCoveredRange(it.filePath, it.startLine, it.endLine);
821
+ if (it.startLine === 1) fullStart1EndLine.set(it.filePath, Math.max(fullStart1EndLine.get(it.filePath) || 0, it.endLine));
822
+ }
823
+ addSelectedBlock(it.filePath, { tier: 'full', item: it, win: cand.win, autoExpanded: true });
824
+ } else {
825
+ addSelectedBlock(it.filePath, { tier: 'skeleton', item: it, win: cand.win, hop: cand.hop });
826
+ }
827
+ }
828
+ }
829
+
830
+ if (includedFiles.length === 0) {
831
+ const treeLines = buildRepositoryFileTree(fileEntries, 1800);
832
+ return [
833
+ '<context_slice mode="file_tree_zero_matches" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' query="' + escapeXmlAttr(rawQuery) + '">',
834
+ ' <note>WARNING: 0 matches found for query "' + escapeXmlText(rawQuery) + '". 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>',
835
+ ' <repository_file_tree>',
836
+ ...treeLines,
837
+ ' </repository_file_tree>',
838
+ '</context_slice>'
839
+ ].join('\n');
840
+ }
841
+
842
+ const headerByFile = new Map();
843
+ const headerEndByFile = new Map();
844
+ for (const fp of includedFiles) {
845
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
846
+ const entries = selectedByFile.get(fp) || [];
847
+ const hasStart1ModuleSkel = entries.some((e) => e.tier === 'skeleton' && e.item.kind === 'module' && e.item.startLine === 1);
848
+ if (hasStart1ModuleSkel) continue;
849
+ const hdr = fileHeaders.get(fp);
850
+ if (!hdr) continue;
851
+ if ((fullStart1EndLine.get(fp) || 0) >= hdr.endLine) continue;
852
+ headerEndByFile.set(fp, hdr.endLine);
853
+ headerByFile.set(fp, hdr);
854
+ }
855
+
856
+ const footerByFile = new Map();
857
+ for (const fp of includedFiles) {
858
+ if (PLAIN_TEXT_CONFIG_EXT_RE.test(fp) || DOC_EXT_RE.test(fp)) continue;
859
+ const ftr = fileFooters.get(fp);
860
+ if (!ftr) continue;
861
+ const ranges = coveredRangesByFile.get(fp) || [];
862
+ const totalLines = fileLineCounts.get(fp) || 0;
863
+ const wholeFileCovered = ranges.some((r) => r[0] <= 1 && r[1] >= totalLines);
864
+ if (!partialFiles.has(fp) && wholeFileCovered) continue;
865
+ const hdrEnd = headerEndByFile.get(fp) || 0;
866
+ const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some((r) => c.startLine >= r[0] && c.endLine <= r[1]));
867
+ if (uncovered.length > 0) {
868
+ footerByFile.set(fp, {
869
+ startLine: uncovered[0].startLine,
870
+ endLine: uncovered[uncovered.length - 1].endLine,
871
+ text: uncovered.map((c) => c.text).join('\n'),
872
+ chunks: uncovered
873
+ });
874
+ }
875
+ }
876
+
877
+ const used = Math.max(0, budget - remaining);
878
+ const expandAttr = autoExpandedNames.length > 0 ? ' autoExpanded="' + escapeXmlAttr(autoExpandedNames.join(',')) + '"' : '';
879
+ const out = [
880
+ '<context_slice mode="progressive-structural-slice" root="' + escapeXmlAttr(rootAttr) + '" version="' + version + '"' + (subPathTag || '') + ' budget="' + budget + '" used="' + used + '"' + expandAttr + '>'
881
+ ];
882
+
883
+ for (const fp of includedFiles) {
884
+ const rawEntries = (selectedByFile.get(fp) || []).slice().sort((a, b) => a.item.startLine - b.item.startLine);
885
+ const presentClassNames = new Set(rawEntries.filter((e) => e.item.kind === 'class').map((e) => e.item.name));
886
+ const entries = rawEntries.filter(
887
+ (e) => !(e.tier === 'skeleton' && e.item.kind === 'method' && presentClassNames.has(e.item.name.split('.')[0])),
888
+ );
889
+ const fullEntries = entries.filter((e) => e.tier === 'full');
890
+ const hdr = headerByFile.get(fp);
891
+ const ftr = footerByFile.get(fp);
892
+ const totalLines = fileLineCounts.get(fp) || 0;
893
+ const shownRanges = [];
894
+ if (hdr) shownRanges.push([1, hdr.endLine]);
895
+ for (const ent of entries) {
896
+ if (ent.win) shownRanges.push(...ent.win.ranges);
897
+ else shownRanges.push([ent.item.startLine, ent.item.endLine]);
898
+ }
899
+ if (ftr) {
900
+ for (const c of ftr.chunks) shownRanges.push([c.startLine, c.endLine]);
901
+ }
902
+ out.push(' <file path="' + escapeXmlAttr(fp) + '" total_lines="' + totalLines + '" shown_lines="' + formatShownLines(shownRanges) + '">');
903
+ if (hdr) {
904
+ out.push(' <file_header lines="1-' + hdr.endLine + '">');
905
+ out.push(hdr.header);
906
+ out.push(' </file_header>');
907
+ }
908
+ for (const ent of entries) {
909
+ const it = ent.item;
910
+ if (ent.tier === 'full') {
911
+ const linesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
912
+ const parserAttr = includeParserAttr && it.parserMode ? ' parser="' + escapeXmlAttr(it.parserMode) + '"' : '';
913
+ const autoAttr = ent.autoExpanded ? ' autoExpanded="true"' : '';
914
+ out.push(' <focal symbol="' + escapeXmlAttr(it.name) + '" lines="' + linesAttr + '"' + parserAttr + autoAttr + '>');
915
+ out.push(ent.win ? ent.win.windowedCode : it.full);
916
+ out.push(' </focal>');
917
+ } else {
918
+ let skelBody = ent.win ? ent.win.windowedCode : it.skeleton;
919
+ if (!ent.win && it.kind === 'class' && /\.pyw?$/i.test(fp)) {
920
+ const expandedChildRanges = fullEntries
921
+ .filter((fe) => fe.item.kind === 'method' && fe.item.name.startsWith(it.name + '.'))
922
+ .map((fe) => ({ name: fe.item.name, startLine: fe.item.startLine, endLine: fe.item.endLine }));
923
+ if (expandedChildRanges.length > 0) {
924
+ skelBody = buildPythonClassSkeleton(it.full, it.startLine, expandedChildRanges);
925
+ }
926
+ }
927
+ const hopAttr = (ent.hop !== null && ent.hop !== undefined) ? ' hop="' + ent.hop + '"' : '';
928
+ const skelLinesAttr = ent.win ? formatShownLines(ent.win.ranges) : (it.startLine + '-' + it.endLine);
929
+ out.push(' <skeleton symbol="' + escapeXmlAttr(it.name) + '" lines="' + skelLinesAttr + '"' + hopAttr + '>');
930
+ out.push(skelBody);
931
+ out.push(' </skeleton>');
932
+ }
933
+ }
934
+ if (ftr) {
935
+ out.push(' <file_footer lines="' + ftr.startLine + '-' + ftr.endLine + '">');
936
+ out.push(ftr.text);
937
+ out.push(' </file_footer>');
938
+ }
939
+ out.push(' </file>');
940
+ }
941
+
942
+ const omitted = candidateItems.filter((it) => it.score > 0 && !includedIds.has(it.filePath + ':' + it.startLine)).slice(0, 3);
943
+ if (omitted.length > 0) {
944
+ out.push(' <omitted_top_matches>');
945
+ for (const o of omitted) {
946
+ out.push(' <!-- Omitted: ' + o.filePath + ':' + o.startLine + ' (' + o.name + ', score: ' + o.score.toFixed(1) + ') — consider expanding -->');
947
+ }
948
+ out.push(' </omitted_top_matches>');
949
+ }
950
+
951
+ out.push('</context_slice>');
952
+ return out.join('\n');
953
+ }
128
954
 
129
955
 
130
956
  const CJK_RE = /[一-鿿぀-ゟ゠-ヿ가-힯]/;
@@ -508,17 +1334,20 @@ function expandQueryTerms(query) {
508
1334
  for (const term of snapshot) {
509
1335
  for (const t of bilingualLookup(term)) terms.add(t);
510
1336
  }
511
- return [...terms].filter(Boolean);
1337
+ // Filter pure syntax keywords (class, def, function...) whenever non-syntax identifiers exist
1338
+ const collected = [...terms].filter(Boolean);
1339
+ const nonSyntax = collected.filter((t) => !SYNTAX_NOISE_WORDS.has(t));
1340
+ return nonSyntax.length > 0 ? nonSyntax : collected;
512
1341
  }
513
1342
 
514
1343
  const args = process.argv.slice(2);
515
1344
  if (args.includes('--version') || args.includes('-v')) {
516
- process.stdout.write('ctxslice v0.4.0\n');
1345
+ process.stdout.write('ctxslice v0.4.2\n');
517
1346
  process.exit(0);
518
1347
  }
519
1348
  if (args.includes('--help') || args.includes('-h')) {
520
1349
  process.stdout.write(
521
- 'ContextSlice CLI v0.4.0 — Zero-Config Multi-Language Structural Code Slicer\n\n' +
1350
+ 'ContextSlice CLI v0.4.2 — Zero-Config Multi-Language Structural Code Slicer\n\n' +
522
1351
  'Usage:\n ctxslice "<query>" [--root <dir>] [--budget <tokens>]\n\n' +
523
1352
  'Options:\n --root <dir> Target repository path (default: current directory)\n' +
524
1353
  ' --budget <num> Max token budget (default: 32768)\n' +
@@ -623,20 +1452,10 @@ function extractBlocks(code, ext, fileName) {
623
1452
  let m = null;
624
1453
 
625
1454
  if (e === '.py' || e === '.pyw') {
626
- m = line.match(/^(?:async\s+)?(def|class)\s+([A-Za-z_][A-Za-z0-9_]*)/);
627
- if (m) {
628
- name = m[2];
629
- kind = m[1] === 'class' ? 'class' : 'function';
630
- let end = i;
631
- for (let j = i + 1; j < lines.length; j++) {
632
- if (lines[j].trim() === '' || /^\s+/.test(lines[j])) end = j;
633
- else break;
634
- }
635
- while (end > i && lines[end].trim() === '') end--;
636
- const full = lines.slice(i, end + 1).join('\n');
637
- const skeleton = end - i > 2 ? `${lines[i]}\n # ... ${end - i} lines folded` : full;
638
- blocks.push({ name, kind, startLine: i + 1, endLine: end + 1, full, skeleton });
639
- i = end;
1455
+ const pyRes = extractPythonBlocks(lines, i);
1456
+ if (pyRes) {
1457
+ blocks.push(...pyRes.blocks);
1458
+ i = pyRes.endIdx;
640
1459
  continue;
641
1460
  }
642
1461
  }
@@ -1118,314 +1937,43 @@ for (const filePath of files) {
1118
1937
  } catch {}
1119
1938
  }
1120
1939
 
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
1940
  const terms = expandQueryTerms(query);
1137
1941
  const allRawBlocks = [];
1138
1942
  const fileHeaders = new Map();
1139
1943
  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
1944
 
1170
- const totalBlocks = Math.max(1, allRawBlocks.length);
1171
- const termDF = {};
1172
- for (const t of terms) {
1173
- let df = 0;
1174
- for (const b of allRawBlocks) {
1175
- if (b.name.toLowerCase().includes(t) || b.filePath.toLowerCase().includes(t) || b.full.toLowerCase().includes(t)) {
1176
- df++;
1945
+ if (query.trim()) {
1946
+ for (const rec of textRecords) {
1947
+ const skipHdrFtr = PLAIN_TEXT_CONFIG_EXT_RE.test(rec.relPath) || DOC_EXT_RE.test(rec.relPath);
1948
+ if (!skipHdrFtr) {
1949
+ const hdr = extractFileHeader(rec.content);
1950
+ if (hdr) fileHeaders.set(rec.relPath, hdr);
1951
+ const ftr = extractFileFooter(rec.content);
1952
+ if (ftr) fileFooters.set(rec.relPath, ftr);
1177
1953
  }
1178
- }
1179
- termDF[t] = Math.max(1, df);
1180
- }
1181
-
1182
- const scored = allRawBlocks.map((b) => {
1183
- const lower = b.full.toLowerCase();
1184
- const relLower = b.filePath.toLowerCase();
1185
- let score = 0;
1186
- for (const t of terms) {
1187
- const df = termDF[t] || 1;
1188
- const idf = Math.log(1 + (totalBlocks / df));
1189
- const scarcityMultiplier = (df / totalBlocks > 0.3) ? 0.35 : (df / totalBlocks > 0.15) ? 0.7 : 1.25;
1190
- const nameMatch = b.name.toLowerCase().includes(t) ? 35 : 0;
1191
- const pathMatch = relLower.includes(t) ? 25 : 0;
1192
- const bodyOcc = lower.split(t).length - 1;
1193
- const bodyScore = Math.min(15, 3 * Math.log1p(bodyOcc));
1194
- score += (nameMatch + pathMatch + bodyScore) * idf * scarcityMultiplier;
1195
- }
1196
- return { ...b, score };
1197
- }).sort((a, b) => b.score - a.score);
1198
-
1199
- // True Call Graph (SymbolMap + Word-Boundary Call/Constant Matching + BFS maxHops)
1200
- const symbolMap = new Map();
1201
- const constSymbolNames = new Set();
1202
- for (let i = 0; i < scored.length; i++) {
1203
- const b = scored[i];
1204
- if (b.name && b.kind !== 'module' && !CONTROL_WORDS.has(b.name)) {
1205
- const names = (b.kind === 'const' && b.name.includes(','))
1206
- ? b.name.split(',').map((s) => s.trim()).filter(Boolean)
1207
- : [b.name];
1208
- for (const sn of names) {
1209
- if (!symbolMap.has(sn)) symbolMap.set(sn, []);
1210
- symbolMap.get(sn).push(i);
1211
- if (b.kind === 'const') constSymbolNames.add(sn);
1954
+ const items = extractBlocks(rec.content, path.extname(rec.filePath), rec.relPath);
1955
+ for (const b of items) {
1956
+ allRawBlocks.push({ ...b, filePath: rec.relPath });
1212
1957
  }
1213
1958
  }
1214
1959
  }
1215
- const callAdj = Array.from({ length: scored.length }, () => new Set());
1216
- const definedNames = Array.from(symbolMap.keys());
1217
- for (let i = 0; i < scored.length; i++) {
1218
- const caller = scored[i];
1219
- const maskedCaller = maskCommentsAndStrings(caller.full);
1220
- for (const sym of definedNames) {
1221
- if (sym === caller.name) continue;
1222
- if (maskedCaller.includes(sym)) {
1223
- const esc = sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1224
- const isConstRef = constSymbolNames.has(sym) && sym.length >= 3;
1225
- const re = isConstRef ? new RegExp('\\b' + esc + '\\b', 'm') : new RegExp('\\b' + esc + '\\s*\\(', 'm');
1226
- if (re.test(maskedCaller)) {
1227
- for (const t of (symbolMap.get(sym) || [])) {
1228
- callAdj[i].add(t);
1229
- callAdj[t].add(i);
1230
- }
1231
- }
1232
- }
1233
- }
1234
- }
1235
- const hopDistances = new Map();
1236
- const focalFiles = new Set();
1237
- const bfsQ = [];
1238
- for (let i = 0; i < scored.length; i++) {
1239
- if (scored[i].score > 0 && bfsQ.length < 3) {
1240
- bfsQ.push(i);
1241
- hopDistances.set(i, 0);
1242
- focalFiles.add(scored[i].filePath);
1243
- }
1244
- }
1245
- let qHead = 0;
1246
- while (qHead < bfsQ.length) {
1247
- const curr = bfsQ[qHead++];
1248
- const curHop = hopDistances.get(curr) ?? 0;
1249
- if (curHop >= 2) continue;
1250
- for (const nbr of callAdj[curr]) {
1251
- if (!hopDistances.has(nbr)) {
1252
- hopDistances.set(nbr, curHop + 1);
1253
- bfsQ.push(nbr);
1254
- }
1255
- }
1256
- }
1257
-
1258
- let remaining = budget;
1259
- const includedIds = new Set();
1260
- const includedFiles = [];
1261
- const includedFilesSet = new Set();
1262
- const fullStart1EndLine = new Map();
1263
- const coveredRangesByFile = new Map();
1264
- const partialFiles = new Set();
1265
- const selectedByFile = new Map();
1266
- const addCoveredRange = (fp, s, e) => {
1267
- if (!coveredRangesByFile.has(fp)) coveredRangesByFile.set(fp, []);
1268
- coveredRangesByFile.get(fp).push([s, e]);
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
- };
1278
- const dirBudgetUsed = {};
1279
- const maxDirBudget = budget * 0.65;
1280
-
1281
- const candidateItems = [];
1282
- for (let i = 0; i < scored.length; i++) {
1283
- const item = scored[i];
1284
- const topDir = item.filePath.split('/')[0] || 'root';
1285
- const curDir = dirBudgetUsed[topDir] || 0;
1286
- const hop = hopDistances.get(i);
1287
- const isFocal = hop === 0 || (i < 2 && item.score > 0);
1288
- const key = item.filePath + ':' + item.startLine;
1289
- const win = configWindowByKey.get(key);
1290
-
1291
- if (isFocal && (item.rawTokens <= remaining || remaining === budget) && (curDir + item.rawTokens <= maxDirBudget || remaining === budget)) {
1292
- remaining = Math.max(0, remaining - item.rawTokens);
1293
- dirBudgetUsed[topDir] = curDir + item.rawTokens;
1294
- includedIds.add(key);
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
- }
1305
- }
1306
- addSelectedBlock(item.filePath, { tier: 'full', item, win });
1307
- } else if (item.skelTokens <= remaining && curDir + item.skelTokens <= maxDirBudget) {
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);
1309
- const linked = (hop !== undefined && hop <= 2) || item.score > 0 || sameFileConst;
1310
- if (linked) {
1311
- remaining -= item.skelTokens;
1312
- dirBudgetUsed[topDir] = curDir + item.skelTokens;
1313
- includedIds.add(key);
1314
- partialFiles.add(item.filePath);
1315
- if (item.skeleton === item.full) {
1316
- addCoveredRange(item.filePath, item.startLine, item.endLine);
1317
- }
1318
- addSelectedBlock(item.filePath, { tier: 'skeleton', item, win, hop });
1319
- } else {
1320
- partialFiles.add(item.filePath);
1321
- candidateItems.push(item);
1322
- }
1323
- } else {
1324
- partialFiles.add(item.filePath);
1325
- candidateItems.push(item);
1326
- }
1327
- }
1328
-
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();
1345
- const headerEndByFile = new Map();
1346
- for (const fp of includedFiles) {
1347
- const hdr = fileHeaders.get(fp);
1348
- if (!hdr) continue;
1349
- const coveredEnd = fullStart1EndLine.get(fp) || 0;
1350
- if (coveredEnd >= hdr.endLine) continue;
1351
- headerEndByFile.set(fp, hdr.endLine);
1352
- headerByFile.set(fp, hdr);
1353
- }
1354
-
1355
- const footerByFile = new Map();
1356
- for (const fp of includedFiles) {
1357
- const ftr = fileFooters.get(fp);
1358
- if (!ftr) continue;
1359
- const ranges = coveredRangesByFile.get(fp) || [];
1360
- const totalLines = fileLineCounts.get(fp) || 0;
1361
- const wholeFileCovered = ranges.some(([s, e]) => s <= 1 && e >= totalLines);
1362
- if (!partialFiles.has(fp) && wholeFileCovered) continue;
1363
- const hdrEnd = headerEndByFile.get(fp) || 0;
1364
- const uncovered = ftr.chunks.filter((c) => c.startLine > hdrEnd && !ranges.some(([s, e]) => c.startLine >= s && c.endLine <= e));
1365
- if (uncovered.length > 0) {
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
- });
1372
- }
1373
- }
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>');
1419
- }
1420
-
1421
- const omitted = candidateItems.filter(item => item.score > 0 && !includedIds.has(item.filePath + ':' + item.startLine)).slice(0, 3);
1422
- if (omitted.length > 0) {
1423
- out.push(' <omitted_top_matches>');
1424
- for (const o of omitted) {
1425
- out.push(` <!-- Omitted: ${o.filePath}:${o.startLine} (${o.name}, score: ${o.score.toFixed(1)}) — consider expanding -->`);
1426
- }
1427
- out.push(' </omitted_top_matches>');
1428
- }
1429
1960
 
1430
- out.push('</context_slice>');
1431
- process.stdout.write(out.join('\n') + '\n');
1961
+ const outputXml = assembleContextSliceXml({
1962
+ blocks: allRawBlocks,
1963
+ fileEntries,
1964
+ fileLineCounts,
1965
+ fileHeaders,
1966
+ fileFooters,
1967
+ rawQuery: query,
1968
+ terms,
1969
+ budget,
1970
+ maxHops: 2,
1971
+ autoExpand: false,
1972
+ rootAttr: path.basename(targetRoot),
1973
+ version: '0.4.2',
1974
+ subPathTag: '',
1975
+ includeParserAttr: false,
1976
+ controlWords: CONTROL_WORDS,
1977
+ maskFn: maskCommentsAndStrings
1978
+ });
1979
+ process.stdout.write(outputXml + '\n');