Skip to main content

aft_base/compress/
bun.rs

1use crate::compress::caps::{cap_classified_blocks, ClassifiedBlock, DropClass};
2use crate::compress::generic::GenericCompressor;
3use crate::compress::{CompressionResult, Compressor, Specificity};
4
5pub struct BunCompressor;
6
7impl Compressor for BunCompressor {
8    fn specificity(&self) -> Specificity {
9        Specificity::PackageManager
10    }
11
12    fn matches(&self, command: &str) -> bool {
13        command
14            .split_whitespace()
15            .next()
16            .is_some_and(|head| head == "bun")
17    }
18
19    fn compress_with_exit_code(
20        &self,
21        command: &str,
22        output: &str,
23        exit_code: Option<i64>,
24    ) -> CompressionResult {
25        match bun_subcommand(command).as_deref() {
26            Some("install" | "i" | "add" | "remove") => compress_package(output).into(),
27            Some("test") => preserve_bun_failure(output, compress_test(output), exit_code),
28            Some("build") => compress_build(output),
29            _ => GenericCompressor::compress_output(output).into(),
30        }
31    }
32
33    fn matches_output(&self, output: &str) -> bool {
34        let mut saw_ran_summary = false;
35        let mut saw_result_marker = false;
36
37        for line in output.lines() {
38            saw_ran_summary |= is_ran_summary_line(line);
39            saw_result_marker |= is_bun_test_result_marker(line);
40
41            if saw_ran_summary && saw_result_marker {
42                return true;
43            }
44        }
45
46        false
47    }
48
49    fn compress_output_match_with_exit_code(
50        &self,
51        output: &str,
52        exit_code: Option<i64>,
53    ) -> CompressionResult {
54        preserve_bun_failure(output, compress_test(output), exit_code)
55    }
56}
57
58fn preserve_bun_failure(
59    output: &str,
60    compressed: CompressionResult,
61    exit_code: Option<i64>,
62) -> CompressionResult {
63    let stripped_failure =
64        compressed.text.trim().is_empty() || !super::text_has_failure_signal(&compressed.text);
65    if !output.trim().is_empty()
66        && stripped_failure
67        && (matches!(exit_code, Some(code) if code != 0) || super::text_has_failure_signal(output))
68    {
69        GenericCompressor::compress_output(output).into()
70    } else {
71        compressed
72    }
73}
74
75/// Known bun subcommands we want to match on. Used by `bun_subcommand`
76/// to safely skip over flag values like `--cwd <dir>` that would
77/// otherwise be misread as the subcommand. Listing only the
78/// subcommands the compressor actually dispatches on plus the most
79/// common bun verbs keeps the set small without missing real cases.
80///
81/// Full bun verb set (per `bun --help`): install, add, remove, update,
82/// outdated, link, unlink, why, audit, patch, pm, publish, pack, run,
83/// test, x, exec, create, init, build, repl, upgrade.
84const BUN_SUBCOMMANDS: &[&str] = &[
85    "install", "i", "add", "remove", "update", "outdated", "link", "unlink", "why", "audit",
86    "patch", "pm", "publish", "pack", "run", "test", "x", "exec", "create", "init", "build",
87    "repl", "upgrade", "help", "info",
88];
89
90/// Detect the bun subcommand from a command line.
91///
92/// Important: previous implementations used `find(!starts_with('-'))`
93/// which broke for `bun --cwd packages/opencode-plugin test` — the
94/// flag's value (`packages/opencode-plugin`) was returned as the
95/// subcommand, causing the bun-test compressor to silently fall
96/// through to the generic compressor and drop per-test failure
97/// blocks. We now match against a whitelist of known bun verbs so
98/// flag values are skipped safely.
99fn bun_subcommand(command: &str) -> Option<String> {
100    command
101        .split_whitespace()
102        .skip_while(|token| *token != "bun")
103        .skip(1)
104        .find(|token| BUN_SUBCOMMANDS.contains(token))
105        .map(ToString::to_string)
106}
107
108fn compress_package(output: &str) -> String {
109    let mut result = Vec::new();
110    let mut last_content_line = None;
111    for line in output.lines() {
112        if is_bun_progress(line) {
113            continue;
114        }
115        let trimmed = line.trim_start();
116        if !trimmed.is_empty() {
117            last_content_line = Some(line);
118        }
119        if trimmed.contains("packages installed")
120            || trimmed.contains("package installed")
121            || is_bun_install_summary(trimmed)
122            || trimmed.starts_with("error:")
123            || trimmed.starts_with("warn:")
124            || trimmed.starts_with("bun install error:")
125            || trimmed.starts_with("Saved lockfile")
126        {
127            result.push(line.to_string());
128        }
129    }
130    // Never reduce a non-empty install to nothing: whatever bun printed last
131    // is its verdict, and an empty reply hides whether the install ran at all.
132    if result.is_empty() {
133        if let Some(line) = last_content_line {
134            result.push(line.to_string());
135        }
136    }
137    trim_trailing_lines(&result.join("\n"))
138}
139
140/// Bun's closing summary when an install had nothing to add, e.g.
141/// `Checked 437 installs across 463 packages (no changes) [18.00ms]`.
142fn is_bun_install_summary(trimmed: &str) -> bool {
143    trimmed.starts_with("Checked ") && trimmed.contains(" installs across ")
144}
145
146fn compress_build(output: &str) -> CompressionResult {
147    let mut blocks = Vec::new();
148    for line in output.lines() {
149        if is_timing_line(line) {
150            blocks.push(ClassifiedBlock::new(DropClass::Timing, line.to_string()));
151        } else {
152            blocks.push(ClassifiedBlock::unclassified(line.to_string()));
153        }
154    }
155    let capped = cap_classified_blocks(blocks);
156    CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
157}
158
159/// Compress `bun test` output. Preserves:
160///   - Bun version header (`bun test v1.3.14 ...`)
161///   - File-section headers (`path/to/foo.test.ts:`) that precede a kept failure
162///   - All failure context: `error:` block + diff + source pointer (`  N |`)
163///     + stack frames + the explicit `(fail) test name [Xms]` marker
164///   - Final summary lines: ` N pass`, ` N fail`, ` N expect() calls`, and
165///     `Ran N tests across N files. [Xms]`
166///
167/// Drops:
168///   - `(pass) test name [Xms]` markers (the summary's `N pass` line
169///     already conveys count) — but if no failures exist, returns the
170///     full original output via the generic compressor for safety
171///
172/// Failure blocks are class-capped by the shared semantic cap helper; the
173/// registry emits the single visible omission marker.
174///
175/// Why this matters: bun test writes failure blocks INLINE between the
176/// header and the final summary. With the 30KB inline cap, large test
177/// runs middle-truncate and lose the failure block entirely — agents
178/// see only the header + summary count and have no debugging context.
179fn compress_test(output: &str) -> CompressionResult {
180    let lines: Vec<&str> = output.lines().collect();
181    if lines.is_empty() {
182        return CompressionResult::new(output.to_string());
183    }
184
185    // Quick pre-scan: if no failures, defer to generic. This keeps the
186    // pass-only path cheap and avoids touching outputs that don't have
187    // the truncation problem (small all-pass runs are already short).
188    let has_failures = lines.iter().any(|line| is_bun_test_fail_marker(line));
189    if !has_failures {
190        return CompressionResult::new(compress_test_pass_only(&lines));
191    }
192
193    let mut blocks: Vec<ClassifiedBlock> = Vec::new();
194    let mut index = 0usize;
195    let mut saw_ran_summary = false;
196    let mut pending_section: Option<String> = None;
197
198    while index < lines.len() {
199        let line = lines[index];
200
201        if saw_ran_summary {
202            // Past the `Ran N tests across M files. [Xms]` line, output
203            // belongs to a chained command (`; next_cmd`). Pass through
204            // so chains don't silently lose the next command's output.
205            // (Note: `&&` short-circuits on test failure so this is mainly
206            // relevant for `;` separators or `|| fallback_cmd`.)
207            blocks.push(ClassifiedBlock::unclassified(line.to_string()));
208            index += 1;
209            continue;
210        }
211
212        // Bun version header — keep, minus the noisy version + commit hash.
213        if is_bun_test_header(line) {
214            blocks.push(ClassifiedBlock::unclassified(render_bun_header(line)));
215            index += 1;
216            continue;
217        }
218
219        // File-section header (e.g. `src/foo.test.ts:`). Only keep if
220        // a failure block follows before the next file-section header
221        // or summary.
222        if is_file_section_header(line) {
223            let next_fail = next_index(&lines, index + 1, is_bun_test_fail_marker);
224            let next_section = next_index(&lines, index + 1, |l| {
225                is_file_section_header(l) || is_summary_line(l)
226            });
227            let keep_section = match (next_fail, next_section) {
228                (Some(fi), Some(si)) => fi < si,
229                (Some(_), None) => true,
230                (None, _) => false,
231            };
232            if keep_section {
233                pending_section = Some(line.to_string());
234            }
235            index += 1;
236            continue;
237        }
238
239        // Summary tail — always keep (Ran line minus its [Xms] duration).
240        if is_summary_line(line) {
241            blocks.push(ClassifiedBlock::unclassified(render_summary_line(line)));
242            // The `Ran N tests across M files. [Xms]` line marks the
243            // boundary between bun-test output and any chained-command
244            // output that follows. (Bun uses `file. [` singular when
245            // M == 1 and `files. [` plural otherwise.)
246            if is_ran_summary_line(line) {
247                saw_ran_summary = true;
248            }
249            index += 1;
250            continue;
251        }
252
253        // Failure block: source pointers, error messages, diff lines,
254        // stack frames, and the explicit `(fail) ...` marker.
255        // Detect block start: an `error:` line, or a code-pointer block
256        // (` N | ...`) that leads into an error.
257        if is_bun_test_error_start(line) || is_bun_test_code_pointer(line) {
258            // Collect lines up to and including the next `(fail) ...`
259            // marker. We rely on the `(fail)` marker as the right edge
260            // because bun always emits one per failed test after the
261            // diagnostic block.
262            let block_start = index;
263            let mut block_end = index;
264            while block_end < lines.len() {
265                if is_bun_test_fail_marker(lines[block_end]) {
266                    block_end += 1;
267                    break;
268                }
269                // Stop early if we hit something that clearly isn't
270                // part of a failure block — but be permissive: source
271                // pointers, error text, stack frames, blank lines all
272                // count as block content.
273                block_end += 1;
274            }
275
276            let mut block_lines = Vec::new();
277            if let Some(section) = pending_section.take() {
278                block_lines.push(section);
279            }
280            block_lines.extend(
281                lines[block_start..block_end]
282                    .iter()
283                    .map(|line| (*line).to_string()),
284            );
285            blocks.push(ClassifiedBlock::new(
286                DropClass::Failure,
287                block_lines.join("\n"),
288            ));
289            index = block_end;
290            continue;
291        }
292
293        // Drop everything else (individual pass lines, blank padding).
294        index += 1;
295    }
296
297    // Safety net: if we somehow stripped everything, fall back so the
298    // agent at least sees the raw bytes truncated by the generic path.
299    if blocks.is_empty() {
300        return GenericCompressor::compress_output(output).into();
301    }
302    let capped = cap_classified_blocks(blocks);
303    CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
304}
305
306/// All-pass `bun test` output: keep version header + summary + drop the
307/// rest. Bun in default mode doesn't print per-test pass markers, but
308/// `--verbose` does, so we explicitly preserve only header + summary.
309///
310/// IMPORTANT: when `bun test` is part of a shell chain like
311/// `bun test && bun run build`, anything AFTER the
312/// `Ran N tests across M files. [Xms]` line is the chained command's
313/// output. We preserve those trailing lines unchanged so chains don't
314/// silently lose the next command's output. The chained command itself
315/// is generic content from our perspective (we have no signal about
316/// what it is from the bun-test compressor's POV) so we pass it through
317/// verbatim and let the inline cap handle excess size.
318fn compress_test_pass_only(lines: &[&str]) -> String {
319    let mut result: Vec<String> = Vec::new();
320    let mut saw_ran_summary = false;
321
322    for line in lines {
323        if saw_ran_summary {
324            // Everything from here on is chained-command output. Pass through.
325            result.push((*line).to_string());
326            continue;
327        }
328        if is_bun_test_header(line) {
329            result.push(render_bun_header(line));
330        } else if is_summary_line(line) {
331            result.push(render_summary_line(line));
332            // The `Ran N tests across M files. [Xms]` line is the LAST line
333            // bun emits for the test run itself. Everything after must be
334            // from a chained command (`&& other_cmd`).
335            if is_ran_summary_line(line) {
336                saw_ran_summary = true;
337            }
338        }
339    }
340
341    if result.is_empty() {
342        return GenericCompressor::compress_output(&lines.join("\n"));
343    }
344    trim_trailing_lines(&result.join("\n"))
345}
346
347fn next_index<F>(lines: &[&str], start: usize, predicate: F) -> Option<usize>
348where
349    F: Fn(&str) -> bool,
350{
351    lines
352        .iter()
353        .enumerate()
354        .skip(start)
355        .find(|(_, line)| predicate(line))
356        .map(|(i, _)| i)
357}
358
359fn is_bun_test_header(line: &str) -> bool {
360    line.starts_with("bun test v")
361}
362
363/// Render the bun banner without the noisy version + commit hash:
364/// `bun test v1.3.14 (0d9b296a)` -> `bun test`. The version/hash is pure
365/// per-call token tax with no agent value.
366fn render_bun_header(line: &str) -> String {
367    match line.find(" v") {
368        Some(idx) => line[..idx].to_string(),
369        None => line.to_string(),
370    }
371}
372
373/// Strip the trailing ` [Xms]` wall-clock duration from the
374/// `Ran N tests across M files. [Xms]` line — noise for the common case and
375/// recoverable via `compressed:false`. Other summary lines (`N pass` etc.) and
376/// non-Ran lines pass through unchanged.
377fn render_summary_line(line: &str) -> String {
378    if is_ran_summary_line(line.trim_start()) {
379        if let Some(idx) = line.rfind(" [") {
380            return line[..idx].to_string();
381        }
382    }
383    line.to_string()
384}
385
386fn is_file_section_header(line: &str) -> bool {
387    // File-section headers from bun look like `path/to/foo.test.ts:`
388    // (no leading whitespace, no spaces in the path part, trailing
389    // colon, contains `.test.` or `.spec.` to avoid false-positives on
390    // error-message colons).
391    let trimmed = line.trim_end();
392    if trimmed.starts_with(' ') || !trimmed.ends_with(':') {
393        return false;
394    }
395    let path = &trimmed[..trimmed.len() - 1];
396    if path.is_empty() || path.contains(' ') {
397        return false;
398    }
399    path.contains(".test.")
400        || path.contains(".spec.")
401        || path.contains("_test.")
402        || path.contains("_spec.")
403}
404
405fn is_bun_test_result_marker(line: &str) -> bool {
406    is_bun_test_pass_marker(line) || is_bun_test_fail_marker(line)
407}
408
409fn is_bun_test_pass_marker(line: &str) -> bool {
410    is_bun_test_marker(line, "(pass)")
411}
412
413fn is_bun_test_fail_marker(line: &str) -> bool {
414    is_bun_test_marker(line, "(fail)")
415}
416
417fn is_bun_test_marker(line: &str, marker: &str) -> bool {
418    let trimmed = line.trim();
419    let Some(rest) = trimmed.strip_prefix(marker) else {
420        return false;
421    };
422    if !rest.chars().next().is_some_and(|ch| ch.is_whitespace()) {
423        return false;
424    }
425
426    let name_and_timing = rest.trim_start();
427    let Some((name, timing)) = name_and_timing.rsplit_once(" [") else {
428        return false;
429    };
430    if name.trim().is_empty() {
431        return false;
432    }
433
434    let Some(duration) = timing.strip_suffix(']') else {
435        return false;
436    };
437    is_bun_test_duration(duration)
438}
439
440fn is_bun_test_duration(duration: &str) -> bool {
441    ["ms", "µs", "μs", "us", "ns", "s"]
442        .iter()
443        .any(|unit| duration.strip_suffix(*unit).is_some_and(is_decimal_number))
444}
445
446fn is_decimal_number(value: &str) -> bool {
447    let mut saw_digit = false;
448    let mut saw_dot = false;
449
450    for ch in value.chars() {
451        match ch {
452            '0'..='9' => saw_digit = true,
453            '.' if !saw_dot => saw_dot = true,
454            _ => return false,
455        }
456    }
457
458    saw_digit
459}
460
461fn is_bun_test_error_start(line: &str) -> bool {
462    // Bun emits the failing assertion as `error: expect(...)` (and
463    // sometimes plain `error: ...`). Source pointers preceding this
464    // also need to be kept, but they get caught by the code-pointer
465    // detector — this is the block's primary anchor.
466    line.starts_with("error:")
467}
468
469fn is_bun_test_code_pointer(line: &str) -> bool {
470    // Bun prints the failing line of source code with format `<N> | ...`
471    // where <N> is the line number (with leading space to align).
472    // These appear immediately above and below the `error:` line.
473    let trimmed = line.trim_start();
474    if !trimmed.contains(" | ") && !trimmed.contains("| ") {
475        return false;
476    }
477    // Confirm it starts with a digit (line number).
478    trimmed
479        .chars()
480        .next()
481        .is_some_and(|char| char.is_ascii_digit())
482}
483
484/// Detects the `Ran N tests across M files. [Xms]` final line that bun
485/// emits to mark the end of its own output. Accepts both the singular
486/// (`file. [`) and plural (`files. [`) forms.
487fn is_ran_summary_line(line: &str) -> bool {
488    let Some(rest) = line.strip_prefix("Ran ") else {
489        return false;
490    };
491    let Some((test_count, rest)) = rest.split_once(" tests across ") else {
492        return false;
493    };
494    if test_count.is_empty() || !test_count.chars().all(|ch| ch.is_ascii_digit()) {
495        return false;
496    }
497    let Some((file_count, rest)) = rest.split_once(" file") else {
498        return false;
499    };
500    if file_count.is_empty() || !file_count.chars().all(|ch| ch.is_ascii_digit()) {
501        return false;
502    }
503    rest.starts_with(". [") || rest.starts_with("s. [")
504}
505
506fn is_summary_line(line: &str) -> bool {
507    let trimmed = line.trim_start();
508    // Summary lines come after `[N]ms` markers in counts. Catch:
509    //   " N pass", " N fail", " N expect() calls"
510    //   "Ran N tests across N files. [Xms]"
511    if is_ran_summary_line(trimmed) {
512        return true;
513    }
514    if let Some(first_token) = trimmed.split_whitespace().next() {
515        if first_token.chars().all(|char| char.is_ascii_digit()) {
516            let rest = trimmed[first_token.len()..].trim_start();
517            return rest.starts_with("pass")
518                || rest.starts_with("fail")
519                || rest.starts_with("expect()");
520        }
521    }
522    false
523}
524
525fn is_bun_progress(line: &str) -> bool {
526    let trimmed = line.trim();
527    trimmed == "."
528        || trimmed.chars().all(|char| char == '.')
529        || trimmed.starts_with("Resolving")
530        || trimmed.starts_with("Resolved")
531        || trimmed.starts_with("Downloaded")
532        || trimmed.starts_with("Extracted")
533}
534
535fn is_timing_line(line: &str) -> bool {
536    let trimmed = line.trim_start();
537    trimmed.starts_with('[') && trimmed.contains(" ms]")
538}
539
540fn trim_trailing_lines(input: &str) -> String {
541    input
542        .lines()
543        .map(str::trim_end)
544        .collect::<Vec<_>>()
545        .join("\n")
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551
552    #[test]
553    fn bun_test_compile_error_falls_back_when_exit_is_unknown() {
554        let output = "bun test v1.3.14 (0d9b296a)\n\nerror: Cannot find module './missing' from 'src/app.test.ts'\n\nRan 0 tests across 1 file. [12.00ms]\n";
555
556        let compressed = BunCompressor.compress("bun test", output);
557
558        assert!(compressed.text.contains("Cannot find module"));
559        assert!(compressed.text.contains("Ran 0 tests"));
560        assert_ne!(compressed.text, "bun test\nRan 0 tests across 1 file.");
561    }
562
563    #[test]
564    fn bun_install_with_no_changes_keeps_its_summary() {
565        let output = "bun install v1.4.2 (744846f84)\n\nChecked 437 installs across 463 packages (no changes) [18.00ms]\n";
566
567        let compressed = BunCompressor.compress("bun install --frozen-lockfile", output);
568
569        assert_eq!(
570            compressed.text,
571            "Checked 437 installs across 463 packages (no changes) [18.00ms]"
572        );
573    }
574
575    #[test]
576    fn bun_install_keeps_warnings_and_never_returns_empty() {
577        let output = "bun install v1.4.2 (744846f84)\nwarn: incorrect peer dependency \"typebox@1.1.38\"\n\n+ typebox@1.1.38\n\n1 package installed [120.00ms]\n";
578        let compressed = BunCompressor.compress("bun install", output);
579        assert_eq!(
580            compressed.text,
581            "warn: incorrect peer dependency \"typebox@1.1.38\"\n1 package installed [120.00ms]"
582        );
583
584        // An unfamiliar closing line is still shown rather than dropped.
585        let unfamiliar = "bun install v9.9.9\n\nDone in 4 steps\n";
586        let compressed = BunCompressor.compress("bun install", unfamiliar);
587        assert_eq!(compressed.text, "Done in 4 steps");
588    }
589}