claude-code-token-optimization-by-tool-call 0.0.0-stage → 0.2.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.
@@ -0,0 +1,319 @@
1
+ // extract(text, opts) -> string. Pure: no I/O.
2
+ //
3
+ // Success (exit 0): `0`, or `0` plus a warnings section when showWarning.
4
+ // Failure: a header line, then either the whole (short) output or a set of
5
+ // `L<a>-L<b>:` blocks chosen by parser, within budgetChars.
6
+ import { toLines, cutLine } from './clean.mjs';
7
+ import { pickParser, generic, npmPnpm } from './parsers/index.mjs';
8
+ import { renderBlocks, collapseConsecutive, droppedLine, mergeRanges } from './format.mjs';
9
+ import { extractWarnings, isWarning } from './warnings.mjs';
10
+
11
+ export const DEFAULT_BUDGET = 6000;
12
+ export const SHORT_MAX_LINES = 60;
13
+ export const TAIL_LINES = 15;
14
+ export const TAIL_MAX_CHARS = 1500;
15
+ const TRAILER_RESERVE = 110;
16
+ const MAX_FAILED_TRIES = 40;
17
+ const MIN_USEFUL = 40;
18
+ // Share of the budget that context fill (step 5) may use.
19
+ export const CONTEXT_FILL = 1;
20
+
21
+ // A short failure returns its whole output, so a log reference would only add
22
+ // ~100 chars to most failures: the header is then just the exit code.
23
+ // The long-failure log path stays absolute: a reader's file tool needs it as is.
24
+ export function header({ exitCode, profile, lines, logPath, timedOut }) {
25
+ if (profile === 'short') return `exit=${exitCode}${timedOut ? ' timeout' : ''}`;
26
+ return `exit=${exitCode} profile=${profile} lines=${lines} log=${logPath}${timedOut ? ' timeout' : ''}`;
27
+ }
28
+
29
+ // Last 15 non-empty lines, at most ~1500 chars (trimmed from the front).
30
+ export function tailBlock(lines, maxLines = TAIL_LINES, maxChars = TAIL_MAX_CHARS) {
31
+ let end = lines.length - 1;
32
+ while (end >= 0 && lines[end].trim() === '') end--;
33
+ if (end < 0) return null;
34
+ let start = end;
35
+ let count = 0;
36
+ let chars = 0;
37
+ for (let i = end; i >= 0; i--) {
38
+ if (lines[i].trim() === '') continue;
39
+ const len = cutLine(lines[i]).length + 1;
40
+ if (count > 0 && chars + len > maxChars) break;
41
+ chars += len;
42
+ count++;
43
+ start = i;
44
+ if (count >= maxLines) break;
45
+ }
46
+ return { start, end, priority: 3, tail: true };
47
+ }
48
+
49
+ export const HEAD_LINES = 10;
50
+ export const HEAD_MAX_CHARS = 1000;
51
+
52
+ // First 10 non-empty lines (~1000 chars): what ran and the first thing it said.
53
+ export function headBlock(lines, maxLines = HEAD_LINES, maxChars = HEAD_MAX_CHARS) {
54
+ let count = 0;
55
+ let chars = 0;
56
+ let end = -1;
57
+ for (let i = 0; i < lines.length; i++) {
58
+ if (lines[i].trim() === '') continue;
59
+ const len = cutLine(lines[i]).length + 1;
60
+ if (count > 0 && chars + len > maxChars) break;
61
+ chars += len;
62
+ count++;
63
+ end = i;
64
+ if (count >= maxLines) break;
65
+ }
66
+ return end < 0 ? null : { start: 0, end, priority: 0, head: true };
67
+ }
68
+
69
+ function covered(b, selected) {
70
+ // true when every line of b is inside some selected block
71
+ outer: for (let i = b.start; i <= b.end; i++) {
72
+ for (const s of selected) if (i >= s.start && i <= s.end) continue outer;
73
+ return false;
74
+ }
75
+ return true;
76
+ }
77
+
78
+ function renderWithin(lines, selected, budget) {
79
+ const body = renderBlocks(lines, selected);
80
+ return body.length <= budget ? body : null;
81
+ }
82
+
83
+ /**
84
+ * Choose and render blocks for a long failure output. Returns { profile, body }.
85
+ */
86
+ export function longBody(lines, { command = '', budgetChars = DEFAULT_BUDGET } = {}) {
87
+ const { winner } = pickParser(lines, command);
88
+ const profile = winner ? winner.name : 'generic';
89
+ const fillBudget = Math.max(0, budgetChars - TRAILER_RESERVE);
90
+
91
+ const selected = [];
92
+ const tail = tailBlock(lines);
93
+ if (tail) {
94
+ // the tail is always included; shrink it from the front if the budget is tiny
95
+ let t = { ...tail };
96
+ while (t.start < t.end && renderBlocks(lines, [t]).length > fillBudget) t.start++;
97
+ selected.push(t);
98
+ }
99
+
100
+ let parserCands = [];
101
+ if (winner) {
102
+ parserCands = winner.blocks(lines).map((b) => ({ ...b }));
103
+ if (winner !== npmPnpm && npmPnpm.detect(lines) >= 0.5) parserCands.push(...npmPnpm.blocks(lines));
104
+ parserCands.sort((a, b) => b.priority - a.priority || a.start - b.start);
105
+ }
106
+ const genericCands = generic.blocks(lines);
107
+
108
+ const dropped = [];
109
+ let failures = 0;
110
+ let current = renderBlocks(lines, selected);
111
+ const tryAdd = (cand) => {
112
+ if (covered(cand, selected)) return;
113
+ if (cand.hit !== undefined && covered({ start: cand.hit, end: cand.hit }, selected)) return;
114
+ if (failures >= MAX_FAILED_TRIES || fillBudget - current.length < MIN_USEFUL) {
115
+ dropped.push(cand);
116
+ return;
117
+ }
118
+ const whole = renderWithin(lines, [...selected, cand], fillBudget);
119
+ if (whole !== null) {
120
+ selected.push(cand);
121
+ current = whole;
122
+ return;
123
+ }
124
+ // largest prefix of the block that fits
125
+ let lo = cand.start;
126
+ let hi = cand.end - 1;
127
+ let best = -1;
128
+ let bestBody = null;
129
+ while (lo <= hi) {
130
+ const mid = (lo + hi) >> 1;
131
+ const body = renderWithin(lines, [...selected, { ...cand, end: mid }], fillBudget);
132
+ if (body !== null) {
133
+ best = mid;
134
+ bestBody = body;
135
+ lo = mid + 1;
136
+ } else hi = mid - 1;
137
+ }
138
+ if (best >= cand.start && bestBody !== current) {
139
+ selected.push({ ...cand, end: best });
140
+ current = bestBody;
141
+ dropped.push({ ...cand, start: best + 1 });
142
+ } else {
143
+ dropped.push(cand);
144
+ }
145
+ failures++;
146
+ };
147
+
148
+ for (const c of parserCands) tryAdd(c);
149
+ for (const c of genericCands) tryAdd(c);
150
+ // 4-5. leftover budget: context. First the head of the output, then the
151
+ // gaps between chosen blocks, smallest first. Context never brings back
152
+ // warning lines or lines the parser calls noise (they were skipped on purpose).
153
+ const ctxCap = Math.min(fillBudget, Math.round(budgetChars * CONTEXT_FILL));
154
+ const isNoise = (l) => isWarning(l) || (winner?.noise ? winner.noise(l) : false);
155
+ const runsOf = (r) => {
156
+ const out = [];
157
+ let start = -1;
158
+ for (let i = r.start; i <= r.end + 1; i++) {
159
+ const ok = i <= r.end && !isNoise(lines[i]);
160
+ if (ok && start < 0) start = i;
161
+ else if (!ok && start >= 0) {
162
+ out.push({ start, end: i - 1 });
163
+ start = -1;
164
+ }
165
+ }
166
+ // a run of blank lines only would render as an empty `L<a>-L<b>:` block
167
+ return out.filter((r) => lines.slice(r.start, r.end + 1).some((l) => l.trim()));
168
+ };
169
+ let tries = 0;
170
+ const addContext = (r) => {
171
+ if (ctxCap - current.length < MIN_USEFUL || tries > MAX_FAILED_TRIES || covered(r, selected)) return;
172
+ const body = renderWithin(lines, [...selected, r], ctxCap);
173
+ if (body !== null) {
174
+ selected.push(r);
175
+ current = body;
176
+ } else tries++;
177
+ };
178
+ const head = headBlock(lines);
179
+ if (head) for (const r of runsOf(head)) addContext(r);
180
+ if (current.length < ctxCap) {
181
+ const ranges = mergeRanges(selected);
182
+ const gaps = [];
183
+ for (let k = 0; k < ranges.length; k++) {
184
+ const from = k === 0 ? 0 : ranges[k - 1].end + 1;
185
+ if (ranges[k].start > from) gaps.push({ start: from, end: ranges[k].start - 1 });
186
+ }
187
+ const last = ranges[ranges.length - 1];
188
+ if (last && last.end < lines.length - 1) gaps.push({ start: last.end + 1, end: lines.length - 1 });
189
+ const runs = gaps.flatMap(runsOf).sort((x, y) => x.end - x.start - (y.end - y.start) || x.start - y.start);
190
+ for (const r of runs) addContext(r);
191
+ }
192
+
193
+ const stillDropped = dropped.filter((d) => !covered(d, selected)).sort((a, b) => a.start - b.start);
194
+ let body = current;
195
+ if (stillDropped.length) body += (body ? '\n\n' : '') + droppedLine(stillDropped);
196
+ if (body.length > budgetChars) body = body.slice(0, Math.max(0, budgetChars - 1)) + '…';
197
+ return { profile, body };
198
+ }
199
+
200
+ export function extract(text, opts = {}) {
201
+ const { exitCode = 1, command = '', logPath = '', budgetChars = DEFAULT_BUDGET, timedOut = false, showWarning = false, explainSuccess = false, largeOutputBytes = LARGE_OUTPUT_BYTES } = opts;
202
+ let big = largeOutputLine(text, largeOutputBytes);
203
+ // The reader needs the log path to read ranges. A failure this large always has
204
+ // it in its header and an explained success in its line; a bare `0` does not.
205
+ if (big && logPath && exitCode === 0 && !timedOut && !explainSuccess) big += ` log=${logPath}`;
206
+ if (exitCode === 0 && !timedOut) {
207
+ const ok = explainSuccess ? successLine(text, logPath) : '0';
208
+ const parts = [ok, big];
209
+ if (showWarning) parts.push(extractWarnings(text, { budgetChars, logPath }));
210
+ return parts.filter(Boolean).join('\n');
211
+ }
212
+ // The line counts toward the budget: the body gets what is left. A tight
213
+ // budget gets the short form, and none at all when even that leaves no room.
214
+ if (big && big.length + 1 + MIN_USEFUL > budgetChars) {
215
+ const b = largeOutput(text, largeOutputBytes);
216
+ big = `warning: large output: ${kb(b.bytes)} (~${ktok(b.tokens)} tokens)`;
217
+ if (big.length + 1 + MIN_USEFUL > budgetChars) big = '';
218
+ }
219
+ const bodyBudget = big ? budgetChars - big.length - 1 : budgetChars;
220
+ return withLargeLine(failure(text, { exitCode, command, logPath, budgetChars: bodyBudget, timedOut, showWarning }), big);
221
+ }
222
+
223
+ // The large-output line goes right under the failure header, where it is seen first.
224
+ function withLargeLine(out, big) {
225
+ if (!big) return out;
226
+ const i = out.indexOf('\n');
227
+ return i === -1 ? `${out}\n${big}` : `${out.slice(0, i)}\n${big}${out.slice(i)}`;
228
+ }
229
+
230
+ function failure(text, { exitCode, command, logPath, budgetChars, timedOut, showWarning }) {
231
+ const lines = toLines(text);
232
+ const n = lines.length;
233
+ if (isBinary(text)) {
234
+ const h = header({ exitCode, profile: 'binary', lines: n, logPath, timedOut });
235
+ return `${h}\n[binary output: ${text.length} chars, not shown; see log]`;
236
+ }
237
+ if (n <= SHORT_MAX_LINES) {
238
+ const body = collapseConsecutive(lines).join('\n');
239
+ if (body.length <= budgetChars) {
240
+ const h = header({ exitCode, profile: 'short', lines: n, logPath, timedOut });
241
+ return body ? `${h}\n${body}` : h;
242
+ }
243
+ }
244
+ // On failure, showWarning appends the warnings section; its share comes out of the budget.
245
+ let warn = '';
246
+ if (showWarning) {
247
+ warn = extractWarnings(text, { budgetChars: Math.round(budgetChars * FAIL_WARN_SHARE), logPath });
248
+ }
249
+ const bodyBudget = warn ? budgetChars - warn.length - 2 : budgetChars;
250
+ const { profile, body } = longBody(lines, { command, budgetChars: bodyBudget });
251
+ const h = header({ exitCode, profile, lines: n, logPath, timedOut });
252
+ const full = [body, warn].filter(Boolean).join('\n\n');
253
+ return full ? `${h}\n${full}` : h;
254
+ }
255
+
256
+ const FAIL_WARN_SHARE = 0.25;
257
+
258
+ // Output above this many bytes (cleaned, as written to the log) gets a one-line
259
+ // warning. Claude Code's Bash tool keeps ~30k chars of a result; a log above
260
+ // 100 KB costs ~30k tokens or more to read whole, so the reader should read
261
+ // line ranges, and the command is a candidate for a quieter reporter.
262
+ export const LARGE_OUTPUT_BYTES = 100_000;
263
+ const CHARS_PER_TOKEN = 3.5;
264
+
265
+ // The threshold from RUN_TOOL_LARGE_OUTPUT_BYTES (0 turns the warning off), else the default.
266
+ export function largeOutputThreshold(env = process.env) {
267
+ const v = env.RUN_TOOL_LARGE_OUTPUT_BYTES;
268
+ const n = Number(v);
269
+ return v !== undefined && v !== '' && Number.isFinite(n) && n >= 0 ? n : LARGE_OUTPUT_BYTES;
270
+ }
271
+
272
+ // Size of a command's output: bytes, lines and the token estimate of reading it whole.
273
+ export function outputSize(text) {
274
+ const bytes = Buffer.byteLength(text || '');
275
+ return { bytes, lines: text ? toLines(text).length : 0, tokens: Math.round((text || '').length / CHARS_PER_TOKEN) };
276
+ }
277
+
278
+ // null when the output is within the threshold (0 or a non-number turns the check off).
279
+ export function largeOutput(text, threshold = LARGE_OUTPUT_BYTES) {
280
+ if (!(threshold > 0)) return null;
281
+ const size = outputSize(text);
282
+ return size.bytes > threshold ? { ...size, threshold } : null;
283
+ }
284
+
285
+ const kb = (n) => `${Math.round(n / 1000)} KB`;
286
+ const ktok = (n) => (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
287
+
288
+ export function largeOutputLine(text, threshold = LARGE_OUTPUT_BYTES) {
289
+ const big = largeOutput(text, threshold);
290
+ if (!big) return '';
291
+ return `warning: large output: ${kb(big.bytes)}, ${big.lines} lines (over ${kb(threshold)}; ~${ktok(big.tokens)} tokens to read whole). Read line ranges of the log, and consider a quieter command (e.g. --silent, a dot reporter).`;
292
+ }
293
+
294
+ // An agent that did not call run itself (the hook rewrote its command) reads a
295
+ // bare `0` as the command's own output and goes looking for the real one: say
296
+ // what happened, in one line.
297
+ export function successLine(text, logPath) {
298
+ const n = text ? toLines(text).filter((l) => l.trim()).length : 0;
299
+ if (!n) return '0 (exit 0, no output)';
300
+ return `0 (exit 0; ${n} line${n === 1 ? '' : 's'} of output hidden by run-tool; log=${logPath})`;
301
+ }
302
+
303
+ // Binary output (a NUL byte, or many U+FFFD from invalid UTF-8) is noise to a reader.
304
+ const BINARY_SAMPLE = 65536;
305
+ const BINARY_REPLACEMENT_SHARE = 0.1;
306
+ export function isBinary(text) {
307
+ const s = text.slice(0, BINARY_SAMPLE);
308
+ if (!s) return false;
309
+ if (s.includes('\u0000')) return true;
310
+ let bad = 0;
311
+ for (const ch of s) if (ch === '�') bad++;
312
+ return bad / s.length > BINARY_REPLACEMENT_SHARE;
313
+ }
314
+
315
+ // Body of an extract (everything after the header line).
316
+ export function bodyOf(out) {
317
+ const i = out.indexOf('\n');
318
+ return i === -1 ? '' : out.slice(i + 1);
319
+ }
package/src/format.mjs ADDED
@@ -0,0 +1,232 @@
1
+ // Block rendering: stack-frame folding, consecutive-duplicate collapse,
2
+ // cross-block message dedupe, long-line cut.
3
+ import { cutLine } from './clean.mjs';
4
+
5
+ const NODE_FRAME = /^\s+at\s+\S/;
6
+ // V8 frames without the `at ` prefix (e.g. node:test YAML `stack:` lines)
7
+ const BARE_FRAME = /^\s+[\w$.<>\[\]]+(?: \[as [\w$]+\])? \((?:[^()]|\([^()]*\))+:\d+:\d+\)\s*$/;
8
+ const PY_FRAME = /^\s*File "[^"]+", line \d+/;
9
+ const LIBRARY = /node_modules|node:internal|internal\/|site-packages|<anonymous>|<frozen |\/usr\/lib\/python/;
10
+
11
+ export const MAX_PROJECT_FRAMES = 3;
12
+ export const MAX_HINTS = 2;
13
+ const HINT = /^hint: /;
14
+
15
+ export function isFrame(line) {
16
+ return NODE_FRAME.test(line) || BARE_FRAME.test(line) || PY_FRAME.test(line);
17
+ }
18
+ export const isLibraryFrame = (text) => LIBRARY.test(text);
19
+
20
+ // Normalised form of a message, for "same message" comparison across blocks.
21
+ // Only volatile numbers are masked (hex ids, timestamps, durations, long
22
+ // decimals, line:col), so messages differing in a meaningful number (an
23
+ // expected value, a count) stay distinct.
24
+ export function normalizeMessage(line) {
25
+ return line
26
+ .trim()
27
+ .replace(/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{6,}\b/gi, 'H')
28
+ .replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2})?(\.\d+)?Z?/g, 'T')
29
+ .replace(/\b\d{1,2}:\d{2}:\d{2}(\.\d+)?\b/g, 'T')
30
+ .replace(/:\d+:\d+\b/g, ':N:N')
31
+ .replace(/\b\d+(\.\d+)?\s?(ms|s|µs|ns)\b/g, 'Nms')
32
+ .replace(/\b\d+\.\d{3,}\b/g, 'N');
33
+ }
34
+
35
+ // Collapse runs of identical lines into `<line> (×N)`.
36
+ export function collapseConsecutive(lines) {
37
+ const out = [];
38
+ for (let i = 0; i < lines.length; ) {
39
+ let j = i + 1;
40
+ while (j < lines.length && lines[j] === lines[i]) j++;
41
+ const n = j - i;
42
+ out.push(n > 1 ? `${lines[i]} (×${n})` : lines[i]);
43
+ i = j;
44
+ }
45
+ return out;
46
+ }
47
+
48
+ export function mergeRanges(blocks) {
49
+ const sorted = blocks.map((b) => ({ start: b.start, end: b.end })).sort((a, b) => a.start - b.start || a.end - b.end);
50
+ const out = [];
51
+ for (const b of sorted) {
52
+ const prev = out[out.length - 1];
53
+ if (prev && b.start <= prev.end + 1) prev.end = Math.max(prev.end, b.end);
54
+ else out.push({ ...b });
55
+ }
56
+ return out;
57
+ }
58
+
59
+ // Markup dumps (Testing Library's "Ignored nodes … <body>", snapshot diffs of
60
+ // HTML) can run to hundreds of lines and crowd out the failing assertion.
61
+ // Colour remnants like `[36m` (ESC already removed upstream) are ignored.
62
+ const MARKUP = /^\s*(<\/?[\w.:-]+|\/?>|[\w:@.-]+=(["{]|$)|<!--)/;
63
+ const COLOUR_REMNANT = /\x1b?\[\d+(?:;\d+)*m/g;
64
+ export const MARKUP_MIN_RUN = 8;
65
+ const MARKUP_KEEP = 2;
66
+ const MARKUP_SIG_MAX = 400;
67
+ export const isMarkup = (line) => MARKUP.test(line.replace(COLOUR_REMNANT, ''));
68
+
69
+ // Linter tables pad every row to align the rule column (eslint stylish: often
70
+ // 100+ spaces). Only such rows are squeezed: code frames need their spacing
71
+ // for the `^`/`~~~` markers to point at the right column.
72
+ const LINT_ROW = /^\s+\d+:\d+\s+(error|warning)\s/;
73
+ export function squeezeColumns(line) {
74
+ if (!LINT_ROW.test(line)) return line;
75
+ const indent = /^\s*/.exec(line)[0];
76
+ return indent + line.slice(indent.length).replace(/ {3,}/g, ' ').trimEnd();
77
+ }
78
+
79
+ // Build display items for lines[start..end], folding stack traces and markup dumps.
80
+ function itemsFor(lines, start, end, owner) {
81
+ const items = [];
82
+ let i = start;
83
+ while (i <= end) {
84
+ if (isMarkup(lines[i])) {
85
+ let j = i;
86
+ while (j + 1 <= end && (isMarkup(lines[j + 1]) || !lines[j + 1].trim() || /^\s+\S/.test(lines[j + 1]) && isMarkup(lines[Math.min(j + 2, end)]))) j++;
87
+ if (j - i + 1 >= MARKUP_MIN_RUN) {
88
+ for (let k = i; k < i + MARKUP_KEEP; k++) items.push({ text: lines[k], line: k + 1, owner: owner[k], kind: 'line' });
89
+ // what a reader needs from a DOM dump is what rendered: text nodes and test ids
90
+ const seenSig = new Set();
91
+ const sig = [];
92
+ for (let k = i + MARKUP_KEEP; k <= j; k++) {
93
+ const t = lines[k].replace(COLOUR_REMNANT, '').trim();
94
+ const id = /\bdata-test(?:id|-id)?=["']([^"']+)["']/.exec(t);
95
+ const s = id ? `#${id[1]}` : t && !isMarkup(t) ? `"${t}"` : null;
96
+ if (s && !seenSig.has(s)) { seenSig.add(s); sig.push(s); }
97
+ }
98
+ let sigText = '';
99
+ for (const s of sig) {
100
+ if (sigText.length + s.length > MARKUP_SIG_MAX) { sigText += ' …'; break; }
101
+ sigText += (sigText ? ' ' : '') + s;
102
+ }
103
+ items.push({ text: ` (+${j - i + 1 - MARKUP_KEEP} lines of markup, L${i + MARKUP_KEEP + 1}-L${j + 1}${sigText ? `; rendered: ${sigText}` : ''})`, line: i + MARKUP_KEEP + 1, owner: owner[i], kind: 'fold' });
104
+ i = j + 1;
105
+ continue;
106
+ }
107
+ }
108
+ if (HINT.test(lines[i])) {
109
+ // git hint: runs are folded to their first two lines
110
+ let j = i;
111
+ while (j + 1 <= end && HINT.test(lines[j + 1])) j++;
112
+ for (let k = i; k <= Math.min(j, i + MAX_HINTS - 1); k++) items.push({ text: lines[k], line: k + 1, owner: owner[k], kind: 'line' });
113
+ if (j - i + 1 > MAX_HINTS) items.push({ text: `hint: (+${j - i + 1 - MAX_HINTS} lines)`, line: i + MAX_HINTS + 1, owner: owner[i], kind: 'fold' });
114
+ i = j + 1;
115
+ continue;
116
+ }
117
+ if (!isFrame(lines[i])) {
118
+ items.push({ text: lines[i], line: i + 1, owner: owner[i], kind: 'line' });
119
+ i++;
120
+ continue;
121
+ }
122
+ // collect one trace: consecutive frames (a python frame owns its code line)
123
+ const frames = [];
124
+ while (i <= end && isFrame(lines[i])) {
125
+ const f = { idx: [i], text: lines[i] };
126
+ if (PY_FRAME.test(lines[i]) && i + 1 <= end && !isFrame(lines[i + 1]) && /^\s+\S/.test(lines[i + 1])) {
127
+ f.idx.push(i + 1);
128
+ i++;
129
+ }
130
+ frames.push(f);
131
+ i++;
132
+ }
133
+ const project = frames.filter((f) => !isLibraryFrame(f.text));
134
+ let keep = project.slice(0, MAX_PROJECT_FRAMES);
135
+ if (!keep.length) keep = frames.slice(0, 1);
136
+ const keepSet = new Set(keep);
137
+ const hidden = frames.length - keep.length;
138
+ for (const f of frames) {
139
+ if (!keepSet.has(f)) continue;
140
+ for (const k of f.idx) items.push({ text: lines[k], line: k + 1, owner: owner[k], kind: 'frame' });
141
+ }
142
+ if (hidden > 0) {
143
+ const indent = /^\s*/.exec(frames[0].text)[0];
144
+ items.push({ text: `${indent}(+${hidden} frames)`, line: frames[0].idx[0] + 1, owner: owner[frames[0].idx[0]], kind: 'fold' });
145
+ }
146
+ }
147
+ return items;
148
+ }
149
+
150
+ const DEDUPE_MIN = 12;
151
+ const MAX_REFS = 3;
152
+
153
+ /**
154
+ * Render selected blocks ({start,end} 0-based inclusive, possibly overlapping)
155
+ * as `L<a>-L<b>:` blocks in log order. A line belongs to the earliest selected
156
+ * block covering it; a message already shown by another block is dropped and
157
+ * the first occurrence is annotated `(×N, also L…)`.
158
+ */
159
+ export function renderBlocks(lines, blocks) {
160
+ const sel = blocks.filter((b) => b.end >= b.start).slice().sort((a, b) => a.start - b.start || b.end - a.end);
161
+ // tail lines are always shown verbatim: never removed as repeats
162
+ const pinned = new Set();
163
+ for (const b of sel) if (b.tail) for (let i = b.start; i <= b.end; i++) pinned.add(i + 1);
164
+ const owner = {};
165
+ sel.forEach((b, n) => {
166
+ for (let i = b.start; i <= b.end; i++) if (!(i in owner)) owner[i] = n;
167
+ });
168
+ const ranges = mergeRanges(sel);
169
+ const rendered = [];
170
+ const seen = new Map(); // key -> {item, count, refs}
171
+ for (const r of ranges) {
172
+ const items = itemsFor(lines, r.start, r.end, owner);
173
+ // consecutive identical lines
174
+ const collapsed = [];
175
+ for (const it of items) {
176
+ const prev = collapsed[collapsed.length - 1];
177
+ if (prev && prev.kind !== 'fold' && it.kind !== 'fold' && prev.text === it.text) prev.count++;
178
+ else collapsed.push({ ...it, count: 1 });
179
+ }
180
+ // cross-block dedupe
181
+ const kept = [];
182
+ let removedRun = 0;
183
+ const flushRemoved = () => {
184
+ // a single repeated line is just dropped; a run gets a marker
185
+ if (removedRun >= 2) kept.push({ text: ` (+${removedRun} repeated lines)`, kind: 'fold', count: 1 });
186
+ removedRun = 0;
187
+ };
188
+ for (const it of collapsed) {
189
+ if (it.kind !== 'fold' && !pinned.has(it.line) && it.text.trim().length >= DEDUPE_MIN) {
190
+ const key = normalizeMessage(it.text);
191
+ const first = seen.get(key);
192
+ if (first && first.item.owner !== it.owner) {
193
+ first.count += it.count;
194
+ first.refs.push(it.line);
195
+ removedRun++;
196
+ continue;
197
+ }
198
+ if (!first) seen.set(key, { item: it, count: it.count, refs: [] });
199
+ }
200
+ flushRemoved();
201
+ kept.push(it);
202
+ }
203
+ flushRemoved();
204
+ if (kept.some((k) => k.kind !== 'fold')) rendered.push({ r, items: kept });
205
+ }
206
+ const parts = [];
207
+ for (const { r, items } of rendered) {
208
+ const out = [`L${r.start + 1}-L${r.end + 1}:`];
209
+ for (const it of items) {
210
+ let text = it.kind === 'fold' ? it.text : cutLine(squeezeColumns(it.text));
211
+ const d = it.kind !== 'fold' && it.text.trim().length >= DEDUPE_MIN ? seen.get(normalizeMessage(it.text)) : null;
212
+ if (d && d.item === it && d.refs.length) {
213
+ const refs = d.refs.slice(0, MAX_REFS).map((n) => `L${n}`).join(',');
214
+ text += ` (×${d.count}, also ${refs}${d.refs.length > MAX_REFS ? ',…' : ''})`;
215
+ } else if (it.count > 1) {
216
+ text += ` (×${it.count})`;
217
+ }
218
+ out.push(text);
219
+ }
220
+ parts.push(out.join('\n'));
221
+ }
222
+ return parts.join('\n\n');
223
+ }
224
+
225
+ export function formatRange(b) {
226
+ return `L${b.start + 1}-L${b.end + 1}`;
227
+ }
228
+
229
+ export function droppedLine(dropped, maxRanges = 3) {
230
+ const ranges = dropped.slice(0, maxRanges).map(formatRange).join(', ');
231
+ return `… +${dropped.length} more blocks (${ranges}${dropped.length > maxRanges ? ', …' : ''}) — see log`;
232
+ }