aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
use crate::compress::caps::{cap_classified_blocks, ClassifiedBlock, DropClass};
use crate::compress::generic::GenericCompressor;
use crate::compress::line_cut::ensure_final_lines;
use crate::compress::{CompressionResult, Compressor};

pub struct CargoCompressor;

impl Compressor for CargoCompressor {
    fn matches(&self, command: &str) -> bool {
        command
            .split_whitespace()
            .next()
            .is_some_and(|head| head == "cargo")
    }

    fn compress_with_exit_code(
        &self,
        command: &str,
        output: &str,
        exit_code: Option<i64>,
    ) -> CompressionResult {
        if let Some(raw) = short_output_passthrough(output) {
            return raw;
        }
        match cargo_subcommand(command).as_deref() {
            Some("build" | "check" | "clippy") => compress_build_like(output),
            Some("test") => compress_test(output, exit_code),
            _ => GenericCompressor::compress_output(output).into(),
        }
    }

    fn matches_output(&self, output: &str) -> bool {
        output.lines().any(is_cargo_test_signature_line)
    }

    fn compress_output_match_with_exit_code(
        &self,
        output: &str,
        exit_code: Option<i64>,
    ) -> CompressionResult {
        if let Some(raw) = short_output_passthrough(output) {
            return raw;
        }
        compress_test(output, exit_code)
    }
}

/// Output this short goes back exactly as the command printed it. A summary
/// saves almost nothing at this size, and every line it leaves out is one the
/// reader may need. 1 KiB is the size below which `git status` output is
/// already passed through raw (`git::STATUS_SHORT_LIMIT`), and the byte window
/// `line_cut::ensure_final_lines` keeps verbatim at the end of any output.
const SHORT_OUTPUT_BYTES: usize = 1024;

fn short_output_passthrough(output: &str) -> Option<CompressionResult> {
    (output.len() <= SHORT_OUTPUT_BYTES).then(|| CompressionResult::new(output.to_string()))
}

fn is_cargo_test_signature_line(line: &str) -> bool {
    line.starts_with("test result:")
        || line.starts_with("failures:")
        || (line.starts_with("---- ") && line.ends_with(" stdout ----"))
}

fn cargo_subcommand(command: &str) -> Option<String> {
    let mut tokens = command.split_whitespace();
    while let Some(token) = tokens.next() {
        if token == "cargo" {
            break;
        }
    }
    while let Some(token) = tokens.next() {
        if crate::compress::is_shell_boundary(token) {
            return None;
        }
        if matches!(
            token,
            "-Z" | "--config"
                | "--color"
                | "--manifest-path"
                | "--target-dir"
                | "--lockfile-path"
                | "-C"
        ) {
            if tokens.next().is_none_or(crate::compress::is_shell_boundary) {
                return None;
            }
        } else if !token.starts_with('-') && !token.starts_with('+') {
            return Some(token.to_string());
        }
    }
    None
}

fn compress_build_like(output: &str) -> CompressionResult {
    let lines: Vec<&str> = output.lines().collect();
    let has_diagnostic = lines
        .iter()
        .any(|line| is_warning_or_error(line) || line.trim_start().starts_with("error["));

    if !has_diagnostic {
        return CompressionResult::new(output.trim_end().to_string());
    }

    let mut blocks = Vec::new();
    let mut index = 0usize;

    while index < lines.len() {
        let line = lines[index];
        let noise = line.trim().is_empty()
            || (is_cargo_status_line(line) && !is_final_cargo_summary(line))
            || is_test_progress_line(line.trim());
        if noise {
            index += 1;
            continue;
        }

        if is_warning_or_error(line) || line.trim_start().starts_with("error[") {
            let class = if line.trim_start().starts_with("warning:") {
                DropClass::Warning
            } else {
                DropClass::Error
            };
            let start = index;
            index += 1;
            // The block owns the diagnostic's own body only. A line that does
            // not continue it (another tool's verdict in a gate script) is not
            // the diagnostic's to lose when the block is capped.
            let mut body = DiagnosticBody::default();
            while index < lines.len()
                && !starts_next_build_message(lines[index])
                && body.continues(lines[index])
            {
                index += 1;
            }
            blocks.push(ClassifiedBlock::new(class, lines[start..index].join("\n")));
            continue;
        }

        // Cargo's final summary and any line cargo did not write itself.
        blocks.push(ClassifiedBlock::unclassified(line.to_string()));
        index += 1;
    }

    let capped = cap_classified_blocks(blocks);
    CompressionResult::with_class_drops(trim_trailing_lines(&capped.text), capped.dropped_by_class)
        .map_text(|text| ensure_final_lines(output, text))
}

fn starts_next_build_message(line: &str) -> bool {
    is_cargo_status_line(line)
        || is_warning_or_error(line)
        || line.trim_start().starts_with("error[")
        || is_final_cargo_summary(line)
}

fn is_warning_or_error(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with("warning:") || trimmed.starts_with("error:")
}

fn is_error_diagnostic(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with("error:") || trimmed.starts_with("error[")
}

fn is_ignored_progress(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed == "Updating crates.io index" || is_compiling_line(trimmed)
}

fn is_compiling_line(trimmed: &str) -> bool {
    let Some(rest) = trimmed.strip_prefix("Compiling ") else {
        return false;
    };
    let mut parts = rest.split_whitespace();
    let _crate_name = parts.next();
    parts.next().is_some_and(|part| {
        part.strip_prefix('v').is_some_and(|version| {
            version
                .chars()
                .all(|char| char.is_ascii_digit() || char == '.')
        })
    })
}

fn is_final_cargo_summary(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with("Finished ")
        || trimmed.starts_with("error: could not compile")
        || trimmed.starts_with("test result:")
}

/// Cargo status verbs. Cargo right-aligns them in a 12-column field, so a real
/// status line is indented; an unindented "Running checks" from a script is not
/// one.
const CARGO_STATUS_VERBS: &[&str] = &[
    "Adding",
    "Blocking",
    "Building",
    "Checking",
    "Compiling",
    "Doc-tests",
    "Documenting",
    "Downloaded",
    "Downloading",
    "Executable",
    "Finished",
    "Fresh",
    "Locking",
    "Running",
    "Updating",
];

fn is_cargo_status_line(line: &str) -> bool {
    if is_ignored_progress(line) {
        return true;
    }
    let trimmed = line.trim_start();
    line.starts_with(' ')
        && CARGO_STATUS_VERBS.iter().any(|verb| {
            trimmed
                .strip_prefix(verb)
                .is_some_and(|rest| rest.starts_with(' '))
        })
}

/// libtest's per-test progress (`test name ... ok`, `... ignored`,
/// `... FAILED`) and its slow-test notice. The `test result:` line and the
/// failure list already account for every one of them.
fn is_test_progress_line(trimmed: &str) -> bool {
    trimmed.strip_prefix("test ").is_some_and(|rest| {
        rest.contains(" ... ") || rest.ends_with(" has been running for over 60 seconds")
    }) || is_nextest_progress_line(trimmed)
}

/// cargo nextest's per-test progress for tests that did not fail, which its
/// `Summary [` line accounts for: `PASS [   0.004s] name`, `SLOW [> 60.000s]
/// name`, `SKIP [ ] name` and `Starting N tests across M binaries`. `FAIL [`
/// and `TIMEOUT [` lines are not progress: they name the failures and are kept.
fn is_nextest_progress_line(trimmed: &str) -> bool {
    let bracketed = |status: &str| {
        trimmed
            .strip_prefix(status)
            .and_then(|rest| rest.trim_start().strip_prefix('['))
            .and_then(|rest| rest.split_once(']'))
            .map(|(inside, _)| inside.trim().trim_start_matches("> "))
    };
    let timed = |inside: &str| {
        inside
            .strip_suffix('s')
            .is_some_and(|seconds| seconds.parse::<f64>().is_ok())
    };
    bracketed("PASS").is_some_and(timed)
        || bracketed("SLOW").is_some_and(timed)
        || bracketed("SKIP").is_some()
        || trimmed
            .strip_prefix("Starting ")
            .is_some_and(|rest| rest.contains(" tests across "))
}

/// Follows the body of one rustc or clippy diagnostic line by line and says
/// whether each line still belongs to it. A line belongs only when it has a
/// shape the compiler prints; indentation alone proves nothing, because a gate
/// script's indented verdict (`  win-check rc=101`) is just as indented. A
/// blank line ends the body: rustc separates diagnostics with one and never
/// puts one inside.
#[derive(Default)]
struct DiagnosticBody {
    /// Column of the `=` of the last `= note:` / `= help:` line. rustc wraps a
    /// long note onto following lines aligned past that `= label: ` prefix.
    label_column: Option<usize>,
}

impl DiagnosticBody {
    fn continues(&mut self, line: &str) -> bool {
        let trimmed = line.trim_start();
        let indent = line.len() - trimmed.len();
        if trimmed.is_empty() {
            self.label_column = None;
            return false;
        }
        if is_equals_label(trimmed) {
            self.label_column = Some(indent);
            return true;
        }
        // `= note: expected type `u32``
        // `           found reference `&str``
        if self
            .label_column
            .is_some_and(|column| indent > column + "= ".len())
        {
            return true;
        }
        self.label_column = None;
        trimmed.starts_with("--> ")
            || trimmed.starts_with("::: ")
            || is_diagnostic_gutter(line)
            || trimmed.starts_with('^')
            || trimmed == "..."
            || trimmed.starts_with("help:")
            || trimmed.starts_with("note:")
    }
}

/// `= note: ...`, `= help: ...` and the like: an indented `= ` followed by a
/// lowercase word and a colon.
fn is_equals_label(trimmed: &str) -> bool {
    trimmed
        .strip_prefix("= ")
        .and_then(|rest| rest.split_once(':'))
        .is_some_and(|(word, _)| {
            !word.is_empty() && word.chars().all(|char| char.is_ascii_lowercase())
        })
}

/// The source gutter rustc draws down a diagnostic: `   |` (with carets,
/// underlines or labels after it), `12 | code`, and a suggestion's diff lines
/// `12 + code`, `12 - code`, `12 ~ code`. An unnumbered gutter is always
/// indented; a diff marker always follows a line number.
fn is_diagnostic_gutter(line: &str) -> bool {
    let trimmed = line.trim_start();
    let digits = trimmed.len()
        - trimmed
            .trim_start_matches(|char: char| char.is_ascii_digit())
            .len();
    let after_number = &trimmed[digits..];
    let marker_text = after_number.trim_start();
    let mut marker = marker_text.chars();
    let Some(symbol) = marker.next() else {
        return false;
    };
    let marker_ends = marker.next().is_none_or(char::is_whitespace);
    if digits == 0 {
        return line.starts_with(char::is_whitespace) && symbol == '|' && marker_ends;
    }
    after_number.starts_with(char::is_whitespace)
        && matches!(symbol, '|' | '+' | '-' | '~')
        && marker_ends
}

/// Mark the lines of a `cargo test` run that its summary may leave out because
/// the summary already accounts for them: blank lines, per-test progress,
/// cargo's status lines and compiler warning blocks. Every other line is
/// somebody's report (a test's printed output, another check's verdict in a
/// gate script) and must be kept verbatim and in order.
fn test_noise_mask(lines: &[&str]) -> Vec<bool> {
    let mut warning: Option<DiagnosticBody> = None;
    lines
        .iter()
        .map(|line| {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                warning = None;
                return true;
            }
            if trimmed.starts_with("warning:") {
                warning = Some(DiagnosticBody::default());
                return true;
            }
            if warning.as_mut().is_some_and(|body| body.continues(line)) {
                return true;
            }
            warning = None;
            is_test_progress_line(trimmed) || is_cargo_status_line(line)
        })
        .collect()
}

fn compress_test(output: &str, exit_code: Option<i64>) -> CompressionResult {
    let lines: Vec<&str> = output.lines().collect();
    let noise = test_noise_mask(&lines);
    let failure_headers = failure_list_headers(&lines);
    let has_failures = failure_headers.iter().any(|header| *header);
    let total = cargo_test_total_line(&lines);
    if !has_failures {
        let has_error_diagnostic = lines.iter().any(|line| is_error_diagnostic(line));
        let has_warning_or_error = lines
            .iter()
            .any(|line| is_warning_or_error(line) || line.trim_start().starts_with("error["));
        if has_error_diagnostic
            || (matches!(exit_code, Some(code) if code != 0) && has_warning_or_error)
        {
            return append_cargo_test_total(compress_build_like(output), total.as_deref());
        }

        let result: Vec<String> = lines
            .iter()
            .zip(&noise)
            .filter(|(line, noise)| {
                let trimmed = line.trim_start();
                trimmed.starts_with("running ")
                    || trimmed.starts_with("test result:")
                    || is_final_cargo_summary(trimmed)
                    || !**noise
            })
            .map(|(line, _)| (*line).to_string())
            .collect();
        return append_cargo_test_total(
            CompressionResult::new(ensure_final_lines(
                output,
                &trim_trailing_lines(&result.join("\n")),
            )),
            total.as_deref(),
        );
    }

    let mut sections = Vec::new();
    let mut summary = Vec::new();
    let mut names = Vec::new();
    let mut seen_names = std::collections::HashSet::new();
    let mut in_failure_list = false;
    let mut warnings = 0;
    let mut index = 0usize;
    while index < lines.len() {
        let line = lines[index];
        let trimmed = line.trim_start();
        if failure_headers[index] {
            in_failure_list = true;
            index += 1;
            continue;
        }
        if let Some(name) = failure_name(trimmed.trim_end(), in_failure_list) {
            if seen_names.insert(name) {
                names.push(name);
            }
            if !line.starts_with("---- ") {
                index += 1;
                continue;
            }
        } else if !trimmed.is_empty() {
            in_failure_list = false;
        }

        if line.starts_with("---- ") {
            let start = index;
            while index < lines.len() {
                index += 1;
                if index < lines.len()
                    && (lines[index].starts_with("---- ")
                        || lines[index].trim_start().starts_with("test result:")
                        || failure_headers[index])
                {
                    break;
                }
            }
            sections.push(&lines[start..index]);
            in_failure_list = false;
            continue;
        }

        if trimmed.starts_with("warning:") {
            warnings += 1;
        }
        if trimmed.starts_with("test result:") {
            // A new test binary may report the same name as an earlier one.
            seen_names.clear();
        }
        if !noise[index] {
            summary.push(line);
        }
        index += 1;
    }

    let list = format!("failures:\n    {}", names.join("\n    "));
    let verdict_at = summary
        .iter()
        .position(|line| line.trim_start().starts_with("test result:"))
        .unwrap_or(summary.len());
    summary.insert(verdict_at, &list);
    let summary =
        append_cargo_test_total(CompressionResult::new(summary.join("\n")), total.as_deref());
    let summary = summary.map_text(|text| ensure_final_lines(output, text));
    let (details, dropped) = bounded_failure_sections(&sections, summary.text.len());
    let text = if details.is_empty() {
        summary.text
    } else {
        summary
            .text
            .replacen(&list, &format!("{details}\n{list}"), 1)
    };
    let mut drops = std::collections::BTreeMap::new();
    if warnings > 0 {
        drops.insert(DropClass::Warning, warnings);
    }
    if dropped > 0 {
        drops.insert(DropClass::Failure, dropped);
    }
    let mut result = CompressionResult::with_class_drops(text, drops);
    result.bounded_cargo_test_details = true;
    result
}

// Failed completion previews have a 512-byte head and a 1,792-byte tail,
// not a fixed line cap. Reserve the names and results before spending the tail
// on panic sections, so compiler warnings cannot displace the explanation.
test_support_visibility! {
const FAILURE_SECTION_LINES: usize = 6;
}
test_support_visibility! {
const FAILURE_DETAIL_LINES: usize = 20;
}
const FAILURE_DETAIL_BYTES: usize = super::caps::COMPLETION_FAILURE_TAIL_BYTES;

fn bounded_failure_sections(sections: &[&[&str]], summary_bytes: usize) -> (String, usize) {
    let mut remaining_bytes = FAILURE_DETAIL_BYTES.saturating_sub(summary_bytes + 1);
    let mut remaining_lines = FAILURE_DETAIL_LINES;
    let mut kept = Vec::new();
    let mut dropped = 0;
    for section in sections {
        let panic = section.iter().position(|line| line.contains("panicked at"));
        let start = panic.unwrap_or(1);
        let body: Vec<&str> = section[start..]
            .iter()
            .copied()
            .filter(|line| {
                !line.trim().is_empty()
                    && !line
                        .trim_start()
                        .starts_with("note: run with `RUST_BACKTRACE")
            })
            .collect();
        let mut candidate = vec![section[0]];
        let mut bytes = section[0].len() + 1;
        // A panic location alone does not explain why the assertion failed.
        // Keep the header and the first two body lines together, or omit them.
        let minimum = body.len().min(2);
        let minimum_bytes = bytes
            + body[..minimum]
                .iter()
                .map(|line| line.len() + 1)
                .sum::<usize>();
        if remaining_lines < minimum + 1 || remaining_bytes < minimum_bytes {
            dropped += 1;
            continue;
        }
        for line in &body {
            if candidate.len() == FAILURE_SECTION_LINES
                || candidate.len() == remaining_lines
                || bytes + line.len() + 1 > remaining_bytes
            {
                break;
            }
            candidate.push(line);
            bytes += line.len() + 1;
        }
        if candidate.len() < body.len() + 1 {
            dropped += 1;
        }
        remaining_lines -= candidate.len();
        remaining_bytes -= bytes;
        kept.extend(candidate);
    }
    (kept.join("\n"), dropped)
}

test_support_visibility! {
pub(super) fn failure_summary_preserved(raw: &str, compressed: &str) -> bool {
    let raw_counts = failure_name_counts(raw);
    let compressed_counts = failure_name_counts(compressed);
    if raw_counts.is_empty()
        || raw_counts.iter().any(|(name, views)| {
            compressed_counts.get(name).map_or(0, |counts| counts[2]) < *views.iter().max().unwrap()
        })
    {
        return false;
    }
    let mut saw_result = false;
    let compressed_lines: std::collections::HashSet<_> =
        compressed.lines().map(str::trim).collect();
    for line in raw.lines().map(str::trim) {
        if line.starts_with("test result:") {
            saw_result = true;
            if !compressed_lines.contains(line) {
                return false;
            }
        }
    }
    saw_result && compressed_lines.contains("failures:")
}
}

// Libtest introduces stdout sections with a header, then repeats the header
// before an indented name list and its verdict. A test can print the same word;
// without that surrounding structure it remains ordinary captured output.
fn failure_list_headers(lines: &[&str]) -> Vec<bool> {
    lines
        .iter()
        .enumerate()
        .map(|(index, line)| {
            if line.trim() != "failures:" {
                return false;
            }
            let mut saw_name = false;
            for next in &lines[index + 1..] {
                let trimmed = next.trim();
                if trimmed.is_empty() {
                    continue;
                }
                if !saw_name && trimmed.starts_with("---- ") && trimmed.ends_with(" stdout ----") {
                    return true;
                }
                if next.starts_with(char::is_whitespace) && failure_name(trimmed, true).is_some() {
                    saw_name = true;
                    continue;
                }
                return saw_name && trimmed.starts_with("test result:");
            }
            false
        })
        .collect()
}

fn failure_name_counts(output: &str) -> std::collections::HashMap<&str, [usize; 3]> {
    let lines: Vec<_> = output.lines().collect();
    let headers = failure_list_headers(&lines);
    let mut counts = std::collections::HashMap::<_, [usize; 3]>::new();
    let mut in_list = false;
    for (index, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if headers[index] {
            in_list = true;
            continue;
        }
        if let Some(name) = failure_name(trimmed, in_list) {
            let kind = failure_name_kind(trimmed);
            if kind == 1 {
                in_list = false;
            }
            counts.entry(name).or_default()[kind] += 1;
        } else if !trimmed.is_empty() {
            in_list = false;
        }
    }
    counts
}

// Status, stdout header and final list are three views of each failure,
// not three occurrences. The summary must list each reported occurrence.
fn failure_name_kind(line: &str) -> usize {
    if line.starts_with("test ") || is_nextest_verdict(line) {
        0
    } else if line.starts_with("---- ") {
        1
    } else {
        2
    }
}

fn append_cargo_test_total(
    compressed: CompressionResult,
    total: Option<&str>,
) -> CompressionResult {
    match total {
        Some(total) => compressed.map_text(|text| insert_cargo_test_total(text, total)),
        None => compressed,
    }
}

fn insert_cargo_test_total(output: &str, total: &str) -> String {
    let mut lines = output.lines().map(str::to_string).collect::<Vec<_>>();
    let insert_at = lines
        .iter()
        .rposition(|line| line.trim_start().starts_with("test result:"))
        .map_or(lines.len(), |index| index + 1);
    lines.insert(insert_at, total.to_string());
    lines.join("\n")
}

fn cargo_test_total_line(lines: &[&str]) -> Option<String> {
    let mut passed = 0usize;
    let mut failed = 0usize;
    let mut ignored = 0usize;
    let mut binaries = 0usize;
    let mut unparsed_binaries = 0usize;

    for line in lines {
        if !line.trim_start().starts_with("test result:") {
            continue;
        }
        binaries += 1;
        let counts = ["passed", "failed", "ignored"].map(|label| {
            line.split(';').find_map(|field| {
                let mut words = field.split_whitespace().rev();
                (words.next()? == label).then(|| words.next()?.parse::<usize>().ok())?
            })
        });
        match counts {
            [Some(binary_passed), Some(binary_failed), Some(binary_ignored)] => {
                passed = passed.saturating_add(binary_passed);
                failed = failed.saturating_add(binary_failed);
                ignored = ignored.saturating_add(binary_ignored);
            }
            _ => unparsed_binaries += 1,
        }
    }

    if binaries < 2 {
        return None;
    }

    let mut total = format!(
        "cargo test total: {passed} passed, {failed} failed, {ignored} ignored across {binaries} binaries"
    );
    let mut incomplete = Vec::new();
    if lines
        .iter()
        .any(|line| line.trim_start().starts_with("error: could not compile"))
    {
        incomplete.push("one or more test binaries failed to compile".to_string());
    }
    let started_binaries = lines
        .iter()
        .filter(|line| {
            let Some(rest) = line.trim_start().strip_prefix("running ") else {
                return false;
            };
            let mut words = rest.split_whitespace();
            words
                .next()
                .is_some_and(|count| count.parse::<usize>().is_ok())
                && matches!(words.next(), Some("test" | "tests"))
        })
        .count();
    let cut_off_binaries = started_binaries.saturating_sub(binaries);
    if cut_off_binaries == 1 {
        incomplete.push("1 test binary was cut off before reporting a result".to_string());
    } else if cut_off_binaries > 1 {
        incomplete.push(format!(
            "{cut_off_binaries} test binaries were cut off before reporting a result"
        ));
    }
    if unparsed_binaries == 1 {
        incomplete.push("1 test result could not be parsed".to_string());
    } else if unparsed_binaries > 1 {
        incomplete.push(format!(
            "{unparsed_binaries} test results could not be parsed"
        ));
    }
    if !incomplete.is_empty() {
        total.push_str(" (incomplete: ");
        total.push_str(&incomplete.join("; "));
        total.push(')');
    }
    Some(total)
}

fn trim_trailing_lines(input: &str) -> String {
    input
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Lines a byte-capped bash reply must retain even when stderr follows the
/// test results. Names and totals are never capped; priority protection covers
/// the first twenty distinct panic locations so backtraces cannot consume the
/// reply. Already bounded panic sections also retain their message lines.
pub struct TestVerdict {
    pub required: Vec<usize>,
    pub empty_results: Vec<usize>,
}

pub fn test_verdict(lines: &[&str]) -> Option<TestVerdict> {
    use std::collections::HashSet;

    if !lines.iter().any(|line| {
        is_cargo_test_signature_line(line.trim_start()) || is_nextest_verdict(line.trim_start())
    }) {
        return None;
    }

    let mut required = Vec::new();
    let mut empty_results = Vec::new();
    let mut names = std::collections::HashMap::<_, [usize; 3]>::new();
    let mut locations = HashSet::new();
    let failure_headers = failure_list_headers(lines);
    let mut in_failure_list = false;
    for (index, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if failure_headers[index] {
            in_failure_list = true;
            continue;
        }
        let failure_name = failure_name(trimmed, in_failure_list);
        if trimmed.starts_with("---- ") || (!trimmed.is_empty() && failure_name.is_none()) {
            in_failure_list = false;
        }
        let is_name = failure_name.is_some_and(|name| {
            let counts = names.entry(name).or_default();
            let previous = *counts.iter().max().unwrap();
            let kind = failure_name_kind(trimmed);
            counts[kind] += 1;
            counts[kind] > previous
        });
        let is_panic = (trimmed.starts_with("thread '") && trimmed.contains("panicked at"))
            || (index > 0 && lines[index - 1].trim_end().ends_with("panicked at"));
        let is_location = is_panic && locations.len() < 20 && locations.insert(trimmed);
        if trimmed.starts_with(
            "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;",
        ) {
            empty_results.push(index);
        } else if is_name
            || is_location
            || trimmed.starts_with("test result:")
            || trimmed.starts_with("cargo test total:")
            || trimmed.starts_with("Summary [")
            || trimmed.starts_with("error: test failed, to rerun")
        {
            required.push(index);
        }
    }
    if let Some(bounded) = bounded_failure_verdict_lines(lines) {
        required.extend(bounded);
        required.sort_unstable();
        required.dedup();
    }
    Some(TestVerdict {
        required,
        empty_results,
    })
}

fn bounded_failure_verdict_lines(lines: &[&str]) -> Option<Vec<usize>> {
    let mut required = Vec::new();
    let mut in_section = false;
    let mut in_list = false;
    let mut section_lines = 0;
    let mut detail_lines = 0;
    let mut bytes = 0;
    let failure_headers = failure_list_headers(lines);
    for (index, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if line.starts_with("---- ") && line.ends_with(" stdout ----") {
            in_section = true;
            in_list = false;
            section_lines = 0;
        } else if failure_headers[index] {
            in_section = false;
            in_list = true;
        } else if trimmed.starts_with("test result:")
            || trimmed.starts_with("cargo test total:")
            || trimmed.starts_with("error: test failed, to rerun")
        {
            in_section = false;
            in_list = false;
        } else if in_list && !trimmed.is_empty() && failure_name(trimmed, true).is_none() {
            in_list = false;
        }
        if trimmed.is_empty() {
            continue;
        }
        if in_section {
            section_lines += 1;
            detail_lines += 1;
            if section_lines > FAILURE_SECTION_LINES || detail_lines > FAILURE_DETAIL_LINES {
                return None;
            }
        }
        if in_section
            || in_list
            || trimmed.starts_with("test result:")
            || trimmed.starts_with("cargo test total:")
            || trimmed.starts_with("error: test failed, to rerun")
        {
            bytes += line.len() + 1;
            if bytes > FAILURE_DETAIL_BYTES {
                return None;
            }
            required.push(index);
        }
    }
    (detail_lines > 0).then_some(required)
}

fn is_nextest_verdict(line: &str) -> bool {
    ["FAIL [", "TIMEOUT [", "Summary ["]
        .iter()
        .any(|prefix| line.starts_with(prefix))
}

fn failure_name(line: &str, in_failure_list: bool) -> Option<&str> {
    if let Some(name) = line
        .strip_prefix("test ")
        .and_then(|line| line.strip_suffix(" ... FAILED"))
    {
        return Some(name);
    }
    if let Some(name) = line
        .strip_prefix("---- ")
        .and_then(|line| line.strip_suffix(" stdout ----"))
    {
        return Some(name);
    }
    if line.starts_with("FAIL [") || line.starts_with("TIMEOUT [") {
        return line.split_once(']').map(|(_, name)| name.trim());
    }
    // The second libtest `failures:` block lists bare names, one per line.
    if in_failure_list && !line.is_empty() && !line.contains(char::is_whitespace) {
        return Some(line);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compress::caps::DropClass;
    use crate::compress::{
        builtin_filters, compress_with_registry_exit_code, toml_filter::build_registry,
    };

    const HOST_SUPERVISOR_FAILURES: &str = include_str!(
        "../../../aft/tests/integration/fixtures/compress_filters/cargo-test/host-supervisor-two-failures.stdout"
    );

    #[test]
    fn cargo_test_printed_failure_header_is_not_a_failure_list() {
        let raw = format!("{}running 1 test\ntest tests::foo ... FAILED\n\nfailures:\n\n---- tests::foo stdout ----\nthread 'tests::foo' panicked at src/lib.rs:1:1:\nfailures:\nnot_a_test\n\nfailures:\n    tests::foo\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\nerror: test failed, to rerun pass `--lib`\n", "   Compiling fixture v0.1.0\n".repeat(80));
        let registry = build_registry(builtin_filters::ALL, None, None);
        let result = compress_with_registry_exit_code("cargo test", &raw, Some(101), &registry);
        assert!(result.bounded_cargo_test_details);
        assert!(
            result.text.contains("failures:\nnot_a_test\n"),
            "{}",
            result.text
        );
        assert!(!result.text.lines().any(|line| line == "    not_a_test"));
        assert_eq!(failure_name_counts(&raw).len(), 1);
        assert_eq!(
            failure_name_counts(&raw).get("tests::foo"),
            Some(&[1, 1, 1])
        );
        assert_eq!(
            failure_name_counts(&result.text).get("tests::foo"),
            Some(&[0, 1, 1])
        );
        assert!(failure_summary_preserved(&raw, &result.text));
    }

    #[test]
    fn cargo_test_reserves_final_line_before_spending_detail_budget() {
        let final_line = format!("warning: final status {}", "x".repeat(1100));
        let raw = format!("{HOST_SUPERVISOR_FAILURES}{final_line}\n");
        let result = compress_test(&raw, Some(101));
        assert_eq!(result.text.lines().last(), Some(final_line.as_str()));
        assert!(
            result.text.len() <= FAILURE_DETAIL_BYTES,
            "{} bytes",
            result.text.len()
        );
        assert!(failure_summary_preserved(&raw, &result.text));
    }

    #[test]
    fn cargo_test_caps_failure_details_but_keeps_every_failure_name() {
        let mut output = String::from("running 40 tests\n\nfailures:\n\n");
        for index in 0..40 {
            output.push_str(&format!(
                "---- case_{index} stdout ----\nthread 'case_{index}' panicked at src/lib.rs:{index}:1\nstack line {index}\n\n"
            ));
        }
        output.push_str("failures:\n");
        for index in 0..40 {
            output.push_str(&format!("    case_{index}\n"));
        }
        output.push_str(
            "\ntest result: FAILED. 0 passed; 40 failed; 0 ignored; 0 measured; 0 filtered out\n",
        );

        let result = compress_test(&output, None);

        assert!(
            result
                .dropped_by_class
                .get(&DropClass::Failure)
                .copied()
                .unwrap_or(0)
                > 0
        );
        let (details, names) = result.text.split_once("failures:\n").expect("failure list");
        assert!(details.lines().count() <= FAILURE_DETAIL_LINES + 1);
        assert!(result.text.len() <= FAILURE_DETAIL_BYTES);
        assert!(details.contains("---- case_0 stdout ----"));
        assert!(details.contains("stack line 0"));
        assert!(!details.contains("---- case_39 stdout ----"));
        for index in 0..40 {
            assert!(names
                .lines()
                .any(|line| line == format!("    case_{index}")));
        }
        assert!(result.had_inner_drop);
        assert!(!result.offset_hint_eligible);
    }

    #[test]
    fn cargo_test_compile_error_preserves_diagnostic_with_unknown_exit() {
        let output = r#"   Compiling demo v0.1.0 (/tmp/demo)
error[E0432]: unresolved import `crate::missing`
 --> src/lib.rs:1:5
  |
1 | use crate::missing;
  |     ^^^^^^^^^^^^^^ no `missing` in the root

error: could not compile `demo` (lib test) due to 1 previous error
"#;

        let result = compress_test(output, None);

        assert!(result.text.contains("error[E0432]"));
        assert!(result.text.contains("unresolved import"));
        assert!(result.text.contains("error: could not compile"));
    }

    #[test]
    fn cargo_test_sums_results_even_when_output_is_wrapped() {
        let output = "runner: cargo test\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\nrunning 1 test\ntest result: FAILED. 1 passed; 1 failed; 2 ignored; 0 measured; 0 filtered out\n";

        assert!(CargoCompressor.matches_output(output));
        let result = compress_test(output, Some(101));

        assert!(result
            .text
            .contains("cargo test total: 3 passed, 1 failed, 3 ignored across 2 binaries"));
    }

    #[test]
    fn cargo_test_total_marks_binaries_that_failed_to_compile() {
        let output = "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\nerror: could not compile `broken` (bin test) due to 1 previous error\n";

        let result = compress_test(output, Some(101));

        assert!(result
            .text
            .contains("cargo test total: 3 passed, 0 failed, 1 ignored across 2 binaries"));
        assert!(result
            .text
            .contains("incomplete: one or more test binaries failed to compile"));
    }

    #[test]
    fn cargo_test_total_marks_binaries_without_a_result_as_incomplete() {
        let output = "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\nrunning 1 test\n";

        let result = compress_test(output, Some(0));

        assert!(result
            .text
            .contains("cargo test total: 3 passed, 0 failed, 0 ignored across 2 binaries"));
        assert!(result
            .text
            .contains("incomplete: 1 test binary was cut off before reporting a result"));
    }

    #[test]
    fn cargo_verdict_keeps_aggregate_total_for_byte_capped_replies() {
        let lines = [
            "running 1 test",
            "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out",
            "cargo test total: 1 passed, 0 failed, 0 ignored across 2 binaries",
        ];
        let verdict = test_verdict(&lines).expect("cargo test output has a verdict");

        assert!(verdict.required.contains(&2));
    }

    #[test]
    fn cargo_verdict_extractor_keeps_nonfinal_rerun_with_unknown_exit() {
        let output = format!("running 1 test\n\nfailures:\n\n---- case stdout ----\nthread 'case' panicked at src/lib.rs:1:1:\n\nfailures:\n    case\n\ntest result: FAILED. 0 passed; 1 failed\nerror: test failed, to rerun pass `--lib`\n{}wrapper finished\n", "wrapper progress\n".repeat(200));
        let result = compress_test(&output, None);
        assert!(result
            .text
            .contains("error: test failed, to rerun pass `--lib`"));
        assert!(result.text.ends_with("wrapper finished"));
    }

    /// A gate script's output, verbatim: two verdicts from other tools, then
    /// four cargo test binaries.
    const GATE_SCRIPT_OUTPUT: &str = "fmt-ok\nwin-check rc=0\ntest result: ok. 803 passed; 0 failed; 19 ignored; 0 measured; 8977 filtered out; finished in 23.38s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.12s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2592 filtered out; finished in 0.16s\ntest result: ok. 114 passed; 0 failed; 3 ignored; 0 measured; 2476 filtered out; finished in 11.74s\n";

    #[test]
    fn cargo_test_summary_keeps_gate_script_verdicts_it_does_not_read() {
        let result = compress_test(GATE_SCRIPT_OUTPUT, Some(0));

        assert_eq!(
            result.text,
            format!(
                "{}\ncargo test total: 919 passed, 0 failed, 22 ignored across 4 binaries",
                GATE_SCRIPT_OUTPUT.trim_end()
            )
        );
    }

    #[test]
    fn cargo_test_summary_keeps_a_failed_verdict_it_does_not_read() {
        let output = GATE_SCRIPT_OUTPUT.replace("win-check rc=0", "win-check rc=101");

        let result = compress_test(&output, Some(0));

        assert!(
            result
                .text
                .starts_with("fmt-ok\nwin-check rc=101\ntest result: ok. 803 passed"),
            "{}",
            result.text
        );
    }

    #[test]
    fn cargo_test_summary_drops_progress_but_keeps_printed_lines_in_order() {
        let output = "   Compiling demo v0.1.0 (/tmp/demo)\n    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.50s\n     Running unittests src/lib.rs (target/debug/deps/demo-0123)\n\nrunning 2 tests\ntest a ... ok\nfmt-ok\ntest b ... ok\nwin-check rc=101\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n";

        let result = compress_test(output, Some(0));

        assert_eq!(
            result.text,
            "    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.50s\nrunning 2 tests\nfmt-ok\nwin-check rc=101\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"
        );
    }

    #[test]
    fn cargo_test_summary_drops_nextest_progress_but_keeps_its_failures() {
        let output = "running 1 test\ntest a ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n    Starting 3 tests across 1 binary\n        PASS [   0.004s] demo tests::a\n        SKIP [         ] demo tests::c\n        FAIL [   0.010s] demo tests::b\nPASS [lint] rc=0\n     Summary [   0.020s] 3 tests run: 1 passed, 1 failed, 1 skipped\n";

        let result = compress_test(output, Some(0));

        assert_eq!(
            result.text,
            "running 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n        FAIL [   0.010s] demo tests::b\nPASS [lint] rc=0\n     Summary [   0.020s] 3 tests run: 1 passed, 1 failed, 1 skipped"
        );
    }

    #[test]
    fn cargo_test_failure_summary_keeps_lines_it_does_not_read() {
        let output = "fmt-ok\nwin-check rc=101\nrunning 2 tests\ntest a ... ok\ntest case ... FAILED\n\nfailures:\n\n---- case stdout ----\nthread 'case' panicked at src/lib.rs:1:1\n\nfailures:\n    case\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\nlint-check rc=0\n";

        let result = compress_test(output, Some(101));

        assert!(
            result
                .text
                .starts_with("fmt-ok\nwin-check rc=101\nrunning 2 tests\n"),
            "{}",
            result.text
        );
        assert!(
            result.text.contains("---- case stdout ----"),
            "{}",
            result.text
        );
        assert!(
            result.text.ends_with("\nlint-check rc=0"),
            "{}",
            result.text
        );
        assert!(!result.text.contains("test a ... ok"), "{}", result.text);
    }

    /// One clippy-style warning carrying every continuation shape rustc and
    /// clippy print: locators, gutters, labels under carets and underlines,
    /// elided source, `= note:` text wrapped onto an aligned line, `= help:`,
    /// a suggestion diff and bare `help:`/`note:` sub-diagnostics. Every line
    /// names `w{index}`, so a test can tell whether the whole warning went.
    fn full_warning(index: usize) -> String {
        let line = index + 1;
        format!(
            "warning: mismatched value `w{index}`\n\
             \x20 --> src/lib.rs:{line}:9\n\
             \x20  | w{index}\n\
             {line} |     let w{index}: u32 = \"w{index}\";\n\
             \x20  |            ---   ^^^^^ expected `u32`, found `&str` for w{index}\n\
             \x20  |            |\n\
             \x20  |            expected due to this w{index}\n\
             ...\n\
             \x20  = note: expected type `u32` for w{index}\n\
             \x20             found reference `&'static str` for w{index}\n\
             \x20  = help: for further information visit https://example.invalid/w{index}\n\
             help: try a number for w{index}\n\
             \x20  |\n\
             {line} -     let w{index}: u32 = \"w{index}\";\n\
             {line} +     let w{index}: u32 = 1;\n\
             \x20  | w{index}\n\
             note: the lint level for w{index} is defined here\n\
             \x20 ::: src/main.rs:1:9 w{index}\n"
        )
    }

    /// Eleven full warnings, one over the warning cap, with `separator` and an
    /// indented verdict from another tool after the eleventh.
    fn capped_warnings_then_indented_verdict(separator: &str) -> String {
        let mut output = String::from("    Checking demo v0.1.0 (/tmp/demo)\n");
        for index in 0..11 {
            if index > 0 {
                output.push('\n');
            }
            output.push_str(&full_warning(index));
        }
        output.push_str(separator);
        output.push_str("  win-check rc=101\n    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.50s\n");
        output
    }

    #[test]
    fn build_like_diagnostic_block_owns_every_continuation_shape() {
        let output = capped_warnings_then_indented_verdict("\n");

        let result = compress_build_like(&output);

        assert_eq!(result.dropped_by_class.get(&DropClass::Warning), Some(&1));
        // The capped eleventh warning goes whole: none of its lines is left
        // behind as a separate line.
        assert!(!result.text.contains("w10"), "{}", result.text);
        // The kept warnings keep their whole bodies.
        for shape in [
            "  --> src/lib.rs:10:9",
            "10 |     let w9: u32 = \"w9\";",
            "expected due to this w9",
            "              found reference `&'static str` for w9",
            "   = help: for further information visit https://example.invalid/w9",
            "10 +     let w9: u32 = 1;",
            "  ::: src/main.rs:1:9 w9",
        ] {
            assert!(result.text.contains(shape), "{shape}: {}", result.text);
        }
    }

    #[test]
    fn build_like_summaries_keep_an_indented_verdict_after_a_capped_warning() {
        for separator in ["", "\n"] {
            let output = capped_warnings_then_indented_verdict(separator);
            assert!(output.len() > SHORT_OUTPUT_BYTES);
            for command in ["cargo build", "cargo check", "cargo clippy"] {
                let result = CargoCompressor.compress_with_exit_code(command, &output, Some(0));

                assert!(
                    result.text.contains("\n  win-check rc=101\n"),
                    "{command} {separator:?}: {}",
                    result.text
                );
                assert!(
                    !result.text.contains("w10"),
                    "{command} {separator:?}: {}",
                    result.text
                );
            }
        }
    }

    #[test]
    fn cargo_test_summary_keeps_an_indented_verdict_after_a_warning() {
        for separator in ["", "\n"] {
            let output = format!(
                "{}{separator}  win-check rc=101\nrunning 1 test\ntest a ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n",
                full_warning(0)
            );

            let result = compress_test(&output, Some(0));

            assert_eq!(
                result.text,
                "  win-check rc=101\nrunning 1 test\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out",
                "{separator:?}"
            );
        }
    }

    #[test]
    fn cargo_build_like_summaries_keep_lines_they_do_not_read() {
        // Eleven diagnostic warnings and cargo's own `generated 11 warnings`
        // line make twelve warning blocks, two over the cap of ten, so the
        // last two are dropped. The verdict printed between them belongs to
        // neither block and must stay.
        let mut output = String::from("fmt-ok\n    Checking demo v0.1.0 (/tmp/demo)\n");
        for index in 0..11 {
            output.push_str(&format!(
                "warning: unused variable: `x{index}`\n --> src/lib.rs:{line}:9\n  |\n{line} |     let x{index} = 1;\n  |         ^^ help: prefix it with an underscore\n  |\n  = note: `#[warn(unused_variables)]` on by default\n\n",
                line = index + 1
            ));
        }
        output.push_str("win-check rc=101\nwarning: `demo` (lib) generated 11 warnings\n    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.50s\n");
        assert!(output.len() > SHORT_OUTPUT_BYTES);

        for command in ["cargo build", "cargo check", "cargo clippy"] {
            let result = CargoCompressor.compress_with_exit_code(command, &output, Some(0));

            assert!(
                result.text.starts_with("fmt-ok\n"),
                "{command}: {}",
                result.text
            );
            assert!(
                result.text.contains("\nwin-check rc=101\n"),
                "{command}: {}",
                result.text
            );
            assert!(
                !result.text.contains("Checking demo"),
                "{command}: {}",
                result.text
            );
            assert!(
                result.text.contains("Finished `dev` profile"),
                "{command}: {}",
                result.text
            );
            assert_eq!(result.dropped_by_class.get(&DropClass::Warning), Some(&2));
        }
    }

    #[test]
    fn cargo_test_compile_error_summary_keeps_lines_it_does_not_read() {
        let output = "fmt-ok\n   Compiling demo v0.1.0 (/tmp/demo)\nerror[E0432]: unresolved import `crate::missing`\n --> src/lib.rs:1:5\n  |\n1 | use crate::missing;\n  |     ^^^^^^^^^^^^^^ no `missing` in the root\n\nwin-check rc=101\nerror: could not compile `demo` (lib test) due to 1 previous error\n";

        let result = compress_test(output, Some(101));

        assert!(
            result.text.starts_with("fmt-ok\nerror[E0432]"),
            "{}",
            result.text
        );
        assert!(
            result
                .text
                .contains("no `missing` in the root\nwin-check rc=101\nerror: could not compile"),
            "{}",
            result.text
        );
    }

    #[test]
    fn cargo_nextest_output_keeps_lines_it_does_not_read() {
        // `cargo nextest` has no extractor of its own and falls back to
        // generic dedup, which must not lose a mixed-in verdict either. Forty
        // tests put the fixture past the 1 KiB raw passthrough.
        let mut output =
            String::from("fmt-ok\nwin-check rc=101\n    Starting 40 tests across 1 binary\n");
        for index in 0..40 {
            output.push_str(&format!(
                "        PASS [   0.004s] demo tests::case_{index}\n"
            ));
        }
        output.push_str("     Summary [   0.010s] 40 tests run: 40 passed, 0 skipped\n");
        assert!(output.len() > SHORT_OUTPUT_BYTES);

        let result = CargoCompressor.compress_with_exit_code("cargo nextest run", &output, Some(0));

        assert_eq!(result.text, output);
    }

    #[test]
    fn cargo_subcommand_returns_none_for_pipe_before_subcommand() {
        assert_eq!(cargo_subcommand("cargo --verbose | grep error"), None);
    }

    #[test]
    fn cargo_subcommand_returns_subcommand_when_before_pipe() {
        assert_eq!(
            cargo_subcommand("cargo test | grep FAIL").as_deref(),
            Some("test")
        );
    }

    #[test]
    fn cargo_subcommand_unaffected_without_metacharacters() {
        assert_eq!(
            cargo_subcommand("cargo test --release").as_deref(),
            Some("test")
        );
    }
}

#[cfg(any(test, feature = "test-support"))]
mod audit_regressions {
    #[test]
    fn cargo_global_options_before_subcommand() {
        for command in [
            "cargo +nightly test",
            "cargo --locked test",
            "cargo -Z unstable-options test",
            "cargo --config k=v test",
            "cargo --config=k=v test",
            "cargo --color always test",
            "cargo -Zunstable-options test",
        ] {
            assert_eq!(
                super::cargo_subcommand(command).as_deref(),
                Some("test"),
                "{command}"
            );
        }
    }
}