supercov 4.0.0

Coverage, security and code quality for coding agents
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
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
use supercov_contracts::AgentPagination;
use supercov_engine::{
    coverage_analysis::{CoverageSummary, McdcVector},
    coverage_index::{IndexedDimensionCoverage, IndexedFileGap, IndexedOutcomeCounts},
    coverage_query::{
        CoverageCoversData, CoverageDecisionData, CoverageDiagnostic, CoverageFileObligation,
        CoverageTestData, DecisionSort, MinimizeMetric,
    },
    indexed_query::{IndexedQueryData, IndexedQueryOutput, IndexedQueryRequest},
};

use crate::{PublicQueryOutput, public_query::PublicQueryInvocation};

const DEFAULT_LIMIT: usize = 20;

fn percentage(value: f64) -> String {
    format!("{value:.2}%")
}

/// A metric's share with its counts, or that the run had nothing of it to
/// measure: a file with no branches read `Branches 100.00% (0/0)`.
fn measured(percent: f64, covered: u64, total: u64) -> String {
    if total == 0 {
        "nothing to measure (0/0)".into()
    } else {
        format!("{} ({covered}/{total})", percentage(percent))
    }
}

/// A percentage in a table column, or `—` where there was nothing to measure.
fn share(percent: f64, total: usize) -> String {
    if total == 0 {
        "—".into()
    } else {
        percentage(percent)
    }
}

fn optional_percentage(value: Option<f64>) -> String {
    value.map(percentage).unwrap_or_else(|| "—".into())
}

fn readable_timestamp(value: &str) -> String {
    if value.len() >= 20 && value.as_bytes().get(10) == Some(&b'T') {
        format!("{} {} UTC", &value[..10], &value[11..19])
    } else {
        value.to_owned()
    }
}

fn number(value: f64) -> String {
    if value == 0.0 {
        "0".into()
    } else if value.fract() == 0.0 {
        format!("{value:.0}")
    } else {
        value.to_string()
    }
}

fn count(value: usize) -> String {
    let digits = value.to_string();
    let mut output = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, character) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            output.push(',');
        }
        output.push(character);
    }
    output
}

fn outcome_lines(outcomes: &IndexedOutcomeCounts) -> Vec<String> {
    [
        ("Passed", outcomes.passed),
        ("Failed", outcomes.failed),
        ("Flaky", outcomes.flaky),
        ("Skipped", outcomes.skipped),
        ("Todo", outcomes.todo),
        ("Timed out", outcomes.timed_out),
        ("Interrupted", outcomes.interrupted),
        ("Unknown", outcomes.unknown),
    ]
    .into_iter()
    .filter(|(_, value)| *value > 0)
    .map(|(label, value)| format!("  {label:<11} {}", count(value)))
    .collect()
}

/// The scope as a table: how many files, their status, where they are and why.
fn scope_group_lines(groups: &[supercov_engine::coverage_query::ScopeGroup]) -> Vec<String> {
    let files = groups
        .iter()
        .map(|group| count(group.files).len())
        .max()
        .unwrap_or(0)
        .max("Files".len());
    let directory = groups
        .iter()
        .map(|group| group.directory.chars().count())
        .max()
        .unwrap_or(0)
        .max("Directory".len());
    let mut lines = vec![format!(
        "{:>files$}  {:<9}  {:<directory$}  Reason",
        "Files", "Status", "Directory"
    )];
    lines.extend(groups.iter().map(|group| {
        format!(
            "{:>files$}  {:<9}  {:<directory$}  {}",
            count(group.files),
            group.status.to_uppercase(),
            group.directory,
            group.reason
        )
    }));
    lines
}

/// The line that settles unclassified source, ready to copy.
fn source_roots_hint(unclassified: &supercov_engine::coverage_query::UnclassifiedSource) -> String {
    format!(
        "If the ambiguous files are your code, name the source roots: SUPERCOV_SOURCE_ROOTS={}",
        unclassified.roots.join(",")
    )
}

fn diagnostic_lines(diagnostic: &CoverageDiagnostic) -> Vec<String> {
    if diagnostic.code == "TEST_EVIDENCE_MISSING" {
        let test_count = diagnostic
            .message
            .split_whitespace()
            .next()
            .and_then(|value| value.parse::<usize>().ok());
        let first = diagnostic
            .message
            .split_once("First: ")
            .map(|(_, value)| value.trim());
        if let (Some(test_count), Some(first)) = (test_count, first) {
            return vec![
                format!(
                    "  {} {} made assertions, but Supercov received no source-coverage evidence:",
                    count(test_count),
                    if test_count == 1 { "test" } else { "tests" }
                ),
                format!("    Example: {first}"),
                "  Possible causes: the code under test is outside the measured source (see `scope`), uninstrumented data, shared setup, lost async context, or missing probe transport. Missing evidence does not prove the code did not execute.".into(),
                "  Inspect the test's coverage and assertion details to distinguish missing execution from missing attribution.".into(),
            ];
        }
    }
    vec![format!("  {}", diagnostic.message)]
}

fn metric_name(metric: MinimizeMetric) -> &'static str {
    match metric {
        MinimizeMetric::All => "all",
        MinimizeMetric::Lines => "lines",
        MinimizeMetric::Statements => "statements",
        MinimizeMetric::Functions => "functions",
        MinimizeMetric::Branches => "branches",
        MinimizeMetric::Mcdc => "mcdc",
    }
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn page_label(page: &AgentPagination) -> String {
    let start = if page.total == 0 || page.returned == 0 {
        0
    } else {
        page.offset + 1
    };
    let end = (page.offset + page.returned).min(page.total);
    format!("showing {start}-{end} of {}", page.total)
}

fn next_page(base: &str, page: &AgentPagination) -> Option<String> {
    page.next_offset.map(|offset| {
        format!(
            "{base} --offset {offset}{}",
            if page.limit == DEFAULT_LIMIT {
                String::new()
            } else {
                format!(" --limit {}", page.limit)
            }
        )
    })
}

fn coverage_command(run: &str, request: &IndexedQueryRequest, child: &str) -> String {
    let mut values = vec![
        format!("{} runs", crate::launcher_command()),
        shell_quote(run),
        child.into(),
    ];
    if request.filter != "all" {
        values.push(format!("--filter {}", request.filter));
    }
    if let Some(kind) = &request.kind {
        values.push(format!("--kind {}", shell_quote(kind)));
    }
    if let Some(runner) = &request.runner {
        values.push(format!("--runner {}", shell_quote(runner)));
    }
    if request.metric != MinimizeMetric::All {
        values.push(format!("--metric {}", metric_name(request.metric)));
    }
    values.join(" ")
}

fn inspect_file_command(
    run: &str,
    request: &IndexedQueryRequest,
    file: Option<&str>,
) -> Option<String> {
    file.map(|file| {
        format!(
            "inspect file: {} {}",
            coverage_command(run, request, "file"),
            shell_quote(file)
        )
    })
}

fn filter_label(request: &IndexedQueryRequest) -> String {
    let mut labels = Vec::new();
    if request.filter != "all" {
        labels.push(format!("{} attempts only", request.filter));
    }
    if let Some(kind) = &request.kind {
        labels.push(format!("kind {kind}"));
    }
    if let Some(runner) = &request.runner {
        labels.push(format!("runner {runner}"));
    }
    labels.join(", ")
}

fn summary_line(summary: &CoverageSummary) -> String {
    format!(
        "lines {}, statements {}, functions {}, branches {}, MC/DC {}",
        share(summary.lines.percentage, summary.lines.total),
        share(summary.statements.percentage, summary.statements.total),
        share(summary.functions.percentage, summary.functions.total),
        share(summary.branches.percentage, summary.branches.total),
        share(summary.condition_coverage_pct, summary.conditions),
    )
}

fn gap_dimensions_total(gap: &supercov_engine::coverage_index::IndexedGapDimensions) -> usize {
    gap.lines + gap.statements + gap.functions + gap.branches + gap.mcdc_conditions
}

/// Coverage by directory: what each holds, how much of it every kind of test
/// covers, and how much all of them cover together.
fn render_areas(
    data: &supercov_engine::coverage_query::CoverageAreasData,
    request: &IndexedQueryRequest,
    page: &AgentPagination,
) -> String {
    use supercov_engine::coverage_query::dimension_for_metric;
    let (metric, heading) = match data.metric {
        MinimizeMetric::All | MinimizeMetric::Lines => (MinimizeMetric::Lines, "Lines"),
        MinimizeMetric::Statements => (MinimizeMetric::Statements, "Statements"),
        MinimizeMetric::Functions => (MinimizeMetric::Functions, "Functions"),
        MinimizeMetric::Branches => (MinimizeMetric::Branches, "Branches"),
        MinimizeMetric::Mcdc => (MinimizeMetric::Mcdc, "MC/DC"),
    };
    let percent = |covered: usize, total: usize| {
        share(
            if total == 0 {
                0.0
            } else {
                covered as f64 * 100.0 / total as f64
            },
            total,
        )
    };
    let mut table = vec![
        ["Directory".to_owned(), "Files".into(), heading.into()]
            .into_iter()
            .chain(data.kinds.iter().cloned())
            .chain(["All".to_owned()])
            .collect::<Vec<_>>(),
    ];
    for area in &data.areas {
        let total = dimension_for_metric(&area.totals, metric);
        table.push(
            [area.directory.clone(), count(area.files), count(total)]
                .into_iter()
                .chain(
                    area.by_kind
                        .iter()
                        .map(|kind| percent(dimension_for_metric(&kind.covered, metric), total)),
                )
                .chain([percent(dimension_for_metric(&area.covered, metric), total)])
                .collect(),
        );
    }
    let widths = (0..table[0].len())
        .map(|column| {
            table
                .iter()
                .map(|row| row[column].chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect::<Vec<_>>();
    let label = filter_label(request);
    let mut lines = vec![format!(
        "Coverage by directory, {} deep{}",
        data.depth,
        if label.is_empty() {
            String::new()
        } else {
            format!(" — {label}")
        }
    )];
    lines.push(String::new());
    lines.extend(table.iter().map(|row| {
        row.iter()
            .enumerate()
            .map(|(column, cell)| {
                if column == 0 {
                    format!("{cell:<width$}", width = widths[column])
                } else {
                    format!("{cell:>width$}", width = widths[column])
                }
            })
            .collect::<Vec<_>>()
            .join("  ")
            .trim_end()
            .to_owned()
    }));
    lines.push(page_label(page));
    let base = format!(
        "{} --group dir{}",
        coverage_command(&data.run, request, "files"),
        request
            .depth
            .map_or_else(String::new, |depth| format!(" --depth {depth}"))
    );
    if let Some(next) = next_page(&base, page) {
        lines.push(format!("next page: {next}"));
    }
    lines.join("\n")
}

fn render_files(
    rows: &[IndexedFileGap],
    request: &IndexedQueryRequest,
    page: &AgentPagination,
    child: &str,
    run: &str,
) -> String {
    let selected = request.kind.is_some() || request.runner.is_some();
    let body = rows
        .iter()
        .map(|gap| {
            let missing = gap.uncovered_lines
                + gap.uncovered_statements
                + gap.uncovered_functions
                + gap.missing_branches
                + gap.missing_mcdc_conditions;
            let status = if missing == 0 {
                "covered in this projection".into()
            } else {
                format!(
                    "uncovered: lines {}  statements {}  functions {}  branch outcomes {}  MC/DC conditions {}",
                    gap.uncovered_lines,
                    gap.uncovered_statements,
                    gap.uncovered_functions,
                    gap.missing_branches,
                    gap.missing_mcdc_conditions,
                )
            };
            let limitations = if gap.measurement_limitations == 0 {
                String::new()
            } else {
                format!(
                    "  measurement limitations {} ({})",
                    gap.measurement_limitations,
                    gap.limitation_kinds.join(", ")
                )
            };
            let provenance = if selected {
                format!(
                    "  [covered elsewhere: {}; nowhere: {}]",
                    gap_dimensions_total(&gap.covered_by_other_tests),
                    gap_dimensions_total(&gap.uncovered_everywhere)
                )
            } else {
                String::new()
            };
            format!("{}\n  {status}{limitations}{provenance}", gap.file)
        })
        .collect::<Vec<_>>()
        .join("\n\n");
    let title = if child == "gaps" {
        "Coverage gaps — only files with unresolved obligations"
    } else {
        "Coverage files — every included source file"
    };
    let label = filter_label(request);
    let projection = if label.is_empty() {
        String::new()
    } else {
        format!(
            "\nProjection: {label}. Uncovered counts are recalculated using only that evidence."
        )
    };
    let body = if page.total == 0 {
        if child == "gaps" {
            "No gaps: every included file is fully covered and measured.".into()
        } else {
            "No source files are included in this run.".into()
        }
    } else {
        body
    };
    let mut output = format!("{title}{projection}\n\n{body}\n\n{}", page_label(page));
    if let Some(inspect) =
        inspect_file_command(run, request, rows.first().map(|row| row.file.as_str()))
    {
        output.push_str(&format!("\n{inspect}"));
    }
    if let Some(next) = next_page(&coverage_command(run, request, child), page) {
        output.push_str(&format!("\nnext page: {next}"));
    }
    output
}

/// What a dimension's percentage leaves out, where it leaves anything out.
///
/// Silence would read as "these numbers describe every test here", and for a
/// Go suite that mixes parallel tests with serial ones they describe only some.
fn unattributed_note(entry: &IndexedDimensionCoverage) -> String {
    let unattributed = entry.tests.saturating_sub(entry.attributed);
    if unattributed == 0 {
        String::new()
    } else {
        format!(" ({unattributed} not attributable)")
    }
}

/// How completely the run could credit each test with what it reached.
///
/// Here whether or not anything is wrong, the way `Instrumentation` is: a
/// reader who only ever sees "Exact for every test" has still learned that the
/// question exists, and will recognise the other answer when a suite starts
/// running its tests at once.
fn attribution_line(counts: &supercov_engine::coverage_query::TestAttributionCounts) -> String {
    let total = counts.total();
    if total == 0 {
        return "No test recorded coverage".into();
    }
    if counts.exact == total {
        return format!("Exact for {} test(s)", count(total));
    }
    let mut parts = Vec::new();
    if counts.exact > 0 {
        parts.push(format!("{} exact", count(counts.exact)));
    }
    if counts.partial > 0 {
        // Ruby records a line for the first test that reaches it, so a later
        // test running the same line is credited with none of it.
        parts.push(format!("{} a lower bound", count(counts.partial)));
    }
    if counts.run_wide > 0 {
        parts.push(format!("{} counted run-wide", count(counts.run_wide)));
    }
    let detail = parts.join(", ");
    // The offer belongs only where it would change the answer. Running the
    // suite in order is what buys back a run-wide credit; it buys nothing for
    // a lower bound, which is how the language reports coverage at all.
    if counts.run_wide > 0 {
        format!(
            "{detail} — `--exact-attribution` credits them individually, running your suite in order"
        )
    } else {
        detail
    }
}

fn render_dimension(
    values: &[IndexedDimensionCoverage],
    request: &IndexedQueryRequest,
    page: &AgentPagination,
    child: &str,
    run: &str,
) -> String {
    let body = values
        .iter()
        .map(|entry| {
            let name = entry
                .kind
                .as_deref()
                .or(entry.runner.as_deref())
                .unwrap_or("unknown");
            let setups = if entry.setups == 0 {
                String::new()
            } else {
                format!(" + {} setup scope(s)", entry.setups)
            };
            // A percentage here describes the tests that have coverage of
            // their own. Where none of them do, there is no percentage to
            // print: the tests ran and reached real code, and what they
            // reached is in the run's totals rather than in theirs.
            if entry.tests > 0 && entry.attributed == 0 {
                return format!(
                    "{name}  {} test(s){setups}  coverage not attributable; counted run-wide",
                    entry.tests
                );
            }
            format!(
                "{name}  {} test(s){}{setups}  lines {}  branches {}  MC/DC {}",
                entry.tests,
                unattributed_note(entry),
                share(entry.summary.lines.percentage, entry.summary.lines.total),
                share(
                    entry.summary.branches.percentage,
                    entry.summary.branches.total
                ),
                share(
                    entry.summary.condition_coverage_pct,
                    entry.summary.conditions
                ),
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    let mut output = format!("{body}\n{}", page_label(page));
    if let Some(next) = next_page(&coverage_command(run, request, child), page) {
        output.push_str(&format!("\nnext page: {next}"));
    }
    output
}

fn vector_text(vector: &McdcVector) -> String {
    format!(
        "{} -> {}",
        vector
            .values
            .iter()
            .map(|value| match value {
                None => '-',
                Some(true) => 'T',
                Some(false) => 'F',
            })
            .collect::<String>(),
        if vector.outcome { 'T' } else { 'F' }
    )
}

fn branch_need(value: &str) -> String {
    match value {
        "default evaluated" => "default-value branch not observed".into(),
        "value provided" => "explicit-value branch not observed".into(),
        "no matching case" => "switch no-match outcome not observed".into(),
        "try completed without catch" => "try-success outcome not observed".into(),
        "catch entered" => "catch outcome not observed".into(),
        "zero iterations" => "zero-iteration outcome not observed".into(),
        "one or more iterations" => "entered-loop outcome not observed".into(),
        "nullish / short-circuited" => "nullish short-circuit outcome not observed".into(),
        "non-nullish / continued" => "non-nullish continuation outcome not observed".into(),
        "assignment skipped" => "assignment-skipped outcome not observed".into(),
        "right evaluated / assigned" => "right-evaluated assignment outcome not observed".into(),
        "short-circuit / left selected" => {
            "left-selected short-circuit outcome not observed".into()
        }
        "right evaluated / selected" => "right-selected outcome not observed".into(),
        "true" => "decision never true".into(),
        "false" => "decision never false".into(),
        other => format!("branch outcome not observed: {other}"),
    }
}

fn render_needed_obligation(obligation: &CoverageFileObligation) -> String {
    match obligation {
        CoverageFileObligation::Line(_) => "line not executed".into(),
        CoverageFileObligation::Point(item) if item.kind == "statement" => {
            "statement not executed".into()
        }
        CoverageFileObligation::Point(item) if item.kind == "function" => {
            "function not called".into()
        }
        CoverageFileObligation::Point(item) => format!("{} not covered", item.kind),
        CoverageFileObligation::Branch(item) => branch_need(&item.missing),
        CoverageFileObligation::Mcdc(item) => format!(
            "no witness pair shows `{}` independently changing the decision result",
            item.missing_condition
        ),
    }
}

fn file_gap_needs<'a>(
    state: &str,
    obligations: impl IntoIterator<Item = &'a CoverageFileObligation>,
) -> Vec<String> {
    obligations
        .into_iter()
        .filter(|obligation| {
            state != "missing"
                || match obligation {
                    CoverageFileObligation::Line(_) => false,
                    CoverageFileObligation::Point(item) if item.kind == "statement" => false,
                    _ => true,
                }
        })
        .map(render_needed_obligation)
        .collect()
}

/// The saved assessment's word on a file, beside its coverage: nothing when
/// the run has not been assessed or the file has no assessed statement.
fn file_assertion_lines(assertions: Option<&serde_json::Value>) -> Vec<String> {
    let Some(a) = assertions.filter(|a| a["available"] == true) else {
        return Vec::new();
    };
    let statements = a["statements"].as_u64().unwrap_or(0);
    if statements == 0 {
        return Vec::new();
    }
    let mut lines = vec![
        String::new(),
        format!(
            "Assertions  {}% ({}/{statements} statements a test is judged to catch)",
            a["percentage"].as_f64().unwrap_or(0.0),
            a["asserted"]
        ),
    ];
    let not = a["notAssertedLines"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(serde_json::Value::as_u64)
        .collect::<Vec<_>>();
    if !not.is_empty() {
        let shown = not
            .iter()
            .take(12)
            .map(u64::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        let more = if not.len() > 12 {
            format!(" and {} more", not.len() - 12)
        } else {
            String::new()
        };
        lines.push(format!("  Not asserted on line(s) {shown}{more}"));
        lines.push(format!(
            "  Inspect: {}",
            a["inspect"].as_str().unwrap_or("")
        ));
    }
    lines
}

/// The saved assessment's word on the statements of one line.
fn line_assertion_lines(assertions: Option<&serde_json::Value>) -> Vec<String> {
    let Some(a) = assertions.filter(|a| a["available"] == true) else {
        return Vec::new();
    };
    let statements = a["statements"].as_array().cloned().unwrap_or_default();
    if statements.is_empty() {
        return Vec::new();
    }
    let mut lines = vec![String::new(), "Assertions".into()];
    for statement in &statements {
        let test = statement["test"]["name"].as_str().unwrap_or("no test");
        let likely = statement["answer"]
            .as_f64()
            .map(|p| format!(", {:.0}% likely to fail", p * 100.0))
            .unwrap_or_default();
        lines.push(if statement["asserted"] == true {
            format!(
                "  Asserted: `{}`; {test} is judged to fail if it changes ({}{likely})",
                statement["text"].as_str().unwrap_or(""),
                statement["change"].as_str().unwrap_or("")
            )
        } else {
            format!(
                "  Not asserted: `{}`; no test that runs it is judged to fail if it changes ({}); closest: {test}{likely}",
                statement["text"].as_str().unwrap_or(""),
                statement["change"].as_str().unwrap_or("")
            )
        });
    }
    lines.push(format!(
        "  Inspect: {}",
        a["inspect"].as_str().unwrap_or("")
    ));
    lines
}

fn state_label(state: &str) -> &'static str {
    match state {
        "missing" => "NOT COVERED",
        "part" => "PARTIAL",
        "limited" => "NOT MEASURED",
        _ => "UNKNOWN",
    }
}

fn confidence_label(level: &str) -> &str {
    match level {
        "asserted" => "linked to a passing assertion",
        "action" => "linked to a test action",
        "executed" => "execution only",
        "unexecuted" => "not executed",
        other => other,
    }
}

fn title_case_kind(kind: &str) -> String {
    let mut characters = kind.chars();
    characters.next().map_or_else(String::new, |first| {
        first.to_uppercase().collect::<String>() + characters.as_str()
    })
}

fn render_anchor(anchor: &supercov_engine::coverage_query::CoverageAnchor) -> Vec<String> {
    let coverage = anchor.conditions.map_or_else(
        || {
            if anchor.covered {
                "covered".into()
            } else {
                "not covered".into()
            }
        },
        |conditions| {
            format!(
                "{}/{} MC/DC conditions covered",
                anchor.covered_conditions.unwrap_or(0),
                conditions
            )
        },
    );
    let mut lines = vec![format!(
        "  {} at column {} — {coverage} ({} covering test{})",
        title_case_kind(&anchor.kind),
        anchor.column,
        count(anchor.covering_tests),
        if anchor.covering_tests == 1 { "" } else { "s" }
    )];
    if let Some(source) = &anchor.source {
        lines.push(format!("    `{source}`"));
    }
    if !anchor.covered
        && let Some(missing) = &anchor.missing
    {
        lines.push(format!("    Unobserved: {missing}"));
    }
    lines
}

fn push_line_pagination(
    lines: &mut Vec<String>,
    page: &AgentPagination,
    categories: &str,
    next: Option<String>,
) {
    if page.offset > 0 || page.total > page.returned {
        lines.push(format!("{} per category ({categories})", page_label(page)));
    }
    if let Some(next) = next {
        lines.push(format!("next page: {next}"));
    }
}

fn render_coverage(request: &IndexedQueryRequest, output: &IndexedQueryOutput) -> String {
    let page = output.pagination.as_ref();
    match &output.data {
        IndexedQueryData::Summary(data) => {
            let label = filter_label(request);
            let mut first = format!("run {}", data.run);
            if !label.is_empty() {
                first.push_str(&format!(" ({label})"));
            }
            if data.stale {
                first.push_str(&format!(" [STALE: {}]", data.stale_reasons.join(", ")));
            }
            let measurement = if data.measurement.complete {
                if data.measurement.declared == 0 {
                    "Complete for the measured command and coverage model".into()
                } else {
                    // Nothing inside the denominator went unmeasured; what is
                    // declared is what the denominator excludes.
                    format!(
                        "Complete for the measured command and coverage model — {} declared boundary(ies) in {} file(s)",
                        data.measurement.declared, data.measurement.files
                    )
                }
            } else {
                if data.measurement.files > 0 {
                    format!(
                        "Incomplete — {} blocking limitation(s) in {} file(s)",
                        data.measurement.blocking, data.measurement.files
                    )
                } else {
                    format!(
                        "Incomplete — {} blocking transport or run limitation(s)",
                        data.measurement.blocking
                    )
                }
            };
            let coverage_heading = if data.valid {
                "Coverage"
            } else {
                "Coverage (diagnostic — the wrapped command did not pass)"
            };
            let mut lines = vec![first];
            if !data.command.is_empty() {
                lines.push(format!("command: {}", data.command.join(" ")));
            }
            if !data.valid {
                // Calm but unmissable: the run itself is fine, the wrapped
                // command failed, so the numbers below cannot gate anything.
                lines.push(match data.test_exit_code {
                    Some(code) => format!(
                        "status: wrapped command exited {code} — coverage below is diagnostic and cannot gate"
                    ),
                    None => "status: wrapped command exit status unavailable — coverage below is diagnostic and cannot gate".into(),
                });
            }
            lines.extend([
                String::new(),
                coverage_heading.into(),
                format!(
                    "  Lines      {}",
                    measured(
                        data.coverage.lines.percentage,
                        data.coverage.lines.covered as u64,
                        data.coverage.lines.total as u64
                    )
                ),
                format!(
                    "  Branches   {}",
                    measured(
                        data.coverage.branches.percentage,
                        data.coverage.branches.covered as u64,
                        data.coverage.branches.total as u64
                    )
                ),
                format!(
                    "  MC/DC      {}",
                    measured(
                        data.coverage.condition_coverage_pct,
                        data.coverage.covered_conditions as u64,
                        data.coverage.conditions as u64
                    )
                ),
            ]);
            if let Some(assertions) = &data.assertion_coverage {
                lines.extend(assertion_summary_lines(assertions));
            }
            if data.coverage_by_kind.iter().any(|kind| kind.tests > 0) {
                lines.extend([String::new(), "By test kind".into()]);
                for kind in data.coverage_by_kind.iter().filter(|kind| kind.tests > 0) {
                    if kind.attributed == 0 {
                        lines.push(format!(
                            "  {:<12} {:>4} test(s)  coverage not attributable; counted run-wide",
                            kind.kind.as_deref().unwrap_or("unknown"),
                            kind.tests,
                        ));
                        continue;
                    }
                    lines.push(format!(
                        "  {:<12} {:>4} test(s)  lines {:>7}  branches {:>7}  MC/DC {:>7}{}",
                        kind.kind.as_deref().unwrap_or("unknown"),
                        kind.tests,
                        share(kind.summary.lines.percentage, kind.summary.lines.total),
                        share(
                            kind.summary.branches.percentage,
                            kind.summary.branches.total
                        ),
                        share(kind.summary.condition_coverage_pct, kind.summary.conditions),
                        unattributed_note(kind),
                    ));
                }
                // One kind of test at 35.83% under a run total of 41.58%
                // read as two answers to one question. The rest ran while no
                // test was running, and the rows now say so.
                if let Some(tests) = &data.coverage_by_tests {
                    let outside = [
                        (
                            data.coverage.lines.covered,
                            tests.lines.covered,
                            data.coverage.lines.total,
                        ),
                        (
                            data.coverage.branches.covered,
                            tests.branches.covered,
                            data.coverage.branches.total,
                        ),
                        (
                            data.coverage.covered_conditions,
                            tests.covered_conditions,
                            data.coverage.conditions,
                        ),
                    ]
                    .map(|(all, tested, total)| (all.saturating_sub(tested), total));
                    if outside.iter().any(|(only, _)| *only > 0) {
                        let [lines_only, branches_only, conditions_only] =
                            outside.map(|(only, total)| {
                                share(
                                    if total == 0 {
                                        0.0
                                    } else {
                                        only as f64 * 100.0 / total as f64
                                    },
                                    total,
                                )
                            });
                        lines.push(format!(
                            "  {:<12} {:>4}          lines {:>7}  branches {:>7}  MC/DC {:>7}",
                            "no test", "", lines_only, branches_only, conditions_only,
                        ));
                        lines.push("  \"no test\" is code that ran only while no test was running: start-up and setup, module loading, work between tests. It counts in the run's total and in no test's.".into());
                    }
                }
                if let Some(defaults) = data
                    .test_kind_sources
                    .get("runner-default")
                    .filter(|n| **n > 0)
                {
                    lines.push(format!("  {defaults} test(s) use the runner's default kind; this is not inferred from their behavior."));
                    lines.push("  Set SUPERCOV_TEST_KIND=integration (or unit/component/e2e) when running a suite to override it.".into());
                }
            }
            if let Some(context) = &data.e2e_gap_context {
                let share = if data.coverage.lines.covered == 0 {
                    0.0
                } else {
                    context.covered_elsewhere.lines as f64 * 100.0
                        / data.coverage.lines.covered as f64
                };
                lines.extend([
                    String::new(),
                    "E2E gap context".into(),
                    format!(
                        "  Other test kinds only  {} lines ({} of all covered lines)",
                        count(context.covered_elsewhere.lines),
                        percentage(share),
                    ),
                    format!(
                        "  Uncovered everywhere   {} lines",
                        count(context.uncovered_everywhere.lines),
                    ),
                    format!(
                        "  Other kinds            {}",
                        context.other_kinds.join(", ")
                    ),
                    format!(
                        "  Inspect                {}",
                        coverage_command(&data.run, request, "gaps --kind e2e")
                    ),
                ]);
            }
            lines.extend([
                String::new(),
                "Measurement".into(),
                format!("  Instrumentation  {measurement}"),
            ]);
            // "89 blocking limitation(s) in 89 file(s)" did not say that 79
            // of them were one directory, or what would settle them.
            if let Some(unclassified) = &data.unclassified_source {
                const SHOWN: usize = 4;
                let mut places = unclassified
                    .directories
                    .iter()
                    .take(SHOWN)
                    .map(|place| {
                        let name = if place.directory == "." {
                            "the top level"
                        } else {
                            &place.directory
                        };
                        format!("{name} {}", count(place.files))
                    })
                    .collect::<Vec<_>>();
                if unclassified.directories.len() > SHOWN {
                    places.push(format!(
                        "{} elsewhere",
                        count(
                            unclassified.directories[SHOWN..]
                                .iter()
                                .map(|place| place.files)
                                .sum()
                        )
                    ));
                }
                lines.push(format!(
                    "                   Unclassified source: {}",
                    places.join(", ")
                ));
                lines.push(format!(
                    "                   {}",
                    source_roots_hint(unclassified)
                ));
            }
            lines.extend([
                format!("  Attribution      {}", attribution_line(&data.test_attribution)),
                "  Scope            Only code reached by the wrapped command is observed; this status does not prove every project test suite was run.".into(),
            ]);
            if let Some(guests) = data
                .transport
                .as_ref()
                .map(|transport| transport.guest_processes)
                .filter(|guests| *guests > 0)
            {
                lines.push(format!(
                    "  Guests           {guests} process(es) ran the workspace in a container or VM without Supercov's settings; their coverage counts for the run, credited to no test"
                ));
            }
            if let Some(workspace) = &data.workspace {
                lines.push(format!("  Command outputs  {workspace}"));
            }
            lines.extend([String::new(), "Tests".into()]);
            lines.push(format!("  Total       {}", count(data.tests)));
            lines.extend(outcome_lines(&data.test_outcomes));
            if data.setups > 0 {
                lines.push(format!("  Setup scopes {}", count(data.setups)));
            }
            lines.extend([
                String::new(),
                "Remaining".into(),
                format!(
                    "  Files with uncovered code         {}",
                    count(data.files_with_coverage_gaps)
                ),
                format!(
                    "  Files with measurement limits     {}",
                    count(data.files_with_measurement_limitations)
                ),
            ]);
            if !data.diagnostics.is_empty() {
                lines.extend([String::new(), "Warnings".into()]);
                for diagnostic in &data.diagnostics {
                    lines.extend(diagnostic_lines(diagnostic));
                }
            }
            if !data.hints.is_empty() {
                lines.extend([String::new(), "Hints".into()]);
                lines.extend(data.hints.iter().map(|hint| format!("  {hint}")));
            }
            lines.extend([
                String::new(),
                "Commands".into(),
                format!("  {}", coverage_command(&data.run, request, "files")),
                format!("  {}", coverage_command(&data.run, request, "gaps")),
                format!("  {}", coverage_command(&data.run, request, "kinds")),
                format!("  {}", coverage_command(&data.run, request, "runners")),
                format!("  {}", coverage_command(&data.run, request, "scope")),
                format!("  {} runs {} --help", crate::launcher_command(), data.run),
            ]);
            lines.join("\n")
        }
        IndexedQueryData::Areas(data) => {
            render_areas(data, request, page.expect("areas are paginated"))
        }
        IndexedQueryData::Files(data) => render_files(
            &data.files,
            request,
            page.expect("files are paginated"),
            "files",
            &data.run,
        ),
        IndexedQueryData::Gaps(data) => render_files(
            &data.gaps,
            request,
            page.expect("gaps are paginated"),
            "gaps",
            &data.run,
        ),
        IndexedQueryData::Kinds(data) => render_dimension(
            &data.kinds,
            request,
            page.expect("kinds are paginated"),
            "kinds",
            &data.run,
        ),
        IndexedQueryData::Runners(data) => render_dimension(
            &data.runners,
            request,
            page.expect("runners are paginated"),
            "runners",
            &data.run,
        ),
        IndexedQueryData::Scope(data) => {
            let page = page.expect("scope is paginated");
            let mut lines = vec![format!(
                "{} scope; language {}; model {}",
                data.kind, data.language, data.model
            )];
            if let Some(mode) = &data.mode {
                lines.push(format!(
                    "mode {}; roots {}; included {}, excluded {}, ambiguous {}",
                    mode,
                    if data.roots.is_empty() {
                        "none".into()
                    } else {
                        data.roots.join(", ")
                    },
                    data.counts.included,
                    data.counts.excluded,
                    data.counts.ambiguous,
                ));
            }
            if let Some(unit) = &data.unit {
                lines.push(format!("unit {unit}"));
            }
            if let Some(complete) = data.measurement_complete {
                lines.push(format!(
                    "frontend measurement {}",
                    if complete { "complete" } else { "incomplete" }
                ));
            }
            lines.push(format!(
                "measurement {}",
                if data.measurement.complete {
                    if data.measurement.declared == 0 {
                        "complete".into()
                    } else {
                        format!(
                            "complete, {} declared boundary(ies)",
                            data.measurement.declared
                        )
                    }
                } else {
                    format!("{} blocking limitation(s)", data.measurement.blocking)
                }
            ));
            if request.group.as_deref() != Some("file") {
                lines.push(String::new());
                lines.extend(scope_group_lines(&data.groups));
                if let Some(unclassified) = &data.unclassified_source {
                    lines.push(String::new());
                    lines.push(source_roots_hint(unclassified));
                }
                lines.push(String::new());
                lines.push(format!(
                    "File by file: {} --files",
                    coverage_command(&data.run, request, "scope")
                ));
                return lines.join("\n");
            }
            lines.extend(data.entries.iter().map(|entry| {
                format!(
                    "{}  {}  {}{}{}",
                    entry.status.to_uppercase(),
                    entry.file,
                    entry.reason,
                    if entry.measurement_limitations == 0 {
                        String::new()
                    } else {
                        format!(
                            "  [measurement limitations: {} {}]",
                            entry.measurement_limitations,
                            entry.limitation_kinds.join(", ")
                        )
                    },
                    entry
                        .package_root
                        .as_ref()
                        .map_or_else(String::new, |root| format!("  [package {root}]"))
                )
            }));
            lines.push(page_label(page));
            if let Some(next) = next_page(
                &format!("{} --files", coverage_command(&data.run, request, "scope")),
                page,
            ) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
        IndexedQueryData::FileDecisions(data) => {
            let page = page.expect("file decisions are paginated");
            let mut lines = vec![
                format!("{}  MC/DC by decision", data.file),
                format!(
                    "decisions {}, with missing conditions {}; conditions missing {}/{}",
                    data.totals.decisions,
                    data.totals.decisions_with_missing_conditions,
                    data.totals.missing_conditions,
                    data.totals.conditions,
                ),
            ];
            lines.extend(data.decisions.iter().map(|row| {
                let compact = row.source.split_whitespace().collect::<Vec<_>>().join(" ");
                let snippet = if compact.chars().count() > 96 {
                    format!("{}…", compact.chars().take(95).collect::<String>())
                } else {
                    compact
                };
                format!(
                    "{}:{}  [{}]  missing {}/{}  {snippet}",
                    row.line, row.column, row.id, row.missing_conditions, row.conditions,
                )
            }));
            if data.decisions.is_empty() {
                lines.push(String::new());
            }
            lines.push(format!(
                "{} decisions with missing conditions",
                page_label(page)
            ));
            let mut base = format!(
                "{} {} --group decision",
                coverage_command(&data.run, request, "file"),
                shell_quote(&data.file)
            );
            if data.sort != DecisionSort::Location {
                base.push_str(" --sort missing");
            }
            if let Some(next) = next_page(&base, page) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
        IndexedQueryData::FileDetail(data) => {
            let page = page.expect("file detail is paginated");
            let mut lines = vec![
                data.file.clone(),
                String::new(),
                "Uncovered".into(),
                format!(
                    "  Lines not executed              {}",
                    count(data.counts.uncovered_lines)
                ),
                format!(
                    "  Statements not executed         {}",
                    count(data.counts.uncovered_statements)
                ),
                format!(
                    "  Functions not called            {}",
                    count(data.counts.uncovered_functions)
                ),
                format!(
                    "  Branch outcomes not taken       {}",
                    count(data.counts.missing_branches)
                ),
                format!(
                    "  MC/DC conditions not shown      {}",
                    count(data.counts.missing_mcdc_conditions)
                ),
                format!(
                    "  Measurement limitations         {}",
                    count(data.counts.measurement_limitations)
                ),
                String::new(),
                format!("Tests touching this file: {}", count(data.total_tests)),
                String::new(),
                "Gaps".into(),
                format!(
                    "  NOT COVERED = line never executed; PARTIAL = line executed but some behavior remains untested{}",
                    if data.gap_lines.iter().any(|gap| gap.state == "limited") {
                        "; NOT MEASURED = no record of the line, for the reason given"
                    } else {
                        ""
                    }
                ),
            ];
            if page.total == 0 {
                lines.truncate(lines.len() - 1);
                lines.push("  No gap lines: every line is covered and measured.".into());
            } else {
                lines.push(" LINE  STATUS        SOURCE".into());
            }
            if let Some(at) = lines
                .iter()
                .position(|line| line.starts_with("Tests touching this file"))
            {
                let assertions = file_assertion_lines(data.assertions.as_ref());
                lines.splice(at + 1..at + 1, assertions);
            }
            for gap in &data.gap_lines {
                lines.push(format!(
                    "{:>5}  {:<12}  {}",
                    gap.line,
                    state_label(&gap.state),
                    gap.source.as_deref().unwrap_or("(source unavailable)")
                ));
                let needs = file_gap_needs(&gap.state, &gap.obligations);
                for need in needs {
                    lines.push(format!("       Unobserved: {need}"));
                }
                for limitation in &gap.limitations {
                    lines.push(format!("       Cannot measure: {}", limitation.reason));
                }
                if gap.state == "part" {
                    let selector = format!("{}:{}", data.file, gap.line);
                    lines.push(format!(
                        "       Inspect: {} {}",
                        coverage_command(&data.run, request, "line"),
                        shell_quote(&selector)
                    ));
                }
            }
            lines.push(format!("{} gap lines", page_label(page)));
            let base = format!(
                "{} {}",
                coverage_command(&data.run, request, "file"),
                shell_quote(&data.file)
            );
            if let Some(next) = next_page(&base, page) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
        IndexedQueryData::Decision(data) => {
            let page = page.expect("decision is paginated");
            match data.as_ref() {
                CoverageDecisionData::Matches(data) => {
                    let mut lines = data
                        .decisions
                        .iter()
                        .map(|decision| {
                            format!(
                                "{}  {}:{}:{}  {}",
                                decision.id,
                                decision.file,
                                decision.line,
                                decision.column,
                                decision.source
                            )
                        })
                        .collect::<Vec<_>>();
                    lines.push(format!("{} matching decisions", page_label(page)));
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "decision"),
                        shell_quote(request.selector.as_deref().unwrap_or_default())
                    );
                    if let Some(next) = next_page(&base, page) {
                        lines.push(format!("next page: {next}"));
                    }
                    lines.join("\n")
                }
                CoverageDecisionData::Detail(data) => {
                    let mut decisions = Vec::new();
                    for decision in &data.decisions {
                        let mut lines = vec![
                            format!(
                                "{}  {}:{}:{}",
                                decision.meta.id,
                                decision.meta.file,
                                decision.meta.line,
                                decision.meta.column
                            ),
                            decision.meta.source.clone(),
                        ];
                        lines.extend(decision.conditions.iter().map(|condition| {
                            format!(
                                "C{} {}: {}",
                                condition.index + 1,
                                if condition.covered {
                                    "covered"
                                } else {
                                    "MISSING"
                                },
                                condition.source,
                            )
                        }));
                        lines.push(format!("confidence {}", decision.confidence.level));
                        lines.push("vectors:".into());
                        if decision.vector_observations.is_empty() {
                            lines.push("  none".into());
                        } else {
                            lines.extend(decision.vector_observations.iter().map(|observation| {
                                format!(
                                    "  {}  tests={} confidence={}",
                                    vector_text(&observation.vector),
                                    observation.tests.len(),
                                    observation.confidence.level
                                )
                            }));
                        }
                        decisions.push(lines.join("\n"));
                    }
                    let mut output = decisions.join("\n\n");
                    output.push_str(&format!(
                        "\n{} conditions/vectors/tests per decision",
                        page_label(page)
                    ));
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "decision"),
                        shell_quote(request.selector.as_deref().unwrap_or_default())
                    );
                    if let Some(next) = next_page(&base, page) {
                        output.push_str(&format!("\nnext page: {next}"));
                    }
                    output
                }
            }
        }
        IndexedQueryData::Line(data) => {
            let page = page.expect("line is paginated");
            match data.as_ref() {
                CoverageCoversData::Anchors(data) => {
                    let complete = data.covered_anchored;
                    // A line nothing measured is not measured, whatever
                    // limitation says why.
                    let state = if data.total_anchored == 0 && data.total_remaining == 0 {
                        "NOT MEASURED"
                    } else if data.total_tests == 0
                        && complete == 0
                        && data.total_anchored > 0
                        && data.total_limitations == 0
                    {
                        // Nothing anchored on the line was observed, by a test
                        // or in the background: it never ran.
                        "NOT COVERED"
                    } else if complete == data.total_anchored
                        && data.total_limitations == 0
                        && data.total_remaining == 0
                    {
                        "COVERED"
                    } else {
                        "PARTIAL"
                    };
                    let mut lines = vec![
                        format!("{}:{}", data.location.file, data.location.line),
                        String::new(),
                        "Source".into(),
                        format!(
                            "  {:>5} | {}",
                            data.location.line,
                            data.source
                                .as_deref()
                                .unwrap_or("(source unavailable in this run)")
                        ),
                        String::new(),
                        "Status".into(),
                        format!("  {state}"),
                    ];
                    if let Some(origin) = &data.source_origin {
                        lines.insert(
                            4,
                            if origin == "working-tree-stale" {
                                "  (read from the working tree, which changed since this run)"
                                    .into()
                            } else {
                                "  (read from the current working tree)".into()
                            },
                        );
                    }
                    if !data.remaining.is_empty() {
                        lines.extend([String::new(), "Unobserved coverage".into()]);
                        lines.extend(data.remaining.iter().map(|obligation| {
                            format!("  - {}", render_needed_obligation(obligation))
                        }));
                    }
                    if !data.anchored.is_empty() {
                        lines.extend([String::new(), "Coverage details".into()]);
                        for anchor in &data.anchored {
                            lines.extend(render_anchor(anchor));
                        }
                    }
                    if !data.limitations.is_empty() {
                        lines.extend([String::new(), "Measurement limits".into()]);
                        lines.extend(data.limitations.iter().map(|limitation| {
                            format!("  - {}: {}", limitation.kind, limitation.reason)
                        }));
                    }
                    lines.extend(line_assertion_lines(data.assertions.as_ref()));
                    lines.extend([String::new(), "Covering tests".into()]);
                    if data.tests.is_empty() {
                        lines.push("  None".into());
                    } else {
                        lines.extend(data.tests.iter().map(|test| {
                            format!(
                                "  {} [{}] — {}/{}",
                                test.name, test.id, test.provenance.kind, test.provenance.runner
                            )
                        }));
                    }
                    let selector = format!("{}:{}", data.location.file, data.location.line);
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "line"),
                        shell_quote(&selector)
                    );
                    push_line_pagination(
                        &mut lines,
                        page,
                        "tests/obligations/limitations",
                        next_page(&base, page),
                    );
                    lines.join("\n")
                }
                CoverageCoversData::Line(data) => {
                    let complete = data.covered_anchored;
                    let state = if !data.covered {
                        "NOT COVERED"
                    } else if complete < data.total_anchored
                        || data.total_limitations > 0
                        || data.total_remaining > 0
                    {
                        "PARTIAL"
                    } else {
                        "COVERED"
                    };
                    let mut lines = vec![
                        format!("{}:{}", data.location.file, data.location.line),
                        String::new(),
                        "Source".into(),
                        format!(
                            "  {:>5} | {}",
                            data.location.line,
                            data.source
                                .as_deref()
                                .unwrap_or("(source unavailable in this run)")
                        ),
                        String::new(),
                        "Status".into(),
                        format!("  {state}"),
                        format!(
                            "  Evidence: {}{}",
                            confidence_label(&data.confidence.level),
                            if data.confidence.e2e {
                                " through E2E"
                            } else {
                                ""
                            }
                        ),
                    ];
                    if let Some(origin) = &data.source_origin {
                        lines.insert(
                            4,
                            if origin == "working-tree-stale" {
                                "  (read from the working tree, which changed since this run)"
                                    .into()
                            } else {
                                "  (read from the current working tree)".into()
                            },
                        );
                    }
                    if !data.remaining.is_empty() {
                        lines.extend([String::new(), "Unobserved coverage".into()]);
                        lines.extend(data.remaining.iter().map(|obligation| {
                            format!("  - {}", render_needed_obligation(obligation))
                        }));
                    }
                    if !data.anchored.is_empty() {
                        lines.extend([String::new(), "Coverage details".into()]);
                        for anchor in &data.anchored {
                            lines.extend(render_anchor(anchor));
                        }
                    }
                    if !data.limitations.is_empty() {
                        lines.extend([String::new(), "Measurement limits".into()]);
                        lines.extend(data.limitations.iter().map(|limitation| {
                            format!("  - {}: {}", limitation.kind, limitation.reason)
                        }));
                    }
                    lines.extend(line_assertion_lines(data.assertions.as_ref()));
                    lines.extend([String::new(), "Covering tests".into()]);
                    if data.tests.is_empty() {
                        lines.push("  None".into());
                    } else {
                        lines.extend(data.tests.iter().map(|test| {
                            format!(
                                "  {} [{}] — {}/{}",
                                test.name, test.id, test.provenance.kind, test.provenance.runner
                            )
                        }));
                    }
                    if !data.phases.is_empty() {
                        lines.extend([String::new(), "Test phases".into()]);
                        lines.extend(data.phases.iter().map(|phase| {
                            format!(
                                "  {}{}{}",
                                phase.operation,
                                phase
                                    .status
                                    .as_ref()
                                    .map_or_else(String::new, |status| format!(" ({status})")),
                                phase
                                    .source
                                    .as_ref()
                                    .map_or_else(String::new, |source| format!(" at {source}"))
                            )
                        }));
                    }
                    let selector = format!("{}:{}", data.location.file, data.location.line);
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "line"),
                        shell_quote(&selector)
                    );
                    push_line_pagination(
                        &mut lines,
                        page,
                        "tests/phases/obligations/limitations",
                        next_page(&base, page),
                    );
                    lines.join("\n")
                }
            }
        }
        IndexedQueryData::Test(data) => {
            let page = page.expect("test is paginated");
            match data.as_ref() {
                CoverageTestData::Matches(data) => {
                    let mut lines = data
                        .tests
                        .iter()
                        .map(|test| format!("{} [{}] — {}", test.name, test.id, test.outcome))
                        .collect::<Vec<_>>();
                    lines.push(format!("{} matching tests", page_label(page)));
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "test"),
                        shell_quote(request.selector.as_deref().unwrap_or_default())
                    );
                    if let Some(next) = next_page(&base, page) {
                        lines.push(format!("next page: {next}"));
                    }
                    lines.join("\n")
                }
                CoverageTestData::Detail(data) => {
                    let test = data.tests.first().expect("test detail contains one test");
                    let mut lines = vec![
                        test.name.clone(),
                        format!(
                            "outcome {}{}",
                            test.outcome,
                            if test.attempts.is_empty() {
                                String::new()
                            } else {
                                format!(
                                    "; {}",
                                    test.attempts
                                        .iter()
                                        .map(|attempt| format!(
                                            "retry {}={}",
                                            attempt.retry, attempt.status
                                        ))
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                )
                            }
                        ),
                        // Zero here means two different things, and only one
                        // of them is "this test reached nothing". A Go test
                        // that called t.Parallel() stores into the same probe
                        // array as the tests beside it, so what it reached was
                        // recorded against the run: reporting that as a test
                        // covering nothing would be a wrong number, and
                        // reporting nothing at all is what used to answer
                        // "Test not found" for a test that had just passed.
                        if test.attribution == "run-wide" {
                            "coverage not attributable to this test; it ran alongside others and what it reached is recorded run-wide".into()
                        } else if test.attribution == "partial" {
                            // The numbers are real and they are not all of it.
                            // Ruby credits a line to the first test that runs
                            // it, so a later test that runs the same line is
                            // recorded against none of it.
                            format!(
                                "at least {} lines, {} hits, {} decisions, {} phases (a line already recorded for an earlier test is not recorded again)",
                                test.totals.lines,
                                test.totals.hits,
                                test.totals.decisions,
                                test.totals.phases
                            )
                        } else {
                            format!(
                                "{} lines, {} hits, {} decisions, {} phases",
                                test.totals.lines,
                                test.totals.hits,
                                test.totals.decisions,
                                test.totals.phases
                            )
                        },
                    ];
                    lines.extend(
                        test.lines
                            .iter()
                            .map(|line| format!("line: {}:{}", line.file, line.line)),
                    );
                    lines.extend(test.phases.iter().map(|phase| {
                        format!(
                            "{}: {}{}",
                            phase.kind,
                            phase.operation,
                            phase
                                .source
                                .as_ref()
                                .map_or_else(String::new, |source| format!(" at {source}"))
                        )
                    }));
                    lines.push(format!("{} per evidence category", page_label(page)));
                    let base = format!(
                        "{} {}",
                        coverage_command(&data.run, request, "test"),
                        shell_quote(request.selector.as_deref().unwrap_or_default())
                    );
                    if let Some(next) = next_page(&base, page) {
                        lines.push(format!("next page: {next}"));
                    }
                    lines.join("\n")
                }
            }
        }
        IndexedQueryData::Minimize(data) => {
            let page = page.expect("minimize is paginated");
            let target_label = if data.metric == MinimizeMetric::All {
                "coverage across all measured metrics"
            } else {
                metric_name(data.metric)
            };
            let mut lines = vec![
                format!(
                    "exact minimum {}/{} test(s) for {}% {}; explored {} state(s)",
                    data.selected_count,
                    data.total_candidate_tests,
                    number(data.target),
                    target_label,
                    data.explored_states
                ),
                summary_line(&data.summary),
            ];
            lines.extend(data.tests.iter().map(|test| {
                format!(
                    "{}  {}/{}  {}  {}",
                    test.id,
                    test.kind,
                    test.runner,
                    test.file.as_deref().unwrap_or("unknown"),
                    test.name
                )
            }));
            lines.push(page_label(page));
            let base = format!(
                "{} --target {}",
                coverage_command(&data.run, request, "minimize"),
                number(data.target)
            );
            if let Some(next) = next_page(&base, page) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
        IndexedQueryData::Diff(data) => {
            let page = page.expect("diff is paginated");
            let signed = |value: f64| format!("{}{value}", if value >= 0.0 { "+" } else { "" });
            let mut lines = vec![
                format!("{} -> {}", data.older, data.newer),
                format!(
                    "lines {}pp, branches {}pp, MC/DC {}pp",
                    signed(data.delta.lines),
                    signed(data.delta.branches),
                    signed(data.delta.mcdc)
                ),
                format!(
                    "gained: {} lines, {} branches, {} MC/DC conditions",
                    data.gained.line_count, data.gained.branch_count, data.gained.mcdc_count
                ),
                format!(
                    "lost: {} lines, {} branches, {} MC/DC conditions",
                    data.lost.line_count, data.lost.branch_count, data.lost.mcdc_count
                ),
            ];
            let gained = data
                .gained
                .lines
                .iter()
                .map(|line| format!("+ line {line}"))
                .chain(
                    data.gained
                        .branches
                        .iter()
                        .map(|item| format!("+ branch {item}")),
                )
                .chain(
                    data.gained
                        .mcdc
                        .iter()
                        .map(|item| format!("+ MC/DC {item}")),
                )
                .collect::<Vec<_>>();
            if gained.is_empty() {
                lines.push(String::new());
            } else {
                lines.extend(gained);
            }
            lines.push(format!("{} per category", page_label(page)));
            let mut base = format!(
                "{} diff {} {}",
                crate::launcher_command(),
                shell_quote(&data.older),
                shell_quote(&data.newer)
            );
            if request.filter != "all" {
                base.push_str(&format!(" --filter {}", request.filter));
            }
            if let Some(next) = next_page(&base, page) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
    }
}

pub fn render_human(invocation: &PublicQueryInvocation, output: &PublicQueryOutput) -> String {
    match (invocation, output) {
        (
            PublicQueryInvocation::Runs { filter, .. },
            PublicQueryOutput::Runs { data, pagination },
        ) => {
            let id_width = data
                .runs
                .iter()
                .map(|run| run.id.len())
                .max()
                .unwrap_or(2)
                .max(2);
            let mut lines = vec![format!(
                "{:<id_width$}  {:>8}  {:>8}  {:>8}  {}",
                "ID", "LINES", "BRANCH", "MC/DC", "STARTED"
            )];
            lines.extend(data.runs.iter().map(|run| {
                let mut status = Vec::new();
                if let Some(code) = run.test_exit_code {
                    if code != 0 {
                        status.push(format!("FAILED (exit {code})"));
                    }
                } else {
                    status.push("INVALID (exit status unavailable)".into());
                }
                if run.coverage_error.is_some() {
                    status.push("INVALID COVERAGE".into());
                }
                if run.tests == Some(0) {
                    status.push("NO TESTS RAN".into());
                }
                if run.stale == Some(true) {
                    status.push(format!("STALE ({})", run.reasons.join(", ")));
                }
                format!(
                    "{:<id_width$}  {:>8}  {:>8}  {:>8}  {}{}",
                    run.id,
                    optional_percentage(run.lines),
                    optional_percentage(run.branches),
                    optional_percentage(run.mcdc),
                    readable_timestamp(&run.generated_at),
                    if status.is_empty() {
                        String::new()
                    } else {
                        format!("  {}", status.join("; "))
                    }
                )
            }));
            lines.push(page_label(pagination));
            let mut base = format!("{} runs", crate::launcher_command());
            if filter != "all" {
                base.push_str(&format!(" --filter {filter}"));
            }
            if let Some(next) = next_page(&base, pagination) {
                lines.push(format!("next page: {next}"));
            }
            lines.join("\n")
        }
        (
            PublicQueryInvocation::Coverage { request, .. },
            PublicQueryOutput::Coverage { output, .. },
        ) => render_coverage(request, output),
        _ => unreachable!("query execution preserves invocation kind"),
    }
}

fn assertion_summary_lines(value: &serde_json::Value) -> Vec<String> {
    if value["available"] == false {
        return vec![format!(
            "Assertions   not assessed — {}",
            value["assess"]
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| format!(
                    "{} runs latest assertions assess",
                    crate::launcher_command()
                ))
        )];
    }
    let s = &value["summary"];
    match s["percentage"].as_f64() {
        Some(pct) => vec![format!(
            "Assertions   {pct}% ({}/{} executed statements a test is judged to catch)",
            s["asserted"], s["statements"]
        )],
        None => vec!["Assertions   no executed statements to assess".into()],
    }
}

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

    #[test]
    fn assertion_summary_reads_the_assessed_share_or_says_how_to_assess() {
        let report = serde_json::json!({"available":true,"summary":{"statements":4,"asserted":1,"percentage":25.0}});
        assert_eq!(
            assertion_summary_lines(&report),
            vec!["Assertions   25% (1/4 executed statements a test is judged to catch)"]
        );
        let none = serde_json::json!({"available":false,"assess":"npx supercov runs r1 assertions assess"});
        assert_eq!(
            assertion_summary_lines(&none),
            vec!["Assertions   not assessed — npx supercov runs r1 assertions assess"]
        );
    }

    fn request() -> IndexedQueryRequest {
        IndexedQueryRequest {
            run_id: "run_00b780f05c9ae324".into(),
            filter: "all".into(),
            command: "coverage.files".into(),
            metric: MinimizeMetric::All,
            kind: None,
            runner: None,
            file: None,
            line: None,
            selector: None,
            sort: None,
            valid: None,
            test_exit_code: None,
            stale: None,
            stale_reasons: None,
            offset: 0,
            limit: DEFAULT_LIMIT,
            target: None,
            max_states: None,
            group: None,
            depth: None,
        }
    }

    #[test]
    fn file_listing_offers_a_concrete_drill_down_command() {
        assert_eq!(
            inspect_file_command(
                "run_00b780f05c9ae324",
                &request(),
                Some("app/routes/app.articles.$articleId/route.tsx")
            ),
            Some(format!(
                "inspect file: {} runs 'run_00b780f05c9ae324' file 'app/routes/app.articles.$articleId/route.tsx'",
                crate::launcher_command()
            ))
        );
    }

    #[test]
    fn empty_file_listing_does_not_offer_a_drill_down_command() {
        assert_eq!(
            inspect_file_command("run_00b780f05c9ae324", &request(), None),
            None
        );
    }

    #[test]
    fn a_metric_with_nothing_to_measure_is_not_a_percentage() {
        assert_eq!(measured(100.0, 0, 0), "nothing to measure (0/0)");
        assert_eq!(measured(50.0, 1, 2), "50.00% (1/2)");
        assert_eq!(share(100.0, 0), "—");
        assert_eq!(share(100.0, 4), "100.00%");
    }

    #[test]
    fn a_run_without_gaps_says_so_instead_of_an_empty_list() {
        let page = AgentPagination {
            offset: 0,
            limit: DEFAULT_LIMIT,
            returned: 0,
            total: 0,
            has_more: false,
            next_offset: None,
        };
        let text = render_files(&[], &request(), &page, "gaps", "run_00b780f05c9ae324");
        assert!(
            text.contains("\n\nNo gaps: every included file is fully covered and measured.\n\n"),
            "{text}"
        );
    }

    #[test]
    fn counts_are_grouped_for_human_output() {
        assert_eq!(count(0), "0");
        assert_eq!(count(999), "999");
        assert_eq!(count(1_130), "1,130");
        assert_eq!(count(1_000_000), "1,000,000");
    }

    #[test]
    fn follow_up_commands_preserve_the_active_projection() {
        let mut request = request();
        request.filter = "failed".into();
        request.kind = Some("integration".into());
        request.runner = Some("playwright".into());
        assert_eq!(
            coverage_command("run_00b780f05c9ae324", &request, "files"),
            format!(
                "{} runs 'run_00b780f05c9ae324' files --filter failed --kind 'integration' --runner 'playwright'",
                crate::launcher_command()
            )
        );
    }

    #[test]
    fn missing_test_evidence_is_explained_without_internal_codes() {
        let lines = diagnostic_lines(&CoverageDiagnostic {
            code: "TEST_EVIDENCE_MISSING".into(),
            severity: "warning".into(),
            message: "1 test(s) recorded assertion phases but attributed zero coverage evidence; this is valid for assertions over static or uninstrumented data, but may otherwise indicate missing probe transport. First: safety.spec.ts > checks the VM".into(),
        });
        assert_eq!(
            lines,
            vec![
                "  1 test made assertions, but Supercov received no source-coverage evidence:",
                "    Example: safety.spec.ts > checks the VM",
                "  Possible causes: the code under test is outside the measured source (see `scope`), uninstrumented data, shared setup, lost async context, or missing probe transport. Missing evidence does not prove the code did not execute.",
                "  Inspect the test's coverage and assertion details to distinguish missing execution from missing attribution.",
            ]
        );
        assert!(
            lines
                .iter()
                .all(|line| !line.contains("TEST_EVIDENCE_MISSING"))
        );
    }

    #[test]
    fn branch_obligations_are_described_as_observed_facts() {
        assert_eq!(
            branch_need("default evaluated"),
            "default-value branch not observed"
        );
        assert_eq!(
            branch_need("value provided"),
            "explicit-value branch not observed"
        );
        assert_eq!(
            branch_need("zero iterations"),
            "zero-iteration outcome not observed"
        );
    }

    #[test]
    fn the_attribution_line_offers_only_what_would_help() {
        use supercov_engine::coverage_query::TestAttributionCounts;

        let counts = |exact, partial, run_wide| TestAttributionCounts {
            exact,
            partial,
            run_wide,
        };

        // The ordinary answer, printed on every run so the question is
        // familiar before it matters.
        assert_eq!(attribution_line(&counts(16, 0, 0)), "Exact for 16 test(s)");

        // Where running the suite in order would buy the credit back, say so.
        let offered = attribution_line(&counts(0, 0, 2));
        assert!(offered.contains("2 counted run-wide"), "{offered}");
        assert!(offered.contains("--exact-attribution"), "{offered}");

        // Where it would not, do not: Ruby credits a line to the first test
        // that reaches it, and running in order changes nothing about that.
        // An offer that cannot be taken is worse than silence.
        let lower_bound = attribution_line(&counts(0, 3, 0));
        assert!(lower_bound.contains("3 a lower bound"), "{lower_bound}");
        assert!(
            !lower_bound.contains("--exact-attribution"),
            "nothing here is bought by running in order: {lower_bound}"
        );

        // A mixed run names each part rather than rounding to the worst.
        let mixed = attribution_line(&counts(5, 0, 2));
        assert!(mixed.contains("5 exact"), "{mixed}");
        assert!(mixed.contains("2 counted run-wide"), "{mixed}");

        // And a run with no tests says that, rather than claiming exactness
        // over nothing -- which is the shape every floor is satisfied by.
        assert_eq!(
            attribution_line(&counts(0, 0, 0)),
            "No test recorded coverage"
        );
    }
}