lean-ctx-patterns 0.1.1

Deterministic shell-output compression patterns and token counting for LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
// SPDX-License-Identifier: Apache-2.0

use crate::ansi::strip_ansi;

pub fn compress(output: &str) -> Option<String> {
    // node:test first: its `ℹ tests N` / `# tests N` summary is the most
    // specific signal, and its test titles may contain words other parsers
    // key on ("passing", "pytest", "running ").
    if let Some(r) = try_node_test(output) {
        return Some(r);
    }
    if let Some(r) = try_cargo_test(output) {
        return Some(r);
    }
    if let Some(r) = try_pytest(output) {
        return Some(r);
    }
    if let Some(r) = try_vitest(output) {
        return Some(r);
    }
    if let Some(r) = try_jest(output) {
        return Some(r);
    }
    if let Some(r) = try_go_test(output) {
        return Some(r);
    }
    if let Some(r) = try_rspec(output) {
        return Some(r);
    }
    if let Some(r) = try_mocha(output) {
        return Some(r);
    }
    None
}

fn try_cargo_test(output: &str) -> Option<String> {
    if !output.contains("test result:") && !output.contains("running ") {
        return None;
    }
    if !output.contains(" passed") {
        return None;
    }

    let mut total_passed = 0u32;
    let mut total_failed = 0u32;
    let mut total_ignored = 0u32;
    let mut total_filtered = 0u32;
    let mut time = String::new();
    let mut failures: Vec<String> = Vec::new();
    let mut passed_names: Vec<String> = Vec::new();
    let mut suites = 0u32;

    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("test result:") {
            suites += 1;
            for part in trimmed.split(';') {
                let part = part.trim();
                if let Some(n) = extract_cargo_counter(part, "passed") {
                    total_passed += n;
                } else if let Some(n) = extract_cargo_counter(part, "failed") {
                    total_failed += n;
                } else if let Some(n) = extract_cargo_counter(part, "ignored") {
                    total_ignored += n;
                } else if let Some(n) = extract_cargo_counter(part, "filtered out") {
                    total_filtered += n;
                }
            }
            if let Some(pos) = trimmed.find("finished in ") {
                time = trimmed[pos + 12..].trim().to_string();
            }
        }
        if trimmed.starts_with("test ") && trimmed.ends_with("... ok") {
            if let Some(name) = trimmed
                .strip_prefix("test ")
                .and_then(|r| r.strip_suffix(" ... ok"))
            {
                passed_names.push(name.to_string());
            }
        }
        if (trimmed.starts_with("test ") && trimmed.ends_with("... FAILED"))
            || trimmed.starts_with("---- ")
                && trimmed.ends_with(" ----")
                && !trimmed.contains("output")
        {
            let name = if let Some(rest) = trimmed.strip_prefix("test ") {
                rest.strip_suffix(" ... FAILED").unwrap_or(rest)
            } else {
                trimmed.trim_start_matches('-').trim_end_matches('-').trim()
            };
            if !name.is_empty() && !failures.iter().any(|f| f == name) {
                failures.push(name.to_string());
            }
        }
    }

    if total_passed == 0 && total_failed == 0 {
        return None;
    }

    let mut result = format!("cargo test: {total_passed} passed");
    if total_failed > 0 {
        result.push_str(&format!(", {total_failed} failed"));
    }
    if total_ignored > 0 {
        result.push_str(&format!(", {total_ignored} ignored"));
    }
    if total_filtered > 0 {
        result.push_str(&format!(", {total_filtered} filtered"));
    }
    if suites > 1 {
        result.push_str(&format!(" ({suites} suites)"));
    }
    if !time.is_empty() {
        result.push_str(&format!(" [{time}]"));
    }

    for f in failures.iter().take(10) {
        result.push_str(&format!("\n  FAIL: {f}"));
    }

    Some(result)
}

fn extract_cargo_counter(segment: &str, keyword: &str) -> Option<u32> {
    let pos = segment.find(keyword)?;
    let before = segment[..pos].trim();
    let num_str = before.split_whitespace().last()?;
    num_str.parse::<u32>().ok()
}

fn try_pytest(output: &str) -> Option<String> {
    if !output.contains("test session starts") && !output.contains("pytest") {
        return None;
    }

    let mut passed = 0u32;
    let mut failed = 0u32;
    let mut skipped = 0u32;
    let mut xfailed = 0u32;
    let mut xpassed = 0u32;
    let mut warnings = 0u32;
    let mut time = String::new();
    let mut failures = Vec::new();
    let mut passed_names = Vec::new();

    for line in output.lines() {
        let trimmed = line.trim();
        if (trimmed.contains("passed")
            || trimmed.contains("failed")
            || trimmed.contains("error")
            || trimmed.contains("xfailed")
            || trimmed.contains("xpassed")
            || trimmed.contains("warning"))
            && (trimmed.starts_with('=') || trimmed.starts_with('-'))
        {
            for word in trimmed.split_whitespace() {
                if let Some(n) = word.strip_suffix("passed").or_else(|| {
                    if trimmed.contains(" passed") {
                        word.parse::<u32>().ok().map(|_| word)
                    } else {
                        None
                    }
                }) && let Ok(v) = n.trim().parse::<u32>()
                {
                    passed = v;
                }
            }
            passed = extract_pytest_counter(trimmed, " passed").unwrap_or(passed);
            failed = extract_pytest_counter(trimmed, " failed").unwrap_or(failed);
            skipped = extract_pytest_counter(trimmed, " skipped").unwrap_or(skipped);
            xfailed = extract_pytest_counter(trimmed, " xfailed").unwrap_or(xfailed);
            xpassed = extract_pytest_counter(trimmed, " xpassed").unwrap_or(xpassed);
            warnings = extract_pytest_counter(trimmed, " warning").unwrap_or(warnings);
            if let Some(pos) = trimmed.find(" in ") {
                time = trimmed[pos + 4..].trim_end_matches('=').trim().to_string();
            }
        }
        if trimmed.starts_with("FAILED ") {
            failures.push(
                trimmed
                    .strip_prefix("FAILED ")
                    .unwrap_or(trimmed)
                    .to_string(),
            );
        }
        if trimmed.starts_with("PASSED ") || trimmed.ends_with(" PASSED") {
            let name = trimmed
                .strip_prefix("PASSED ")
                .or_else(|| trimmed.strip_suffix(" PASSED"))
                .unwrap_or(trimmed);
            if name.len() <= 50 {
                passed_names.push(name.to_string());
            } else {
                passed_names.push(format!("{}...", &name[..name.floor_char_boundary(47)]));
            }
        }
    }

    if passed == 0 && failed == 0 {
        return None;
    }

    let mut result = format!("pytest: {passed} passed");
    if failed > 0 {
        result.push_str(&format!(", {failed} failed"));
    }
    if skipped > 0 {
        result.push_str(&format!(", {skipped} skipped"));
    }
    if xfailed > 0 {
        result.push_str(&format!(", {xfailed} xfailed"));
    }
    if xpassed > 0 {
        result.push_str(&format!(", {xpassed} xpassed"));
    }
    if warnings > 0 {
        result.push_str(&format!(", {warnings} warnings"));
    }
    if !time.is_empty() {
        result.push_str(&format!(" ({time})"));
    }

    for f in failures.iter().take(5) {
        result.push_str(&format!("\n  FAIL: {f}"));
    }

    if failures.is_empty() && !passed_names.is_empty() {
        let total = passed_names.len();
        let shown: Vec<_> = passed_names.into_iter().take(5).collect();
        let suffix = if total > 5 {
            format!(" ...+{} more", total - 5)
        } else {
            String::new()
        };
        result.push_str(&format!("\n  ran: {}{suffix}", shown.join(", ")));
    }

    Some(result)
}

fn extract_pytest_counter(line: &str, keyword: &str) -> Option<u32> {
    let pos = line.find(keyword)?;
    let before = &line[..pos];
    let num_str = before.split_whitespace().last()?;
    num_str.parse::<u32>().ok()
}

fn try_jest(output: &str) -> Option<String> {
    if !output.contains("Tests:") && !output.contains("Test Suites:") {
        return None;
    }

    let mut suites_line = String::new();
    let mut tests_line = String::new();
    let mut time_line = String::new();

    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("Test Suites:") {
            suites_line = trimmed.to_string();
        } else if trimmed.starts_with("Tests:") {
            tests_line = trimmed.to_string();
        } else if trimmed.starts_with("Time:") {
            time_line = trimmed.to_string();
        }
    }

    if tests_line.is_empty() {
        return None;
    }

    let mut result = String::new();
    if !suites_line.is_empty() {
        result.push_str(&suites_line);
        result.push('\n');
    }
    result.push_str(&tests_line);
    if !time_line.is_empty() {
        result.push('\n');
        result.push_str(&time_line);
    }

    Some(result)
}

fn try_go_test(output: &str) -> Option<String> {
    if !output.contains("--- PASS") && !output.contains("--- FAIL") && !output.contains("PASS\n") {
        return None;
    }

    let mut passed = 0u32;
    let mut failed = 0u32;
    let mut failures = Vec::new();
    let mut passed_names = Vec::new();
    let mut packages = Vec::new();

    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("--- PASS:") {
            passed += 1;
            if let Some(name) = trimmed.strip_prefix("--- PASS: ") {
                let name = name.split_whitespace().next().unwrap_or(name);
                passed_names.push(name.to_string());
            }
        } else if trimmed.starts_with("--- FAIL:") {
            failed += 1;
            failures.push(
                trimmed
                    .strip_prefix("--- FAIL: ")
                    .unwrap_or(trimmed)
                    .to_string(),
            );
        } else if trimmed.starts_with("ok ") || trimmed.starts_with("FAIL\t") {
            packages.push(trimmed.to_string());
        }
    }

    if passed == 0 && failed == 0 {
        return None;
    }

    let mut result = format!("go test: {passed} passed");
    if failed > 0 {
        result.push_str(&format!(", {failed} failed"));
    }

    for pkg in &packages {
        result.push_str(&format!("\n  {pkg}"));
    }

    for f in failures.iter().take(5) {
        result.push_str(&format!("\n  FAIL: {f}"));
    }

    if failures.is_empty() && !passed_names.is_empty() {
        let total = passed_names.len();
        let shown: Vec<_> = passed_names.into_iter().take(5).collect();
        let suffix = if total > 5 {
            format!(" ...+{} more", total - 5)
        } else {
            String::new()
        };
        result.push_str(&format!("\n  ran: {}{suffix}", shown.join(", ")));
    }

    Some(result)
}

fn try_vitest(output: &str) -> Option<String> {
    if !output.contains("PASS") && !output.contains("FAIL") {
        return None;
    }
    if !output.contains(" Tests ") && !output.contains("Test Files") {
        return None;
    }

    let mut test_files_line = String::new();
    let mut tests_line = String::new();
    let mut duration_line = String::new();
    let mut failures = Vec::new();

    for line in output.lines() {
        let trimmed = line.trim();
        let plain = strip_ansi(trimmed);
        if plain.contains("Test Files") {
            test_files_line.clone_from(&plain);
        } else if plain.starts_with("Tests") && plain.contains("passed") {
            tests_line.clone_from(&plain);
        } else if plain.contains("Duration") || plain.contains("Time") {
            if plain.contains("ms") || plain.contains('s') {
                duration_line.clone_from(&plain);
            }
        } else if plain.contains("FAIL")
            && (plain.contains(".test.") || plain.contains(".spec.") || plain.contains("_test."))
        {
            failures.push(plain.clone());
        }
    }

    if tests_line.is_empty() && test_files_line.is_empty() {
        return None;
    }

    let mut result = String::new();
    if !test_files_line.is_empty() {
        result.push_str(&test_files_line);
    }
    if !tests_line.is_empty() {
        if !result.is_empty() {
            result.push('\n');
        }
        result.push_str(&tests_line);
    }
    if !duration_line.is_empty() {
        result.push('\n');
        result.push_str(&duration_line);
    }

    for f in failures.iter().take(10) {
        result.push_str(&format!("\n  FAIL: {f}"));
    }

    Some(result)
}

fn try_rspec(output: &str) -> Option<String> {
    if !output.contains("examples") || !output.contains("failures") {
        return None;
    }

    for line in output.lines().rev() {
        let trimmed = line.trim();
        if trimmed.contains("example") && trimmed.contains("failure") {
            return Some(format!("rspec: {trimmed}"));
        }
    }

    None
}

/// Parses mocha's own summary counter line: `  3 passing (50ms)` or
/// `  1 failing`. Returns `None` for anything else, so test titles or other
/// runners' text containing the words are never read as a mocha summary.
fn mocha_counter(line: &str, keyword: &str) -> Option<(u32, Option<String>)> {
    let trimmed = line.trim();
    let (count, rest) = trimmed.split_once(' ')?;
    if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let n = count.parse::<u32>().ok()?;
    let rest = rest.strip_prefix(keyword)?.trim();
    if rest.is_empty() {
        return Some((n, None));
    }
    let inner = rest.strip_prefix('(')?.strip_suffix(')')?;
    let valid_duration = !inner.is_empty()
        && inner.starts_with(|c: char| c.is_ascii_digit())
        && inner.chars().all(|c| c.is_ascii_alphanumeric() || c == '.');
    valid_duration.then(|| (n, Some(inner.to_string())))
}

fn try_mocha(output: &str) -> Option<String> {
    let mut passing: Option<u32> = None;
    let mut failing: Option<u32> = None;
    let mut duration = String::new();
    let mut failures = Vec::new();
    let mut in_failure = false;

    for line in output.lines() {
        let plain = strip_ansi(line);
        let trimmed = plain.trim();
        if let Some((n, d)) = mocha_counter(trimmed, "passing") {
            passing = Some(n);
            if let Some(d) = d {
                duration = d;
            }
            continue;
        }
        if let Some((n, None)) = mocha_counter(trimmed, "failing") {
            failing = Some(n);
            in_failure = true;
            continue;
        }
        if in_failure
            && trimmed.starts_with(|c: char| c.is_ascii_digit())
            && let Some((num, desc)) = trimmed.split_once(')')
            && num.bytes().all(|b| b.is_ascii_digit())
        {
            failures.push(desc.trim().to_string());
        }
    }

    // Fail closed: without mocha's real summary line, leave the output to
    // generic handling instead of reporting a bogus "0 passed".
    if passing.is_none() && failing.is_none() {
        return None;
    }
    let passing = passing.unwrap_or(0);
    let failing = failing.unwrap_or(0);
    if failing > 0 && failures.is_empty() {
        return None;
    }

    let mut result = format!("mocha: {passing} passed");
    if failing > 0 {
        result.push_str(&format!(", {failing} failed"));
    }
    if !duration.is_empty() {
        result.push_str(&format!(" ({duration})"));
    }

    for f in failures.iter().take(10) {
        result.push_str(&format!("\n  FAIL: {f}"));
    }

    Some(result)
}

#[derive(Default)]
struct NodeTestCounts {
    tests: Option<u32>,
    suites: Option<u32>,
    pass: Option<u32>,
    fail: Option<u32>,
    cancelled: Option<u32>,
    skipped: Option<u32>,
    todo: Option<u32>,
    duration_ms: Option<String>,
}

impl NodeTestCounts {
    /// Records one summary line body (`tests 40`, `duration_ms 52.1`).
    fn record(&mut self, body: &str) {
        let Some((key, value)) = body.trim().split_once(' ') else {
            return;
        };
        let value = value.trim();
        if key == "duration_ms" {
            if !value.is_empty() && value.chars().all(|c| c.is_ascii_digit() || c == '.') {
                self.duration_ms = Some(value.to_string());
            }
            return;
        }
        let Ok(n) = value.parse::<u32>() else {
            return;
        };
        let slot = match key {
            "tests" => &mut self.tests,
            "suites" => &mut self.suites,
            "pass" => &mut self.pass,
            "fail" => &mut self.fail,
            "cancelled" => &mut self.cancelled,
            "skipped" => &mut self.skipped,
            "todo" => &mut self.todo,
            _ => return,
        };
        *slot = Some(n);
    }
}

fn indent_of(line: &str) -> usize {
    line.len() - line.trim_start().len()
}

/// node's built-in test runner (`node --test`), spec reporter (`ℹ tests N`)
/// or TAP reporter (`# tests N`). Failed or cancelled runs keep the full
/// failure details; without them the parser fails closed.
fn try_node_test(output: &str) -> Option<String> {
    if !output.contains("tests ") || !output.contains("pass ") {
        return None;
    }

    let lines: Vec<String> = output.lines().map(strip_ansi).collect();
    let mut spec = NodeTestCounts::default();
    let mut tap = NodeTestCounts::default();
    let mut failing_block_start: Option<usize> = None;

    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if let Some(body) = trimmed.strip_prefix('ℹ') {
            spec.record(body);
        } else if let Some(body) = trimmed.strip_prefix("# ") {
            tap.record(body);
        } else if trimmed == "✖ failing tests:" {
            failing_block_start = Some(i);
        }
    }

    let is_complete =
        |c: &NodeTestCounts| c.tests.is_some() && c.pass.is_some() && c.fail.is_some();
    let (label, counts) = if is_complete(&spec) {
        ("node:test", spec)
    } else if is_complete(&tap) {
        ("node:test (tap)", tap)
    } else {
        return None;
    };

    let tests = counts.tests.unwrap_or(0);
    let pass = counts.pass.unwrap_or(0);
    let fail = counts.fail.unwrap_or(0);
    let cancelled = counts.cancelled.unwrap_or(0);

    let mut result = format!("{label}: {pass} passed");
    if fail > 0 {
        result.push_str(&format!(", {fail} failed"));
    }
    if cancelled > 0 {
        result.push_str(&format!(", {cancelled} cancelled"));
    }
    if let Some(n) = counts.skipped.filter(|n| *n > 0) {
        result.push_str(&format!(", {n} skipped"));
    }
    if let Some(n) = counts.todo.filter(|n| *n > 0) {
        result.push_str(&format!(", {n} todo"));
    }
    result.push_str(&format!(" ({tests} tests"));
    if let Some(n) = counts.suites.filter(|n| *n > 0) {
        result.push_str(&format!(", {n} suites"));
    }
    result.push(')');
    if let Some(d) = &counts.duration_ms {
        result.push_str(&format!(" [{d}ms]"));
    }

    if fail == 0 && cancelled == 0 {
        return Some(result);
    }

    // Never hide failures: keep the details verbatim or do not summarize.
    let mut details: Vec<&str> = Vec::new();
    if label == "node:test" {
        let start = failing_block_start?;
        details.extend(lines[start..].iter().map(String::as_str));
        while details.last().is_some_and(|l| l.trim().is_empty()) {
            details.pop();
        }
    } else {
        let mut i = 0;
        while i < lines.len() {
            let line = &lines[i];
            if line.trim_start().starts_with("not ok ") {
                let indent = indent_of(line);
                details.push(line);
                i += 1;
                while i < lines.len()
                    && (lines[i].trim().is_empty() || indent_of(&lines[i]) > indent)
                    && !lines[i].trim_start().starts_with("not ok ")
                {
                    if !lines[i].trim().is_empty() {
                        details.push(&lines[i]);
                    }
                    i += 1;
                }
                continue;
            }
            i += 1;
        }
    }
    if details.is_empty() {
        return None;
    }
    for d in details {
        result.push('\n');
        result.push_str(d);
    }
    Some(result)
}

#[cfg(test)]
mod mocha_tests {
    use super::*;

    #[test]
    fn mocha_passing_only() {
        let output = "  3 passing (50ms)";
        let result = try_mocha(output).expect("should match");
        assert!(result.contains("3 passed"));
        assert!(result.contains("50ms"));
    }

    #[test]
    fn mocha_with_failures() {
        let output =
            "  2 passing (100ms)\n  1 failing\n\n  1) Array #indexOf():\n     Error: expected -1";
        let result = try_mocha(output).expect("should match");
        assert!(result.contains("2 passed"));
        assert!(result.contains("1 failed"));
        assert!(result.contains("FAIL:"));
    }
}

#[cfg(test)]
mod node_test_tests {
    use super::*;

    /// Spec reporter output of the #2294 reproduction: 40 cases, case 7 fails.
    fn issue_2294_failing_output() -> String {
        let mut out = String::from("\n> demo@1.0.0 test\n> node --test\n\n");
        for i in 1..=40 {
            if i == 7 {
                out.push_str("✖ case 7 returns the expected value (0.912ms)\n");
                out.push_str(
                    "  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:\n\n    assert.ok(i !== 7)\n\n      at TestContext.<anonymous> (/work/demo/a.test.js:3:83)\n      at Test.runInAsyncScope (node:async_hooks:214:14)\n      at Test.run (node:internal/test_runner/test:1047:25) {\n    generatedMessage: true,\n    code: 'ERR_ASSERTION',\n    actual: false,\n    expected: true,\n    operator: '=='\n  }\n\n",
                );
            } else {
                out.push_str(&format!(
                    "✔ case {i} returns the expected value (0.1{i}ms)\n"
                ));
            }
        }
        out.push_str(
            "ℹ tests 40\nℹ suites 0\nℹ pass 39\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 61.204\n\n",
        );
        out.push_str(
            "✖ failing tests:\n\ntest at a.test.js:3:44\n✖ case 7 returns the expected value (0.912ms)\n  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:\n\n    assert.ok(i !== 7)\n\n      at TestContext.<anonymous> (/work/demo/a.test.js:3:83)\n  {\n    generatedMessage: true,\n    code: 'ERR_ASSERTION',\n    actual: false,\n    expected: true,\n    operator: '=='\n  }\n",
        );
        out
    }

    #[test]
    fn node_test_issue_2294_failure_kept() {
        let output = issue_2294_failing_output();
        assert!(
            try_mocha(&output).is_none(),
            "node:test must not be claimed as mocha"
        );
        let result = compress(&output).expect("node:test summary");
        assert!(
            result.starts_with("node:test: 39 passed, 1 failed (40 tests) [61.204ms]"),
            "{result}"
        );
        assert!(result.contains("✖ failing tests:"), "{result}");
        assert!(
            result.contains("✖ case 7 returns the expected value"),
            "{result}"
        );
        assert!(result.contains("assert.ok(i !== 7)"), "{result}");
        assert!(result.contains("operator: '=='"), "{result}");
        assert!(!result.contains("mocha"), "{result}");
        assert!(result.len() < output.len());
    }

    #[test]
    fn node_test_title_with_passing_word_not_mocha() {
        let output = "✔ shows 3 passing checks (0.2ms)\n✔ reports failing tests clearly (0.1ms)\nℹ tests 2\nℹ suites 0\nℹ pass 2\nℹ fail 0\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 40.5\n";
        assert!(try_mocha(output).is_none());
        let result = compress(output).expect("node:test summary");
        assert_eq!(result, "node:test: 2 passed (2 tests) [40.5ms]");
    }

    #[test]
    fn node_test_passing_run_summarized() {
        let mut output = String::new();
        output.push_str("▶ math\n");
        for i in 1..=12 {
            output.push_str(&format!("  ✔ adds case {i} (0.0{i}ms)\n"));
        }
        output.push_str("✔ math (2.1ms)\n﹣ later feature (0.05ms) # SKIP\n");
        output.push_str("ℹ tests 13\nℹ suites 1\nℹ pass 12\nℹ fail 0\nℹ cancelled 0\nℹ skipped 1\nℹ todo 0\nℹ duration_ms 75.3\n");
        let result = compress(&output).expect("node:test summary");
        assert_eq!(
            result,
            "node:test: 12 passed, 1 skipped (13 tests, 1 suites) [75.3ms]"
        );
    }

    #[test]
    fn node_test_failure_without_details_fails_closed() {
        // `tail` cut before the failing-tests block: do not summarize.
        let output = "ℹ tests 3\nℹ suites 0\nℹ pass 2\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 9.1\n";
        assert!(try_node_test(output).is_none());
        assert!(compress(output).is_none());
    }

    #[test]
    fn node_test_tap_reporter_keeps_not_ok() {
        let output = "TAP version 13\n# Subtest: adds\nok 1 - adds\n  ---\n  duration_ms: 0.4\n  ...\n# Subtest: subtracts\nnot ok 2 - subtracts\n  ---\n  duration_ms: 0.7\n  location: '/work/demo/a.test.js:5:1'\n  failureType: 'testCodeFailure'\n  error: 'Expected values to be strictly equal:\\n\\n1 !== 2\\n'\n  code: 'ERR_ASSERTION'\n  ...\n1..2\n# tests 2\n# suites 0\n# pass 1\n# fail 1\n# cancelled 0\n# skipped 0\n# todo 0\n# duration_ms 50.2\n";
        let result = compress(output).expect("tap summary");
        assert!(
            result.starts_with("node:test (tap): 1 passed, 1 failed (2 tests) [50.2ms]"),
            "{result}"
        );
        assert!(result.contains("not ok 2 - subtracts"), "{result}");
        assert!(result.contains("1 !== 2"), "{result}");
        assert!(!result.contains("ok 1 - adds"), "{result}");
    }

    #[test]
    fn real_mocha_output_still_parsed() {
        let output = "\n  Array\n    #indexOf()\n      ✔ should return -1 when the value is not present\n      1) should return the index when present\n\n\n  1 passing (9ms)\n  1 failing\n\n  1) Array\n       #indexOf()\n         should return the index when present:\n\n      AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n-1 !== 0\n\n      at Context.<anonymous> (test/array.spec.js:9:14)\n";
        assert!(try_node_test(output).is_none());
        let result = compress(output).expect("mocha summary");
        assert!(
            result.starts_with("mocha: 1 passed, 1 failed (9ms)"),
            "{result}"
        );
        assert!(result.contains("FAIL: Array"), "{result}");
    }

    #[test]
    fn passing_word_in_prose_not_mocha() {
        let output = "all checks passing now\nnothing failing here\n";
        assert!(try_mocha(output).is_none());
        assert!(compress(output).is_none());
    }
}

#[cfg(test)]
mod cargo_tests {
    use super::*;

    #[test]
    fn cargo_test_all_passing() {
        let output = "\
   Compiling lean-ctx v3.9.11 (/Users/test/rust)
     Running unittests src/lib.rs (target/debug/deps/lean_ctx-abc123)

running 245 tests
test core::tokens::tests::count_empty ... ok
test core::tokens::tests::count_hello ... ok
test core::config::tests::default_config ... ok
test result: ok. 245 passed; 0 failed; 3 ignored; 0 measured; 0 filtered out; finished in 4.23s

     Running tests/integration.rs (target/debug/deps/integration-def456)

running 12 tests
test api_read ... ok
test api_search ... ok
test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.10s";

        let result = try_cargo_test(output).expect("should match");
        assert!(result.contains("257 passed"));
        assert!(result.contains("3 ignored"));
        assert!(result.contains("2 suites"));
        assert!(!result.contains("FAIL"));
    }

    #[test]
    fn cargo_test_with_failures() {
        let output = "\
running 50 tests
test core::foo ... ok
test core::bar ... FAILED
test result: ok. 49 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.0s";

        let result = try_cargo_test(output).expect("should match");
        assert!(result.contains("49 passed"));
        assert!(result.contains("1 failed"));
        assert!(result.contains("FAIL: core::bar"));
    }

    #[test]
    fn cargo_test_single_suite() {
        let output = "\
running 10 tests
test a ... ok
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.5s";

        let result = try_cargo_test(output).expect("should match");
        assert!(result.contains("10 passed"));
        assert!(!result.contains("suites"));
    }

    #[test]
    fn non_cargo_output_rejected() {
        let output = "hello world\nfoo bar";
        assert!(try_cargo_test(output).is_none());
    }
}