opi 0.13.2

Operations Interface — a project control center for your terminal
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
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
//! `opi` — Operations Interface.
//!
//! A project control center for the terminal. `opi` lists a project's scripts
//! and runs the one you pick; `opi <script>` skips the list entirely.

#[cfg(not(unix))]
compile_error!(
    "opi is Unix-only: it runs a script by replacing its own process with exec, \
     and its interactive list drives termios directly."
);

mod actions;
mod audit;
mod cargo;
mod check;
mod check_config;
mod clean;
mod cli;
mod manifest;
mod osv;
mod outdated;
mod project;
mod run;
mod sbom;
mod scripts;
mod secrets;
mod sources;
mod staged;
mod supply;
mod task;
mod workflow;
mod workspace;

use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use runemark::{
    ColorMode, Console, DetailLevel, ErrorBlock, Finding, FindingGroup, Group, Hint, Item, Layout,
    Menu, Metric, NextStep, Outcome, Picked, Report, SelectMode, Tone, Verdict,
};

use crate::cli::Invocation;
use crate::manifest::{Manifest, ManifestError};
use crate::project::Project;
use crate::task::{Task, by_group, find, suggestions};

const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Lines of a failing tool's output health prints before pointing at the tool.
const OUTPUT_LINES: usize = 20;

/// Above either of these the list is shown as tabs rather than flat.
///
/// The flat list was decided against `astro-v7-template` — 24 entries in 8
/// groups, still readable. `web-casoon` has 27 in the root alone, and with a
/// heading per group that is 34 lines: taller than a full-screen terminal, so
/// the top scrolls away and the whole point of the screen is lost.
///
/// A threshold rather than the terminal's own height, which would have fitted
/// more exactly. The height changes while the menu is open, and a list that
/// rearranged itself mid-keystroke would move entries under a cursor already
/// on its way to one. This way `opi` looks the same in every window, and the
/// same as what a pipe prints.
const TABS_ABOVE_TASKS: usize = 15;
const TABS_ABOVE_GROUPS: usize = 5;

/// The one tab every workspace package shares.
const PACKAGES_TAB: &str = "Packages";

fn main() -> ExitCode {
    let invocation = cli::parse(std::env::args().skip(1));

    match &invocation {
        Invocation::Help => {
            println!("{}", cli::help(VERSION));
            return ExitCode::SUCCESS;
        }
        Invocation::Version => {
            println!("opi {VERSION}");
            return ExitCode::SUCCESS;
        }
        _ => {}
    }

    let directory = match std::env::current_dir() {
        Ok(directory) => directory,
        Err(error) => {
            let console = Console::stderr(ColorMode::Auto);
            eprintln!(
                "{}",
                console.paint(
                    Tone::Error,
                    format!("Cannot read the current directory: {error}")
                )
            );
            return ExitCode::FAILURE;
        }
    };

    // A repository may be more than one kind of project at once — twelve of
    // the ones measured carry both a package.json and a Cargo.toml — so both
    // are looked for and neither is allowed to win.
    let npm = Manifest::discover(&directory);
    let rust = cargo::discover(&directory);

    if let (Err(error), None) = (&npm, &rust) {
        report_error(error);
        return ExitCode::FAILURE;
    }

    // Kept before the match consumes it. An empty `Manifest` stands in for a
    // missing one below, and from there nothing can tell the two apart — but
    // the areas that would start a package manager have to.
    let has_npm = npm.is_ok();

    let (manifest, root) = match npm {
        Ok((manifest, root)) => (manifest, root),
        // A Rust-only project still needs somewhere to stand and something to
        // read; an empty manifest answers both without a special case below.
        Err(_) => (
            Manifest::default(),
            rust.as_ref()
                .map_or_else(|| directory.clone(), |(_, root)| root.clone()),
        ),
    };

    let project = Project::detect(&manifest, &root)
        .or_named(rust.as_ref().and_then(|(rust, _)| rust.name.clone()))
        .with_npm(has_npm);
    // Two different questions: the menu only runs what has a script, while
    // health, clean, security and the workflows look inside every member's
    // directory regardless of whether it has one.
    let scripted_members = workspace::members(&root, &manifest);
    let members = workspace::all(&root, &manifest);
    let mut tasks = Task::from_workspace(&manifest, &scripted_members);
    if let Some((rust, _)) = &rust {
        tasks.extend(task::from_cargo(rust));
    }
    task::arrange(&mut tasks);

    let rust_root = rust.as_ref().map(|(_, root)| root.clone());

    match invocation {
        Invocation::List => list(
            &manifest,
            &members,
            rust_root.as_deref(),
            &project,
            &tasks,
            &root,
        ),
        Invocation::Health => health(&manifest, &members, rust_root.as_deref(), &project, &root),
        Invocation::Clean => clean(&manifest, &members, rust_root.as_deref(), &project, &root),
        Invocation::Security => {
            security(&manifest, &members, rust_root.as_deref(), &project, &root)
        }
        Invocation::Updates => updates(&manifest, &members, &project, rust_root.as_deref(), &root),
        Invocation::Workflow(name) => run_workflow(
            &name,
            &manifest,
            &members,
            rust_root.as_deref(),
            &project,
            &root,
        ),
        Invocation::Hooks => hooks(&root),
        Invocation::Checks(name) => configure_checks(
            name.as_deref(),
            &manifest,
            &members,
            rust_root.as_deref(),
            &project,
            &root,
        ),
        Invocation::Sbom(out) => sbom(&project, rust_root.as_deref(), &root, out.as_deref()),
        Invocation::Run {
            name,
            args,
            confirmed,
        } => start(&project, &tasks, &name, &args, confirmed),
        // An unknown flag is only reported once a project is present, so the
        // missing-package.json message wins where both are true — that is the
        // problem the user has to fix first.
        Invocation::UnknownFlag(flag) => {
            let console = Console::stderr(ColorMode::Auto);
            let block = ErrorBlock::new(format!("Unknown option {flag}"))
                .with_remedy("Run opi --help to see the available options.");
            write_block(&block, console);
            ExitCode::FAILURE
        }
        Invocation::Help | Invocation::Version => unreachable!("handled above"),
    }
}

/// Shows the project's scripts and runs whichever one is chosen.
fn list(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    tasks: &[Task],
    directory: &Path,
) -> ExitCode {
    let manager = project.package_manager;

    if tasks.is_empty() {
        let console = Console::stdout(ColorMode::Auto);
        println!(
            "{}  {}",
            console.paint(Tone::Title, project.display_name(directory)),
            console.paint(Tone::Muted, manager.manager)
        );
        println!(
            "{}",
            console.paint(Tone::Muted, "This project defines no scripts.")
        );
        let others = task::other_runners(directory);
        if !others.is_empty() {
            println!(
                "{}",
                console.paint(
                    Tone::Muted,
                    format!("Its tasks may live in {}.", others.join(", "))
                )
            );
        }
        return ExitCode::SUCCESS;
    }

    // Only worth saying where something would actually be run with it: a
    // Rust-only project has no use for a package manager and no reason to hear
    // that one was guessed.
    let runs_scripts = tasks
        .iter()
        .any(|task| matches!(task.exec, task::Exec::Script));
    if !manager.is_certain() && runs_scripts {
        let console = Console::stderr(ColorMode::Auto);
        eprintln!(
            "{}",
            console.paint(
                Tone::Warning,
                format!(
                    "No lockfile and no packageManager field — assuming {}.",
                    manager.manager
                ),
            )
        );
    }

    let mut menu = build_menu(project, tasks, directory);
    // Offered only where it would do something; a key that answers "nothing
    // applies" is worse than no key.
    let checks = check::Check::detect_all(
        manifest,
        members,
        rust_root,
        directory,
        project.package_manager.manager,
    );
    if !checks.is_empty() {
        menu = menu.add_hint(Hint::new('H', "Health"));
    }
    menu = menu
        .add_hint(Hint::new('C', "Clean"))
        .add_hint(Hint::new('S', "Security"))
        .add_hint(Hint::new('U', "Updates"));

    // Both streams have to be terminals. stdout decides whether the list is
    // being captured rather than read, and the menu draws its frames on
    // stderr, so a redirect on either one means plain text is what is wanted.
    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();

    let outcome = match menu.run(
        Console::stderr(ColorMode::Auto),
        SelectMode::Auto,
        interactive,
    ) {
        Ok(outcome) => outcome,
        Err(error) => {
            let block = ErrorBlock::new("Cannot open the terminal")
                .with_explanation(format!("{error}"))
                .with_remedy("Run opi <script> to start a script without the list.");
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    match outcome {
        Outcome::Selected(id) => start(project, tasks, &id, &[], false),
        // Nothing was chosen; that is not a failure.
        Outcome::Cancelled => ExitCode::SUCCESS,
        Outcome::Hotkey('H') => health(manifest, members, rust_root, project, directory),
        Outcome::Hotkey('C') => clean(manifest, members, rust_root, project, directory),
        Outcome::Hotkey('S') => security(manifest, members, rust_root, project, directory),
        Outcome::Hotkey('U') => updates(manifest, members, project, rust_root, directory),
        Outcome::Hotkey(_) => ExitCode::SUCCESS,
        Outcome::Unavailable => {
            print!("{}", menu.render(Console::stdout(ColorMode::Auto)));
            ExitCode::SUCCESS
        }
    }
}

/// What the header says the project is built with.
///
/// A repository carrying both manifests says both. Naming only one would make
/// the other half of its list look like it arrived from nowhere.
fn toolchains(tasks: &[Task], project: &Project) -> String {
    let mut names = Vec::new();
    if tasks
        .iter()
        .any(|task| matches!(task.exec, task::Exec::Script))
    {
        names.push(project.package_manager.manager.to_string());
    }
    if tasks
        .iter()
        .any(|task| matches!(&task.exec, task::Exec::Direct { program, .. } if program == "cargo"))
    {
        names.push("cargo".to_owned());
    }
    if names.is_empty() {
        names.push(project.package_manager.manager.to_string());
    }
    names.join(" · ")
}

/// Whether the list is shown as tabs or flat.
fn layout(entries: usize, groups: usize) -> Layout {
    if entries > TABS_ABOVE_TASKS || groups > TABS_ABOVE_GROUPS {
        Layout::Tabs
    } else {
        Layout::Flat
    }
}

/// What the list adds up to, for the line under the heading.
///
/// The counts are what the list itself only says by being counted, and in the
/// tab layout two of the three are no longer on screen at once.
///
/// Packages are named only where there are some. A single-package project
/// saying "1 package" would answer a question nobody in it has. The same goes
/// for task runner files beside the manifest: named when present, so the list
/// does not pass for everything the project can do.
fn summary(sections: &[(&task::Group, &[Task])], entries: usize, others: &[String]) -> String {
    let mut parts = vec![
        plural(entries, "entry", "entries"),
        plural(sections.len(), "group", "groups"),
    ];

    let packages = sections
        .iter()
        .filter(|(group, _)| matches!(group, task::Group::Workspace(_)))
        .count();
    if packages > 0 {
        parts.push(plural(packages, "package", "packages"));
    }
    if !others.is_empty() {
        parts.push(format!("also {}", others.join(", ")));
    }

    parts.join(" · ")
}

fn plural(count: usize, one: &str, many: &str) -> String {
    format!("{count} {}", if count == 1 { one } else { many })
}

/// Turns the task list into a menu.
///
/// The item id is the script name, so a selection is ready to run as-is.
fn build_menu(project: &Project, tasks: &[Task], directory: &Path) -> Menu {
    let sections = by_group(tasks);
    let entries: usize = sections.iter().map(|(_, section)| section.len()).sum();

    let mut menu = Menu::new()
        .with_heading(project.display_name(directory))
        .with_note(toolchains(tasks, project))
        .with_summary(summary(&sections, entries, &task::other_runners(directory)))
        .with_layout(layout(entries, sections.len()));

    let mut packaged = false;
    for (group, section) in sections {
        let mut rendered = Group::new(group.label());
        // Every workspace package shares one tab, and the first of them marks
        // where the row stops naming actions and starts naming packages.
        //
        // One tab each was measured and does not scale: this repository's
        // largest workspace has 52 packages against 6 action groups, which is
        // a tab row of 58 that is almost entirely package names, permanently
        // scrolling, with the digits worthless past the ninth. Inside the tab
        // each package keeps its heading, so nothing is lost but the length.
        if matches!(group, task::Group::Workspace(_)) {
            rendered = rendered.in_tab(PACKAGES_TAB);
            if !packaged {
                rendered = rendered.with_divider();
                packaged = true;
            }
        }
        for task in section {
            // The id has to disambiguate: root and member scripts share names
            // in every workspace repository measured.
            let id = match &task.workspace {
                Some(member) => format!("{member}/{}", task.name),
                None => task.name.clone(),
            };
            let mut item = Item::new(id, &task.name);
            if let Some(description) = &task.description {
                item = item.with_description(description);
            }
            rendered = rendered.add_item(item);
        }
        menu = menu.add_group(rendered);
    }

    menu
}

/// Runs `name`, or explains why it cannot.
///
/// Returns only on failure: a started script replaces this process.
fn start(
    project: &Project,
    tasks: &[Task],
    name: &str,
    args: &[String],
    confirmed: bool,
) -> ExitCode {
    let Some(task) = find(tasks, name) else {
        let console = Console::stderr(ColorMode::Auto);
        let mut block = ErrorBlock::new(format!("No script named {name}"));

        let close = suggestions(tasks, name);
        block = if close.is_empty() {
            block.with_remedy("Run opi to see the project's scripts.")
        } else {
            block.with_explanation(format!("Did you mean {}?", close.join(", ")))
        };
        for candidate in close {
            block = block.add_command(format!("opi {candidate}"));
        }

        write_block(&block, console);
        return ExitCode::FAILURE;
    };

    if task.confirm && !confirmed && !confirm(task) {
        return ExitCode::FAILURE;
    }

    let manager = project.package_manager;
    let error = run::execute(task, manager.manager, args);

    let console = Console::stderr(ColorMode::Auto);
    let block = ErrorBlock::new(format!("Cannot run {}", manager.manager))
        .with_explanation(format!("{error}"))
        .with_remedy(if manager.is_certain() {
            format!(
                "Check that {} is installed and on your PATH.",
                manager.manager
            )
        } else {
            format!(
                "No lockfile or packageManager field names a package manager, so {} was assumed.",
                manager.manager
            )
        });
    write_block(&block, console);
    ExitCode::FAILURE
}

/// Asks before running a task the project marked as needing it.
///
/// Without a terminal this refuses rather than assuming yes. Skipping the
/// question where it cannot be asked would remove the protection in exactly
/// the case it exists for — a script, a hook, CI — so `--yes` has to be said
/// out loud there.
fn confirm(task: &Task) -> bool {
    let console = Console::stderr(ColorMode::Auto);
    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();

    if !interactive {
        let block = ErrorBlock::new(format!("{} needs confirming", task.name))
            .with_explanation("This project marked it as needing a confirmation, and there is no terminal to ask in.")
            .with_remedy("Run it again with --yes if that is what you mean.")
            .add_command(format!("opi --yes {}", task.name));
        write_block(&block, console);
        return false;
    }

    let menu = Menu::new()
        .with_heading(format!("Run {}?", task.name))
        .with_note(&task.command)
        .add_group(
            Group::new("Confirm")
                .add_item(Item::new("no", "Cancel"))
                .add_item(Item::new("yes", format!("Run {}", task.name))),
        );

    // Cancel first, so the cursor starts on the harmless answer.
    matches!(
        menu.run(console, SelectMode::Auto, true),
        Ok(Outcome::Selected(choice)) if choice == "yes"
    )
}

/// Writes an error block to stderr, ignoring a broken pipe.
fn write_block(block: &ErrorBlock, console: Console) {
    let mut stderr = io::stderr().lock();
    let _ = block.write_to(console, &mut stderr);
    let _ = stderr.flush();
}

fn report_error(error: &ManifestError) {
    let console = Console::stderr(ColorMode::Auto);
    let block = match error {
        ManifestError::Missing { directory } => ErrorBlock::new("No package.json found")
            .with_explanation(format!(
                "Searched {} and every directory above it.",
                directory.display()
            ))
            .with_remedy("Change into a project directory and run opi again."),
        ManifestError::Unreadable { path, error } => ErrorBlock::new("package.json is unreadable")
            .with_explanation(format!("{}: {error}", path.display()))
            .with_remedy("Check the file permissions."),
        ManifestError::Malformed { path, error } => {
            ErrorBlock::new("package.json is not valid JSON")
                .with_explanation(format!("{}: {error}", path.display()))
                .with_remedy("Fix the syntax error and run opi again.")
        }
    };

    write_block(&block, console);
}

/// Runs the project's checks and reports what each tool said.
fn health(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let checks = check::Check::detect_all(
        manifest,
        members,
        rust_root,
        root,
        project.package_manager.manager,
    );

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "health")
    );
    println!();

    if checks.is_empty() {
        println!(
            "{}",
            console.paint(
                Tone::Muted,
                "No checks apply: this project depends on none of the tools opi knows."
            )
        );
        return ExitCode::SUCCESS;
    }

    // Results print as they arrive rather than after the slowest one, so a
    // long test run does not look like a hang.
    let width = checks
        .iter()
        .map(|check| check.label().chars().count())
        .max()
        .unwrap_or(0);
    let reports = check::run_all(checks, |report| {
        let (tone, mark) = match report {
            report if report.warned() => (Tone::Warning, "!"),
            report if report.passed() => (Tone::Success, "✓"),
            report if report.unusable() => (Tone::Warning, "!"),
            _ => (Tone::Error, "✗"),
        };
        println!(
            "{} {}  {}  {}",
            console.paint(tone, mark),
            console.paint(tone, format!("{:width$}", report.check.label())),
            console.paint(
                Tone::Muted,
                format!("{:>6.1}s", report.duration.as_secs_f64())
            ),
            console.paint(Tone::Muted, report.check.tool),
        );
    });

    let failed: Vec<&check::Report> = reports.iter().filter(|report| !report.passed()).collect();
    let unusable = failed.iter().filter(|report| report.unusable()).count();
    let warned = reports.iter().filter(|report| report.warned()).count();

    // No score. A composite number stops meaning anything within weeks; what a
    // failing tool actually said does not.
    for report in reports
        .iter()
        .filter(|report| !report.passed() || report.warned())
    {
        println!();
        let tone = if report.unusable() || report.warned() {
            Tone::Warning
        } else {
            Tone::Error
        };
        println!(
            "{}",
            console.paint(
                tone,
                format!("{} — {}", report.check.label(), report.check.tool)
            )
        );
        // Capped: one failing scanner produced 49 lines on a real project, and
        // several at once bury the summary that says what to do next.
        let lines: Vec<&str> = report.output.lines().collect();
        for line in lines.iter().take(OUTPUT_LINES) {
            println!("  {line}");
        }
        if let Some(hidden) = lines.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
            println!(
                "  {}",
                console.paint(
                    Tone::Muted,
                    format!(
                        "… {hidden} more lines — run `{}` in {} to see them all",
                        report.check.command_line(),
                        report.check.scope.as_deref().unwrap_or("the project root"),
                    )
                )
            );
        }
    }

    println!();
    if failed.is_empty() {
        let note = if warned > 0 {
            format!("{} checks passed, {warned} with warnings.", reports.len())
        } else {
            format!("{} checks passed.", reports.len())
        };
        println!("{}", console.paint(Tone::Success, note));
        ExitCode::SUCCESS
    } else {
        let note = if unusable > 0 {
            format!(
                "{} of {} checks failed, {unusable} could not run.",
                failed.len(),
                reports.len()
            )
        } else {
            format!("{} of {} checks failed.", failed.len(), reports.len())
        };
        println!("{}", console.paint(Tone::Error, note));
        ExitCode::FAILURE
    }
}

/// Shows what can be removed, and removes what is chosen.
fn clean(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let candidates = clean::candidates(manifest, members, rust_root, root);

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "clean")
    );
    println!();

    if candidates.is_empty() {
        println!(
            "{}",
            console.paint(Tone::Muted, "Nothing to remove; the project is clean.")
        );
        return ExitCode::SUCCESS;
    }

    let width = candidates
        .iter()
        .map(|candidate| candidate.display.chars().count())
        .max()
        .unwrap_or(0);
    for candidate in &candidates {
        println!(
            "  {}  {}",
            console.paint(
                if candidate.heavy {
                    Tone::Warning
                } else {
                    Tone::Info
                },
                format!("{:width$}", candidate.display)
            ),
            console.paint(Tone::Muted, clean::human(candidate.bytes)),
        );
    }
    println!();

    let artefacts: Vec<&clean::Candidate> =
        candidates.iter().filter(|entry| !entry.heavy).collect();
    let everything: Vec<&clean::Candidate> = candidates.iter().collect();
    let artefact_bytes: u64 = artefacts.iter().map(|entry| entry.bytes).sum();
    let total_bytes: u64 = everything.iter().map(|entry| entry.bytes).sum();

    // Concrete choices rather than per-entry ticking. The distinction that
    // matters is node_modules against the rest: it is the largest item and the
    // most expensive to rebuild, so it never rides along with a build artefact.
    let mut menu = Menu::new().add_group({
        let mut group = Group::new("Remove");
        if !artefacts.is_empty() {
            group = group.add_item(
                Item::new("artefacts", "Build artefacts")
                    .with_description(clean::human(artefact_bytes)),
            );
        }
        if artefacts.len() != everything.len() {
            group = group.add_item(
                Item::new("everything", "Everything, including node_modules")
                    .with_description(clean::human(total_bytes)),
            );
        }
        group.add_item(Item::new("cancel", "Cancel"))
    });
    menu = menu.with_note(format!("{} removable", clean::human(total_bytes)));

    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();
    let chosen = match menu.run(
        Console::stderr(ColorMode::Auto),
        SelectMode::Auto,
        interactive,
    ) {
        Ok(Outcome::Selected(id)) => id,
        Ok(Outcome::Unavailable) => {
            // Nothing is removed without someone choosing it, so a pipe gets
            // the inventory and stops there.
            println!(
                "{}",
                console.paint(
                    Tone::Muted,
                    "Run opi --clean in a terminal to remove any of it."
                )
            );
            return ExitCode::SUCCESS;
        }
        Ok(_) => return ExitCode::SUCCESS,
        Err(error) => {
            let block =
                ErrorBlock::new("Cannot open the terminal").with_explanation(format!("{error}"));
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    let selected: &[&clean::Candidate] = match chosen.as_str() {
        "artefacts" => &artefacts,
        "everything" => &everything,
        _ => return ExitCode::SUCCESS,
    };

    let started = std::time::Instant::now();
    let (freed, failures) = clean::remove(selected);

    println!(
        "{}",
        console.paint(
            Tone::Success,
            format!(
                "Removed {} in {:.1}s",
                clean::human(freed),
                started.elapsed().as_secs_f64()
            )
        )
    );
    for (path, error) in &failures {
        println!(
            "{}",
            console.paint(Tone::Error, format!("Could not remove {path}: {error}"))
        );
    }

    if failures.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// Scans the repository for secrets and its dependencies for vulnerabilities.
fn security(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "security")
    );
    println!();

    let mut clean = true;
    // Packages the native audits reported, so the OSV section can skip them.
    let mut known: Vec<(&str, String)> = Vec::new();

    // Secrets is a check like any other; this only makes it reachable without
    // waiting for the tests to finish.
    // Secrets scanning is about the repository, not a toolchain, so the Rust
    // side contributes nothing here.
    let scans: Vec<check::Check> = check::Check::detect_all(
        manifest,
        members,
        None,
        root,
        project.package_manager.manager,
    )
    .into_iter()
    .filter(|check| check.name == "Secrets")
    .collect();

    if scans.is_empty() {
        println!(
            "{}",
            console.paint(
                Tone::Muted,
                "No secret scanner: this project depends on none that opi knows."
            )
        );
    } else {
        let reports = check::run_all(scans, |_| {});
        for report in &reports {
            if report.passed() && !report.warned() {
                println!(
                    "{} {}",
                    console.paint(Tone::Success, "✓"),
                    console.paint(Tone::Success, format!("Secrets — {}", report.check.tool))
                );
            } else {
                let (tone, mark) = if report.warned() {
                    (Tone::Warning, "!")
                } else {
                    clean = false;
                    (Tone::Error, "✗")
                };
                println!(
                    "{} {}",
                    console.paint(tone, mark),
                    console.paint(tone, format!("Secrets — {}", report.check.tool))
                );
                // Locations, not values: this output lands in scrollback, CI
                // logs and screenshots.
                let lines: Vec<&str> = report.output.lines().collect();
                for line in lines.iter().take(OUTPUT_LINES) {
                    println!("  {line}");
                }
                if let Some(rest) = lines.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
                    println!(
                        "  {}",
                        console.paint(
                            Tone::Muted,
                            format!(
                                "… {rest} more lines — run `{}`",
                                report.check.command_line()
                            )
                        )
                    );
                }
            }
        }
    }

    // One section per ecosystem present, each named for itself. Health settles
    // the same question with a scope — `Tests (rust)` — and this follows it:
    // npm's section keeps the plain name, Rust's is marked.
    //
    // `project.package_manager` always holds a value, because the absence of
    // every signal still produces the npm fallback, so a Rust-only project
    // would otherwise run `npm audit` where there is no package.json and relay
    // npm's complaint about it as the result.
    if project.npm {
        println!();
        match audit::run(project.package_manager.manager, root) {
            Ok(found) if found.is_empty() => println!(
                "{} {}",
                console.paint(Tone::Success, "✓"),
                console.paint(Tone::Success, "Dependencies — no known vulnerabilities")
            ),
            Ok(found) => {
                known.extend(found.advisories.iter().map(|a| ("npm", a.module.clone())));
                let serious = found
                    .advisories
                    .iter()
                    .any(|advisory| advisory.severity.serious());
                clean = clean && !serious;

                // Parsed rather than relayed, so this is where a report earns its
                // keep: severity counts as metrics, each advisory with the version
                // range that fixes it as its remedy.
                let mut report = Report::new(
                    "Dependencies",
                    if serious {
                        Verdict::Failed
                    } else {
                        Verdict::Warning
                    },
                )
                .with_detail_level(DetailLevel::Detailed);

                // A verdict rather than a tone: this is read in pipes and in CI,
                // where a tone is nothing at all.
                for (severity, count) in found.counts() {
                    report = report.add_metric(
                        Metric::new(severity.label(), count.to_string()).with_verdict(
                            if severity.serious() {
                                Verdict::Failed
                            } else {
                                Verdict::Warning
                            },
                        ),
                    );
                }

                let mut group = FindingGroup::new("Vulnerable dependencies");
                for advisory in &found.advisories {
                    let mut finding = Finding::new(
                        if advisory.severity.serious() {
                            Tone::Error
                        } else {
                            Tone::Warning
                        },
                        &advisory.module,
                    )
                    .with_rule_id(advisory.severity.label());
                    if let Some(patched) = &advisory.patched {
                        finding = finding.with_remedy(format!("update to {patched}"));
                    }
                    group = group.add_finding(finding);
                }
                report = report.add_group(group);

                print!("{}", report.render(console));
            }
            Err(error) => {
                clean &= !audit_failed(&error);
                println!(
                    "{} {}",
                    console.paint(Tone::Muted, "–"),
                    console.paint(Tone::Muted, format!("Dependencies — {error}"))
                );
            }
        }
        println!();
        clean &= supply_chain(console, project.package_manager.manager, root);
    }

    if let Some(rust_root) = rust_root {
        println!();
        match audit::cargo(rust_root) {
            Ok(found) if found.is_empty() => println!(
                "{} {}",
                console.paint(Tone::Success, "✓"),
                console.paint(
                    Tone::Success,
                    "Dependencies (rust) — no known vulnerabilities"
                )
            ),
            Ok(found) => {
                // Every advisory counts, because there is no severity here to
                // sort them by — see `audit::CargoAdvisory` — and because
                // `cargo audit` fails on any of them itself.
                clean = false;
                known.extend(found.iter().map(|a| ("crates.io", a.package.clone())));

                let mut report = Report::new("Dependencies (rust)", Verdict::Failed)
                    .with_detail_level(DetailLevel::Detailed)
                    .add_metric(
                        Metric::new("advisories", found.len().to_string())
                            .with_verdict(Verdict::Failed),
                    );

                let mut group = FindingGroup::new("Vulnerable crates");
                for advisory in &found {
                    let mut finding = Finding::new(
                        Tone::Error,
                        format!("{} {}", advisory.package, advisory.version),
                    )
                    .with_rule_id(&advisory.id);
                    if let Some(patched) = &advisory.patched {
                        finding = finding.with_remedy(format!("update to {patched}"));
                    }
                    group = group.add_finding(finding);
                }
                report = report.add_group(group);

                // The severity is missing from the JSON but present in the
                // tool's own output, so this is where to send someone who
                // wants it — along with the dependency path that pulled the
                // crate in.
                report = report.add_next_step(
                    NextStep::new("Severities and dependency paths").with_command("cargo audit"),
                );

                print!("{}", report.render(console));
            }
            Err(error) => {
                clean &= !audit_failed(&error);
                println!(
                    "{} {}",
                    console.paint(Tone::Muted, "–"),
                    console.paint(Tone::Muted, format!("Dependencies (rust) — {error}"))
                );
            }
        }
        license_report(console, supply::cargo_licenses(rust_root));
    }

    if project.npm || rust_root.is_some() {
        println!();
        clean &= osv_audit(console, root, &known);
    }

    unpinned_actions(console, root);

    println!();
    non_registry_sources(console, &[Some(root), rust_root]);
    if clean {
        println!("{}", console.paint(Tone::Success, "Nothing to act on."));
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// The lockfile audit through `osv-scanner`, beside the native ones: only what
/// they did not already report. Returns whether nothing needs acting on.
fn osv_audit(console: Console, root: &Path, known: &[(&str, String)]) -> bool {
    let name = "Dependencies (osv)";
    match osv::run(root) {
        Ok(found) => {
            let found = osv::without_known(found, known);
            if found.is_empty() {
                println!(
                    "{} {}",
                    console.paint(Tone::Success, "✓"),
                    console.paint(
                        Tone::Success,
                        format!("{name} — nothing beyond the audits above")
                    )
                );
                return true;
            }
            let serious = found.iter().any(|f| f.advisory.severity.serious());
            let verdict = |serious: bool| {
                if serious {
                    Verdict::Failed
                } else {
                    Verdict::Warning
                }
            };
            let mut report =
                Report::new(name, verdict(serious)).with_detail_level(DetailLevel::Detailed);
            let audit = audit::Audit {
                advisories: found.iter().map(|f| f.advisory.clone()).collect(),
            };
            for (severity, count) in audit.counts() {
                report = report.add_metric(
                    Metric::new(severity.label(), count.to_string())
                        .with_verdict(verdict(severity.serious())),
                );
            }
            let mut group = FindingGroup::new("Vulnerable packages in the lockfiles");
            for advisory in &audit.advisories {
                let mut finding = Finding::new(
                    if advisory.severity.serious() {
                        Tone::Error
                    } else {
                        Tone::Warning
                    },
                    &advisory.module,
                )
                .with_rule_id(advisory.severity.label());
                if let Some(patched) = &advisory.patched {
                    finding = finding.with_remedy(format!("update to {patched}"));
                }
                group = group.add_finding(finding);
            }
            print!("{}", report.add_group(group).render(console));
            !serious
        }
        Err(error) => {
            let reason = match &error {
                audit::AuditError::NotInstalled => {
                    "osv-scanner is not installed; see google.github.io/osv-scanner".to_owned()
                }
                other => other.to_string(),
            };
            println!(
                "{} {}",
                console.paint(Tone::Muted, "–"),
                console.paint(Tone::Muted, format!("{name} — {reason}"))
            );
            !audit_failed(&error)
        }
    }
}

/// Lists dependencies resolved from git, a tarball or a path outside the
/// workspace. Reported, not judged: a fork is often a deliberate choice.
fn non_registry_sources(console: Console, dirs: &[Option<&Path>]) {
    let mut found: Vec<sources::Foreign> = dirs
        .iter()
        .flatten()
        .flat_map(|dir| sources::scan(dir))
        .collect();
    found.dedup();
    if found.is_empty() {
        return;
    }
    println!(
        "{} {}",
        console.paint(Tone::Warning, "!"),
        console.paint(
            Tone::Warning,
            format!(
                "Sources — {} from outside the registry",
                plural(found.len(), "dependency", "dependencies")
            )
        )
    );
    for item in found.iter().take(OUTPUT_LINES) {
        println!(
            "  {}  {}",
            item.name,
            console.paint(Tone::Muted, &item.source)
        );
    }
    if let Some(rest) = found.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
        println!("  {}", console.paint(Tone::Muted, format!("… {rest} more")));
    }
    println!();
}

/// Whether an audit error leaves the question unanswered rather than
/// answered "not here".
///
/// An audit that ran and failed has said nothing about the dependencies, so
/// "Nothing to act on." would be a false acquittal. `cargo audit` not being
/// installed is the ordinary case and is named with its remedy instead — the
/// same split `--updates` makes.
fn audit_failed(error: &audit::AuditError) -> bool {
    matches!(error, audit::AuditError::Failed(_))
}

/// Workflow `uses:` references a tag or branch can move.
///
/// Reported, not judged: pinning is a policy, so it does not fail the run.
fn unpinned_actions(console: Console, root: &Path) {
    let found = actions::unpinned(root);
    if found.is_empty() {
        return;
    }
    println!();
    println!(
        "{} {}",
        console.paint(Tone::Warning, "!"),
        console.paint(
            Tone::Warning,
            format!(
                "GitHub Actions — {} not pinned to a commit SHA",
                plural(found.len(), "reference", "references")
            )
        )
    );
    for item in found.iter().take(OUTPUT_LINES) {
        println!("  {}:{}  {}", item.file, item.line, item.reference);
    }
    if let Some(rest) = found.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
        println!("  {}", console.paint(Tone::Muted, format!("… {rest} more")));
    }
}

/// Signatures, release age and licenses, beside the vulnerability audit.
///
/// Returns whether nothing needs acting on. Only a signature that does not
/// verify counts against that: an unset release age or a copyleft dependency
/// is a policy the project may have chosen, so both are reported, not judged.
fn supply_chain(console: Console, manager: project::PackageManager, root: &Path) -> bool {
    let line = |tone: Tone, mark: &str, text: String| {
        println!(
            "{} {}",
            console.paint(tone, mark),
            console.paint(tone, text)
        );
    };
    let list = |names: &[String]| {
        for name in names.iter().take(OUTPUT_LINES) {
            println!("  {name}");
        }
        if let Some(rest) = names.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
            println!("  {}", console.paint(Tone::Muted, format!("… {rest} more")));
        }
    };

    let mut clean = true;
    match supply::signatures(root) {
        Ok(found) if found.invalid.is_empty() && found.missing.is_empty() => line(
            Tone::Success,
            "✓",
            "Signatures — every installed package verified".to_owned(),
        ),
        Ok(found) => {
            if !found.invalid.is_empty() {
                clean = false;
                line(
                    Tone::Error,
                    "✗",
                    format!(
                        "Signatures — {} do not match what the registry published",
                        plural(found.invalid.len(), "package", "packages")
                    ),
                );
                list(&found.invalid);
            }
            if !found.missing.is_empty() {
                line(
                    Tone::Warning,
                    "!",
                    format!(
                        "Signatures — {} without a registry signature",
                        plural(found.missing.len(), "package", "packages")
                    ),
                );
                list(&found.missing);
            }
        }
        Err(reason) => line(Tone::Muted, "–", format!("Signatures — {reason}")),
    }

    match supply::release_age(manager, root) {
        Some(supply::ReleaseAge::Set(age)) => line(
            Tone::Success,
            "✓",
            format!("Release age — versions younger than {age} are not installed"),
        ),
        Some(supply::ReleaseAge::Unset) => {
            line(
                Tone::Warning,
                "!",
                "Release age — not set: a version installs the moment it is published".to_owned(),
            );
            let remedy = match manager {
                project::PackageManager::Npm => "min-release-age=<days> in .npmrc",
                _ => "minimumReleaseAge: <minutes> in pnpm-workspace.yaml",
            };
            println!("  {}", console.paint(Tone::Muted, remedy));
        }
        None => {}
    }

    install_scripts(console, manager, root);

    if let Some(licenses) = supply::licenses(manager, root) {
        license_report(console, licenses);
    }

    clean
}

/// The license line, with the notable packages beneath it.
fn license_report(console: Console, found: Result<supply::Licenses, String>) {
    let found = match found {
        Ok(found) => found,
        Err(reason) => {
            println!(
                "{} {}",
                console.paint(Tone::Muted, "–"),
                console.paint(Tone::Muted, format!("Licenses — {reason}"))
            );
            return;
        }
    };
    const SHOWN: usize = 4;
    let mut parts: Vec<String> = found
        .counts
        .iter()
        .take(SHOWN)
        .map(|(license, count)| format!("{count} {license}"))
        .collect();
    let others: usize = found.counts.iter().skip(SHOWN).map(|(_, n)| n).sum();
    if others > 0 {
        parts.push(format!("{others} other"));
    }
    let (tone, mark) = if found.notable.is_empty() {
        (Tone::Success, "✓")
    } else {
        (Tone::Warning, "!")
    };
    println!(
        "{} {}",
        console.paint(tone, mark),
        console.paint(tone, format!("Licenses — {}", parts.join(" · ")))
    );
    for (license, name) in found.notable.iter().take(OUTPUT_LINES) {
        println!("  {name}  {license}");
    }
    if let Some(rest) = found
        .notable
        .len()
        .checked_sub(OUTPUT_LINES)
        .filter(|n| *n > 0)
    {
        println!("  {}", console.paint(Tone::Muted, format!("… {rest} more")));
    }
}

/// Dependencies with install scripts and whether the project allows them.
///
/// Reported, never judged: an unreviewed script is a policy gap worth a look,
/// not a failure.
fn install_scripts(console: Console, manager: project::PackageManager, root: &Path) {
    let Some(found) = scripts::install_scripts(manager, root) else {
        return;
    };
    let count = |status| found.packages.iter().filter(|(_, s)| *s == status).count();
    let (allowed, ignored) = (
        count(scripts::Status::Allowed),
        count(scripts::Status::Ignored),
    );
    let unreviewed: Vec<&str> = found
        .packages
        .iter()
        .filter(|(_, status)| *status == scripts::Status::Unreviewed)
        .map(|(name, _)| name.as_str())
        .collect();
    let summary = format!(
        "{} with install scripts: {allowed} allowed · {ignored} ignored · {} not reviewed",
        plural(found.packages.len(), "dependency", "dependencies"),
        unreviewed.len()
    );
    if unreviewed.is_empty() {
        println!(
            "{} {}",
            console.paint(Tone::Success, "✓"),
            console.paint(Tone::Success, format!("Install scripts — {summary}"))
        );
        return;
    }
    let tone = Tone::Warning;
    println!(
        "{} {}",
        console.paint(tone, "!"),
        console.paint(tone, format!("Install scripts — {summary}"))
    );
    for name in unreviewed.iter().take(OUTPUT_LINES) {
        println!("  {name}");
    }
    if let Some(rest) = unreviewed
        .len()
        .checked_sub(OUTPUT_LINES)
        .filter(|n| *n > 0)
    {
        println!("  {}", console.paint(Tone::Muted, format!("… {rest} more")));
    }
    let remedy = match manager {
        project::PackageManager::Pnpm => {
            "list them in onlyBuiltDependencies or ignoredBuiltDependencies"
        }
        project::PackageManager::Bun => "trust them in trustedDependencies, or leave them blocked",
        _ => "they run on install; ignore-scripts=true in .npmrc turns that off",
    };
    println!("  {}", console.paint(Tone::Muted, remedy));
}

/// Configures a named workflow without running any checks.
fn configure_checks(
    name: Option<&str>,
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let mut config = match check_config::Config::load(root) {
        Ok(config) => config,
        Err(error) => return check_config_error(error),
    };
    if !io::stdin().is_terminal() || !io::stderr().is_terminal() {
        write_block(
            &ErrorBlock::new("Selecting checks needs a terminal")
                .with_remedy("Run opi --checks in a terminal, or edit .opi/checks.json."),
            Console::stderr(ColorMode::Auto),
        );
        return ExitCode::FAILURE;
    }
    let name = match name {
        Some(name) => name.to_owned(),
        None => {
            let group = ["commit", "push", "release", "deploy"]
                .into_iter()
                .fold(Group::new("Workflow"), |group, name| {
                    group.add_item(Item::new(name, name))
                });
            match Menu::new()
                .with_heading("Configure checks")
                .add_group(group)
                .run(Console::stderr(ColorMode::Auto), SelectMode::Auto, true)
            {
                Ok(Outcome::Selected(name)) => name,
                Ok(_) => return ExitCode::SUCCESS,
                Err(error) => return check_config_error(error.to_string()),
            }
        }
    };
    let Some(workflow) = workflow::Workflow::parse(&name) else {
        return check_config_error(format!(
            "Unknown workflow {name:?}; use commit, push, release or deploy."
        ));
    };
    let mut checks = check::Check::detect_all(
        manifest,
        members,
        rust_root,
        root,
        project.package_manager.manager,
    );
    if workflow == workflow::Workflow::Commit {
        checks = check::Check::for_commit(checks, root);
    }
    let available: std::collections::BTreeSet<&str> =
        checks.iter().map(|check| check.name).collect();
    let previous = config.workflows.get(&name);
    let mut ticked: Vec<String> = match previous {
        Some(previous) => previous.checks.clone(),
        None => available
            .iter()
            .filter(|name| workflow.includes(name))
            .map(|name| (*name).to_owned())
            .collect(),
    };
    let has_build = !check::Check::builds(
        manifest,
        members,
        rust_root,
        root,
        project.package_manager.manager,
    )
    .is_empty();
    let build = previous.map_or_else(
        || workflow.builds() && has_build,
        |selection| selection.build,
    );
    if build {
        ticked.push("@build".to_owned());
    }
    let mut group = Group::new("Checks — all detected tools and workspace members");
    for name in &available {
        group = group.add_item(Item::new(*name, *name));
    }
    if let Some(previous) = previous {
        for name in previous
            .checks
            .iter()
            .filter(|name| !available.contains(name.as_str()))
        {
            group = group.add_item(
                Item::new(name, name).with_description("Unavailable here; deselect to remove"),
            );
        }
    }
    if has_build || build {
        group =
            group.add_item(Item::new("@build", "Build").with_description("Run after the checks"));
    }
    let menu = Menu::new()
        .with_heading(format!("Checks before {name}"))
        .with_ticked(ticked)
        .add_group(group);
    let chosen = match menu.run_multi(Console::stderr(ColorMode::Auto), SelectMode::Auto, true) {
        Ok(Picked::Chosen(chosen)) => chosen,
        Ok(_) => return ExitCode::SUCCESS,
        Err(error) => return check_config_error(error.to_string()),
    };
    let selection = check_config::Selection {
        build: chosen.iter().any(|name| name == "@build"),
        checks: chosen.into_iter().filter(|name| name != "@build").collect(),
    };
    config.workflows.insert(name.clone(), selection);
    match config.save(root) {
        Ok(_) => {
            println!(
                "{}",
                Console::stdout(ColorMode::Auto).paint(
                    Tone::Success,
                    format!(
                        "Saved {name} checks in {}. Run opi --check {name} to use them.",
                        check_config::FILE
                    )
                )
            );
            ExitCode::SUCCESS
        }
        Err(error) => check_config_error(error),
    }
}

fn check_config_error(error: impl Into<String>) -> ExitCode {
    write_block(
        &ErrorBlock::new("Cannot use the workflow check selection")
            .with_explanation(error.into())
            .with_remedy("Review .opi/checks.json or run opi --checks in a terminal."),
        Console::stderr(ColorMode::Auto),
    );
    ExitCode::FAILURE
}

/// Runs a named workflow: the repository questions, then the checks.
fn run_workflow(
    name: &str,
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);

    let Some(workflow) = workflow::Workflow::parse(name) else {
        let block = ErrorBlock::new(format!("No workflow named {name}"))
            .with_remedy("Known workflows: commit, push, release, deploy.");
        write_block(&block, Console::stderr(ColorMode::Auto));
        return ExitCode::FAILURE;
    };

    let config = match check_config::Config::load(root) {
        Ok(config) => config,
        Err(error) => return check_config_error(error),
    };
    let selection = config.workflows.get(name);

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, workflow.label())
    );
    println!();

    let mut blocked = false;

    // The repository questions come first: a release from a dirty tree is
    // settled before spending a minute on its tests.
    for gate in workflow.gates() {
        let result = gate.check(root, manifest.version.as_deref());
        let (tone, mark) = match result.verdict {
            runemark::Verdict::Passed => (Tone::Success, "✓"),
            runemark::Verdict::Skipped => (Tone::Muted, "–"),
            _ => {
                blocked = true;
                (Tone::Error, "✗")
            }
        };
        let detail = result
            .detail
            .map_or_else(String::new, |detail| format!("  {detail}"));
        println!(
            "{} {}{}",
            console.paint(tone, mark),
            console.paint(tone, gate.name()),
            console.paint(Tone::Muted, detail)
        );
    }

    let checks: Vec<check::Check> = check::Check::detect_all(
        manifest,
        members,
        rust_root,
        root,
        project.package_manager.manager,
    )
    .into_iter()
    .filter(|check| {
        selection.map_or_else(
            || workflow.includes(check.name),
            |selected| selected.includes(check.name),
        )
    })
    .collect();

    let checks = if workflow == workflow::Workflow::Commit {
        check::Check::for_commit(checks, root)
            .into_iter()
            .filter(|check| selection.is_none_or(|selected| selected.includes(check.name)))
            .collect()
    } else {
        checks
    };

    let builds = if selection.map_or_else(|| workflow.builds(), |selected| selected.build) {
        check::Check::builds(
            manifest,
            members,
            rust_root,
            root,
            project.package_manager.manager,
        )
    } else {
        Vec::new()
    };
    if let Some(selection) = selection {
        let mut missing: Vec<_> = selection
            .checks
            .iter()
            .filter(|name| !checks.iter().any(|check| check.name == name.as_str()))
            .map(String::as_str)
            .collect();
        if selection.build && builds.is_empty() {
            missing.push("Build");
        }
        if !missing.is_empty() {
            return check_config_error(format!(
                "Selected checks unavailable in this project: {}",
                missing.join(", "),
            ));
        }
    }
    if checks.is_empty() && builds.is_empty() {
        println!(
            "{}",
            console.paint(Tone::Muted, "No checks apply to this project.")
        );
    }

    let width = checks
        .iter()
        .chain(&builds)
        .map(|check| check.label().chars().count())
        .max()
        .unwrap_or(0);
    let print = |report: &check::Report| {
        let (tone, mark) = match report {
            report if report.warned() => (Tone::Warning, "!"),
            report if report.passed() => (Tone::Success, "✓"),
            report if report.unusable() => (Tone::Warning, "!"),
            _ => (Tone::Error, "✗"),
        };
        println!(
            "{} {}  {}",
            console.paint(tone, mark),
            console.paint(tone, format!("{:width$}", report.check.label())),
            console.paint(Tone::Muted, report.check.tool),
        );
    };
    let mut reports = check::run_all(checks, print);
    // After the checks and one at a time: a build pins the machine, and run
    // beside the checks it would slow every one of them down.
    for build in builds {
        let report = build.run();
        print(&report);
        reports.push(report);
    }

    let failed = reports.iter().filter(|report| !report.passed()).count();
    println!();

    if blocked || failed > 0 {
        // Which step and why, rather than a count on its own.
        for report in reports.iter().filter(|report| !report.passed()) {
            println!(
                "{}",
                console.paint(
                    Tone::Error,
                    format!("{} — {}", report.check.label(), report.check.tool)
                )
            );
            for line in report.output.lines().take(OUTPUT_LINES) {
                println!("  {line}");
            }
        }
        println!();
        println!(
            "{}",
            console.paint(Tone::Error, format!("Not ready to {name}."))
        );
        ExitCode::FAILURE
    } else {
        println!(
            "{}",
            console.paint(Tone::Success, format!("Ready to {name}."))
        );
        ExitCode::SUCCESS
    }
}

/// Installs `opi --check push` as the repository's pre-push hook.
fn hooks(root: &Path) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let (message, hook) = match workflow::install_hook(root) {
        Ok(workflow::HookInstall::Created(hook)) => ("Installed the pre-push hook", hook),
        Ok(workflow::HookInstall::Appended(hook)) => ("Added opi to the pre-push hook", hook),
        Ok(workflow::HookInstall::Present(hook)) => ("The pre-push hook already runs opi", hook),
        Err(error) => {
            let block = match error {
                workflow::HookError::NotARepository => ErrorBlock::new("Not a git repository")
                    .with_remedy("Hooks belong to a repository; run git init first."),
                workflow::HookError::Io(error) => {
                    ErrorBlock::new("Cannot write the hook").with_explanation(format!("{error}"))
                }
            };
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };
    let shown = hook.strip_prefix(root).map_or_else(
        |_| hook.display().to_string(),
        |path| path.display().to_string(),
    );
    println!(
        "{} {}  {}",
        console.paint(Tone::Success, "✓"),
        console.paint(Tone::Success, message),
        console.paint(Tone::Muted, shown)
    );
    println!(
        "{}",
        console.paint(
            Tone::Muted,
            "Every push now runs `opi --check push`; `git push --no-verify` skips it."
        )
    );
    ExitCode::SUCCESS
}

/// Writes a CycloneDX SBOM per ecosystem, into `out` or the project root.
///
/// A relative `out` is relative to where `opi` was started, not to the project
/// root. Each ecosystem is tried; the exit code fails if any of them did.
fn sbom(project: &Project, rust_root: Option<&Path>, root: &Path, out: Option<&str>) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let out = match out {
        Some(dir) => PathBuf::from(dir),
        None => match sbom::default_dir(root) {
            Ok(dir) => dir,
            Err(error) => {
                let block =
                    ErrorBlock::new("No place for the SBOM").with_explanation(format!("{error:?}"));
                write_block(&block, Console::stderr(ColorMode::Auto));
                return ExitCode::FAILURE;
            }
        },
    };
    let mut results = Vec::new();
    if project.npm {
        results.push((
            "npm",
            sbom::npm(project.package_manager.manager, root, &out),
        ));
    }
    if let Some(rust_root) = rust_root {
        results.push(("Cargo", sbom::cargo(rust_root, &out)));
    }
    if results.is_empty() {
        let block = ErrorBlock::new("Nothing to describe")
            .with_remedy("An SBOM needs a package.json or a Cargo.toml.");
        write_block(&block, Console::stderr(ColorMode::Auto));
        return ExitCode::FAILURE;
    }
    let mut ok = true;
    for (ecosystem, result) in results {
        match result {
            Ok(path) => println!(
                "{} {}  {}",
                console.paint(Tone::Success, "✓"),
                ecosystem,
                console.paint(Tone::Muted, path.display().to_string())
            ),
            Err(error) => {
                ok = false;
                let block = match error {
                    sbom::SbomError::Missing { tool, install } => {
                        ErrorBlock::new(format!("{ecosystem}: {tool} is not installed"))
                            .with_remedy(format!("Install it with {install}."))
                    }
                    sbom::SbomError::Failed(reason) => {
                        ErrorBlock::new(format!("{ecosystem}: no SBOM written"))
                            .with_explanation(reason)
                    }
                };
                write_block(&block, Console::stderr(ColorMode::Auto));
            }
        }
    }
    if ok {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// Shows which dependencies have moved on, separated by how far.
///
/// Rendered as a runemark `Report` rather than a hand-set table: the split
/// between safe and breaking is the whole value of this screen, and a report's
/// groups make it structural instead of a sentence underneath a list.
fn updates(
    manifest: &Manifest,
    members: &[workspace::Member],
    project: &Project,
    rust_root: Option<&Path>,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let manager = project.package_manager.manager;

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "updates")
    );
    println!();

    // As in `security`: without a package.json the package manager here is a
    // fallback, not a detection, and asking it would be a guess dressed up as
    // a result.
    let workspace = workspace::declared(root, manifest);
    let listed = if project.npm {
        outdated::run(manager, root, workspace)
    } else {
        Err(outdated::OutdatedError::NoManifest)
    };
    // Kept for the menu below, which needs the names rather than the rendering.
    let npm_updates = match &listed {
        Ok(found) => found.clone(),
        Err(_) => Vec::new(),
    };
    let mut failed = section(console, "Dependencies", listed);

    // Two sections rather than one merged list, the way `--security` already
    // splits them. Safe against breaking is this area's ordering principle and
    // it holds inside an ecosystem; across two it would file `tokio` beside
    // `vite` under "Safe to take" with only the name saying which is which,
    // and "Take the safe ones" could name only one of the two commands that
    // would do it.
    if let Some(rust_root) = rust_root {
        println!();
        failed |= section(console, "Dependencies (rust)", outdated::cargo(rust_root));
    }

    if failed {
        return ExitCode::FAILURE;
    }

    apply_updates(manifest, members, project, rust_root, root, &npm_updates)
}

/// Offers to take the updates, and runs the checks on what comes back.
///
/// Only npm's side is applied. `cargo update` writes the lockfile, which is
/// the line this area does not cross.
fn apply_updates(
    manifest: &Manifest,
    members: &[workspace::Member],
    project: &Project,
    rust_root: Option<&Path>,
    root: &Path,
    found: &[outdated::Update],
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let manager = project.package_manager.manager;
    let workspace = workspace::declared(root, manifest);

    let in_range = found.iter().filter(|update| update.in_range).count();
    let safe: Vec<String> = found
        .iter()
        .filter(|update| !update.jump.breaking())
        .map(|update| update.name.clone())
        .collect();
    let raises = outdated::can_raise(manager) && !safe.is_empty();
    let decides = outdated::can_raise(manager) && !found.is_empty();
    // Offered without a finding to justify it: `opi` could not read bun's
    // list, so it cannot know whether anything is outdated — bun's own list
    // can, and says so when nothing is.
    let chooses = project.npm && outdated::can_choose(manager);

    if in_range == 0 && !raises && !decides && !chooses {
        return ExitCode::SUCCESS;
    }

    // Writing is where a wrong detection stops being an annoyance. `pnpm
    // update` in a repository that actually runs npm leaves a pnpm-lock.yaml,
    // and the next `npm ci` resolves against something nobody saw. The listing
    // above keeps guessing silently; this does not.
    if let Some(conflict) = project::conflict(root, project.package_manager) {
        println!();
        println!(
            "{}",
            console.paint(
                Tone::Muted,
                format!(
                    "Not offering to apply these: {} both present, and no packageManager field says which. Adding one answers it.",
                    conflict.lockfiles.join(" and ")
                )
            )
        );
        return ExitCode::SUCCESS;
    }

    println!();
    let mut group = Group::new("Update");
    if in_range > 0 {
        group = group.add_item(
            Item::new("in-range", "Within the declared ranges")
                .with_description(format!("{in_range} packages, no package.json touched")),
        );
    }
    if raises {
        group = group.add_item(
            Item::new("latest", "Raise the ranges").with_description(format!(
                "{} safe, majors left out",
                plural(safe.len(), "package", "packages")
            )),
        );
    }
    if decides {
        group = group.add_item(
            Item::new("decide", "Decide per package")
                .with_description("tick what to raise, majors included"),
        );
    }
    if chooses {
        group = group.add_item(
            Item::new("choose", format!("Choose in {manager}'s own list"))
                .with_description("its interactive update, then the commit checks"),
        );
    }
    let menu = Menu::new().add_group(group.add_item(Item::new("cancel", "Cancel")));

    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();
    let chosen = match menu.run(
        Console::stderr(ColorMode::Auto),
        SelectMode::Auto,
        interactive,
    ) {
        Ok(Outcome::Selected(id)) => id,
        // Nothing is changed without someone choosing it, so a pipe gets the
        // list and stops there, as `--clean` does.
        Ok(Outcome::Unavailable) => {
            println!(
                "{}",
                console.paint(
                    Tone::Muted,
                    "Run opi --updates in a terminal to take any of them."
                )
            );
            return ExitCode::SUCCESS;
        }
        Ok(_) => return ExitCode::SUCCESS,
        Err(error) => {
            let block =
                ErrorBlock::new("Cannot open the terminal").with_explanation(format!("{error}"));
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    let (mode, names) = match chosen.as_str() {
        "in-range" => (outdated::Apply::InRange, safe),
        "latest" => (outdated::Apply::Latest, safe),
        "decide" => match pick_updates(found, &safe) {
            Some(picked) => (outdated::Apply::Latest, picked),
            None => return ExitCode::SUCCESS,
        },
        "choose" => (outdated::Apply::Choose, Vec::new()),
        _ => return ExitCode::SUCCESS,
    };
    if names.is_empty() && mode == outdated::Apply::Latest {
        return ExitCode::SUCCESS;
    }

    println!();
    if let Err(error) = outdated::apply(manager, root, workspace, mode, &names) {
        // The manager has already said why on the terminal it inherited; this
        // only stops the chain rather than repeating it.
        let block = ErrorBlock::new("The update did not finish")
            .with_explanation(format!("{error}"))
            .with_remedy("The package manager's own output above says why.");
        write_block(&block, Console::stderr(ColorMode::Auto));
        return ExitCode::FAILURE;
    }

    // The point of applying from here rather than retyping one line: what the
    // update broke is the next question, and nothing else puts the two
    // together. Measured at 1.4s here and 10.6s on the largest workspace, so
    // it is not a wait worth asking about first.
    println!();
    run_workflow("commit", manifest, members, rust_root, project, root)
}

/// Lets each update be ticked, returning the names to raise.
///
/// The safe ones start ticked and the majors do not, so the default answer is
/// the one "Raise the ranges" gives and a major is only taken on purpose.
/// `None` when the list was left without confirming.
fn pick_updates(found: &[outdated::Update], safe: &[String]) -> Option<Vec<String>> {
    let mut menu = Menu::new()
        .with_heading("Raise the ranges")
        .with_ticked(safe.iter().cloned());
    for (title, breaking) in [("Safe to take", false), ("A decision each", true)] {
        let mut group = Group::new(title);
        for update in found
            .iter()
            .filter(|update| update.jump.breaking() == breaking)
        {
            group = group.add_item(Item::new(&update.name, &update.name).with_description(
                format!(
                    "{} → {}  {}",
                    update.current,
                    update.latest,
                    update.jump.label()
                ),
            ));
        }
        if !group.items.is_empty() {
            menu = menu.add_group(group);
        }
    }

    match menu.run_multi(Console::stderr(ColorMode::Auto), SelectMode::Auto, true) {
        Ok(Picked::Chosen(names)) => Some(names),
        _ => None,
    }
}

/// Renders one ecosystem's updates, returning whether the run itself failed.
///
/// Nothing outdated and output `opi` cannot read are both said in a line and
/// leave the exit code clean: neither is a failure, and an empty section would
/// read as "nothing to report", which is the one thing it must not say where
/// nothing was asked.
fn section(
    console: Console,
    title: &str,
    listed: Result<Vec<outdated::Update>, outdated::OutdatedError>,
) -> bool {
    let found = match listed {
        Ok(found) if found.is_empty() => {
            println!(
                "{} {}",
                console.paint(Tone::Success, "✓"),
                console.paint(Tone::Success, format!("{title} — everything is current"))
            );
            return false;
        }
        Ok(found) => found,
        Err(error) => {
            let fatal = matches!(error, outdated::OutdatedError::Failed(_));
            println!(
                "{} {}",
                console.paint(Tone::Muted, "–"),
                console.paint(Tone::Muted, format!("{title} — {error}"))
            );
            return fatal;
        }
    };

    let (breaking, safe): (Vec<_>, Vec<_>) =
        found.iter().partition(|update| update.jump.breaking());

    let mut report = Report::new(
        title,
        if breaking.is_empty() {
            Verdict::Info
        } else {
            Verdict::Warning
        },
    )
    .with_detail_level(DetailLevel::Detailed);

    if !safe.is_empty() {
        report = report.add_metric(Metric::new("safe", safe.len().to_string()));
    }
    if !breaking.is_empty() {
        report = report
            .add_metric(Metric::new("major", breaking.len().to_string()).with_tone(Tone::Warning));
    }

    for (group_title, tone, group) in [
        ("Safe to take", Tone::Muted, &safe),
        ("A decision each", Tone::Warning, &breaking),
    ] {
        if group.is_empty() {
            continue;
        }
        let mut findings = FindingGroup::new(group_title);
        for update in group.iter() {
            findings = findings.add_finding(
                Finding::new(
                    tone,
                    format!("{} {} → {}", update.name, update.current, update.latest),
                )
                .with_rule_id(update.jump.label()),
            );
        }
        report = report.add_group(findings);
    }

    // No next step naming an update command. Measured, `pnpm update` moves
    // none of what this calls safe in a project whose ranges are exact or
    // `~` — the choice offered below is the one that exists.

    // No width hint: two metrics read better side by side than stacked, and
    // the findings wrap on their own.
    print!("{}", report.render(console));
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::task::Group as TaskGroup;

    fn task(name: &str, group: TaskGroup) -> Task {
        Task {
            name: name.to_owned(),
            description: None,
            command: name.to_owned(),
            group,
            exec: task::Exec::Script,
            confirm: false,
            workspace: None,
            hidden: false,
        }
    }

    fn sections(counts: &[(TaskGroup, usize)]) -> Vec<Task> {
        counts
            .iter()
            .flat_map(|(group, count)| {
                (0..*count).map(move |n| task(&format!("s{n}"), group.clone()))
            })
            .collect()
    }

    #[test]
    fn a_short_list_stays_flat() {
        // The 0.1.0 screen: everything visible at once, no row of tabs above
        // it saying what would fit anyway.
        assert_eq!(layout(12, 4), Layout::Flat);
        assert_eq!(layout(15, 5), Layout::Flat, "the thresholds are inclusive");
    }

    #[test]
    fn a_long_list_becomes_tabs() {
        // web-casoon: 27 entries in 7 groups, 34 lines with a heading each.
        assert_eq!(layout(27, 7), Layout::Tabs);
    }

    #[test]
    fn either_count_is_enough_on_its_own() {
        // Few entries spread very thin still costs a heading per group, and
        // many entries in two groups still scroll.
        assert_eq!(layout(8, 8), Layout::Tabs);
        assert_eq!(layout(30, 2), Layout::Tabs);
    }

    #[test]
    fn the_summary_counts_entries_and_groups() {
        let tasks = sections(&[
            (TaskGroup::Development, 4),
            (TaskGroup::Build, 7),
            (TaskGroup::Quality, 4),
        ]);
        let sections = by_group(&tasks);
        assert_eq!(summary(&sections, 15, &[]), "15 entries · 3 groups");
    }

    #[test]
    fn a_project_with_no_workspace_says_nothing_about_packages() {
        // "1 package" would answer a question nobody in a single-package
        // project has.
        let tasks = sections(&[(TaskGroup::Development, 1)]);
        let sections = by_group(&tasks);
        assert!(!summary(&sections, 1, &[]).contains("package"));
        assert_eq!(summary(&sections, 1, &[]), "1 entry · 1 group");
    }

    #[test]
    fn the_summary_counts_workspace_packages() {
        let tasks = sections(&[
            (TaskGroup::Development, 2),
            (TaskGroup::Workspace("@casoon/blog".to_owned()), 1),
            (TaskGroup::Workspace("@casoon/starter".to_owned()), 1),
        ]);
        let sections = by_group(&tasks);
        assert_eq!(
            summary(&sections, 4, &[]),
            "4 entries · 3 groups · 2 packages"
        );
    }

    #[test]
    fn the_summary_names_other_task_runners() {
        let tasks = sections(&[(TaskGroup::Development, 2)]);
        let sections = by_group(&tasks);
        assert_eq!(
            summary(&sections, 2, &["Makefile".to_owned()]),
            "2 entries · 1 group · also Makefile"
        );
    }
}