cbh_cli 0.2.5

Implementation crate for cargo-bench-history - do not reference directly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
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
//! Argument parsing: the `clap` subcommand surface and its translation into the
//! typed [`Command`](cbh_command::Command) model.
//!
//! The wide option surface is organized into named help groups (Environment,
//! Output, Discriminant selection, Commit selection, Data filtering, Benchmark
//! scope) so `--help` makes the relationship between options legible. Shared
//! groups are factored into [`clap::Args`] structs and `#[command(flatten)]`ed
//! into each subcommand so the same option means the same thing everywhere.

use std::num::NonZeroUsize;
use std::path::PathBuf;

use cbh_command::{
    AnalyzeOptions, BackfillOptions, BlessOptions, CacheSelection, CollectOptions, Command,
    ExamineOptions, ImportOptions, InstallOptions, ListOptions, ListSubject, LocalStorageSelection,
    MachineKeyOptions, PruneOptions, UnblessOptions,
};
use cbh_model::BenchmarkIdPrefix;
use clap::{ArgGroup, Args, Parser, Subcommand as ClapSubcommand, ValueEnum};

const HEADING_ENV: &str = "Environment and execution";
const HEADING_OUTPUT: &str = "Output";
const HEADING_DISCRIMINANT: &str = "Discriminant selection";
const HEADING_COMMIT: &str = "Commit selection";
const HEADING_FILTER: &str = "Data filtering";
const HEADING_SCOPE: &str = "Benchmark scope";
const HEADING_FEATURES: &str = "Feature selection";

/// Maintain a history of benchmark results over time and analyze it for trends.
#[derive(Debug, Parser)]
#[command(
    name = "cargo-bench-history",
    about = "Maintain a history of benchmark results over time and analyze it for trends.",
    disable_help_subcommand = true,
    disable_version_flag = true
)]
pub struct Cli {
    /// The subcommand to execute.
    #[command(subcommand)]
    command: Subcommand,
}

/// A parse outcome that should terminate the program before execution.
///
/// This is either a help/usage request (success, printed to stdout) or a parse
/// error (failure, printed to stderr). Mirrors the shape the binary entry point
/// consumes.
#[derive(Debug)]
pub struct EarlyExit {
    /// The rendered message (help text or error) to print.
    pub output: String,
    /// `Ok` for a help/usage request (exit success), `Err` for a parse error.
    pub status: Result<(), ()>,
}

impl EarlyExit {
    /// Classifies a `clap` parse error into the success/failure early-exit shape.
    fn from_clap(error: &clap::Error) -> Self {
        use clap::error::ErrorKind;
        let success = matches!(
            error.kind(),
            ErrorKind::DisplayHelp
                | ErrorKind::DisplayVersion
                | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
        );
        Self {
            output: error.to_string(),
            status: if success { Ok(()) } else { Err(()) },
        }
    }
}

impl Cli {
    /// Parses an argument vector (program name followed by its arguments) into the
    /// typed CLI, returning an [`EarlyExit`] for a help request or a parse error.
    ///
    /// # Errors
    ///
    /// Returns an [`EarlyExit`] when the arguments request help/usage or fail to
    /// parse.
    pub fn from_args(command_name: &[&str], args: &[&str]) -> Result<Self, EarlyExit> {
        let argv: Vec<&str> = command_name.iter().chain(args).copied().collect();
        Self::try_parse_from(argv).map_err(|error| EarlyExit::from_clap(&error))
    }

    /// Translates the parsed arguments into the typed command model.
    #[must_use]
    pub fn into_command(self) -> Command {
        match self.command {
            Subcommand::Analyze(command) => Command::Analyze(command.into_options()),
            Subcommand::Backfill(command) => Command::Backfill(command.into_options()),
            Subcommand::Bless(command) => Command::Bless(command.into_options()),
            Subcommand::Collect(command) => Command::Collect(command.into_options()),
            Subcommand::Examine(command) => Command::Examine(command.into_options()),
            Subcommand::Import(command) => Command::Import(command.into_options()),
            Subcommand::Install(command) => Command::Install(command.into_options()),
            Subcommand::List(command) => Command::List(command.into_options()),
            Subcommand::MachineKey(command) => Command::MachineKey(command.into_options()),
            Subcommand::Prune(command) => Command::Prune(command.into_options()),
            Subcommand::Unbless(command) => Command::Unbless(command.into_options()),
        }
    }

    /// The top-level help text, including the command list with descriptions.
    ///
    /// Shown when the tool is invoked with no subcommand, so the available
    /// commands and what each one does are immediately visible.
    #[must_use]
    pub fn help(program_name: &str) -> String {
        // `--help` is always reported as an early exit carrying the rendered
        // help text, so the `Ok` arm is never taken in practice.
        Self::from_args(&[program_name], &["--help"])
            .err()
            .map(|early_exit| early_exit.output)
            .unwrap_or_default()
    }
}

#[derive(ClapSubcommand, Debug)]
enum Subcommand {
    /// Analyze stored history for notable patterns.
    Analyze(AnalyzeCommand),
    /// Replay `collect` across a range of historical commits.
    Backfill(BackfillCommand),
    /// Accept a benchmark's current level on the base branch as intentional.
    Bless(BlessCommand),
    /// Run the workspace benchmarks (`cargo bench`) and store the results.
    Collect(CollectCommand),
    /// Import pre-existing engine output into storage without running a benchmark
    /// engine (the collect pipeline minus `cargo bench`). Internal and hidden: it
    /// exists to validate the storage/analysis pipeline against curated engine
    /// output (for example, output produced by `cargo-bench-history-faker`), so it
    /// is kept out of the public help.
    #[command(hide = true)]
    Import(ImportCommand),
    /// Generate a starter configuration file.
    Install(InstallCommand),
    /// List the data set a matching `analyze` would include, without analyzing it.
    List(ListCommand),
    /// Print this machine's hardware fingerprint (the machine key).
    MachineKey(MachineKeyCommand),
    /// Show the raw per-commit data points of one `(benchmark, metric)` series.
    Examine(ExamineCommand),
    /// Delete stored runs (and their blessing sidecars) from the resolved data set.
    Prune(PruneCommand),
    /// Remove blessings recorded at the current commit.
    Unbless(UnblessCommand),
}

/// Environment and execution options shared by every command that reads a
/// repository's git state.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_ENV)]
struct EnvArgs {
    /// Path to the configuration file (defaults to `.cargo/bench_history.toml`).
    /// A relative path is resolved against the working directory (not the target
    /// repository).
    #[arg(long, value_name = "PATH")]
    config: Option<PathBuf>,

    /// Repository to resolve git state from (defaults to the working directory).
    #[arg(long, value_name = "PATH")]
    repo: Option<PathBuf>,

    /// Use local filesystem storage instead of a configured cloud backend.
    ///
    /// `--local=<path>` stores history under `<path>` (a relative path resolves
    /// against the target repository — the working directory by default, or
    /// `--repo`). A bare `--local` (no value) reads the path from the
    /// `CARGO_BENCH_HISTORY_STORAGE` environment variable. Either form overrides
    /// the cloud backend in the configuration file; without `--local`, the
    /// configured cloud backend is used.
    #[arg(long, value_name = "PATH", num_args = 0..=1, require_equals = true)]
    #[expect(
        clippy::option_option,
        reason = "clap's representation of a three-state optional-value flag: absent (None), bare \
                  --local (Some(None) -> read the env var), or --local=<path> (Some(Some(path)))"
    )]
    local: Option<Option<PathBuf>>,

    /// Emit detailed diagnostic notes to standard error describing each step.
    #[arg(long)]
    verbose: bool,
}

/// Translates the `--local` flag into the typed [`LocalStorageSelection`].
///
/// `None` (flag absent) selects the configured cloud backend; `Some(Some(p))`
/// (`--local=<path>`) selects an explicit local path; `Some(None)` (bare
/// `--local`) selects the path from `CARGO_BENCH_HISTORY_STORAGE`.
#[expect(
    clippy::option_option,
    reason = "mirrors the clap field's three-state optional-value representation, mapped here to \
              the typed LocalStorageSelection"
)]
fn local_selection(local: Option<Option<PathBuf>>) -> Option<LocalStorageSelection> {
    match local {
        None => None,
        Some(Some(path)) => Some(LocalStorageSelection::Path(path)),
        Some(None) => Some(LocalStorageSelection::FromEnv),
    }
}

/// Translates the `--cache` flag into the typed [`CacheSelection`].
///
/// Mirrors [`local_selection`]'s three-state mapping: `None` (flag absent) selects
/// no cache; `Some(Some(p))` (`--cache=<path>`) selects an explicit cache
/// directory; `Some(None)` (bare `--cache`) selects the directory from
/// `CARGO_BENCH_HISTORY_CACHE`.
#[expect(
    clippy::option_option,
    reason = "mirrors the clap field's three-state optional-value representation, mapped here to \
              the typed CacheSelection"
)]
fn cache_selection(cache: Option<Option<PathBuf>>) -> Option<CacheSelection> {
    match cache {
        None => None,
        Some(Some(path)) => Some(CacheSelection::Path(path)),
        Some(None) => Some(CacheSelection::FromEnv),
    }
}

/// The `--cache` read-through cache selection, shared by the read commands
/// `analyze`, `list`, and `prune` (the write commands take no cache: they do not
/// read the bulk history). Kept out of [`EnvArgs`] so only the read commands carry
/// it, but placed in the same **Environment and execution** help group.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_ENV)]
struct CacheArg {
    /// Mirror fetched cloud objects under a local directory so repeated reads avoid
    /// re-downloading the whole history.
    ///
    /// `--cache=<path>` mirrors under `<path>` (a relative path resolves against
    /// the target repository — the working directory by default, or `--repo`). A
    /// bare `--cache` (no value) reads the directory from the
    /// `CARGO_BENCH_HISTORY_CACHE` environment variable. The cache applies only to
    /// the cloud backend, so it conflicts with `--local` (a local backend's reads
    /// are already on disk).
    #[arg(
        long,
        value_name = "PATH",
        num_args = 0..=1,
        require_equals = true,
        conflicts_with = "local"
    )]
    #[expect(
        clippy::option_option,
        reason = "clap's representation of a three-state optional-value flag: absent (None), bare \
                  --cache (Some(None) -> read the env var), or --cache=<path> (Some(Some(path)))"
    )]
    cache: Option<Option<PathBuf>>,
}

/// The repeatable, `all`-aware discriminant filters used by every query command.
///
/// Each filter auto-detects the current machine when omitted (`--engine` has no
/// machine-derived value, so it auto-detects to every engine); repeating a filter
/// unions its values; the literal `all` removes the filter for that dimension.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_DISCRIMINANT)]
struct QueryDiscriminantArgs {
    /// Restrict to these engines, e.g. `criterion`/`callgrind` (repeatable; `all`
    /// matches every engine; default: every engine).
    #[arg(long, value_name = "NAME")]
    engine: Vec<String>,

    /// Restrict to these full target triples, e.g. `x86_64-unknown-linux-gnu`
    /// (repeatable; `all` matches every triple; default: this machine's triple).
    #[arg(long, value_name = "TRIPLE")]
    target_triple: Vec<String>,

    /// Restrict to these machine keys (repeatable; `all` matches every
    /// machine; default: this machine's fingerprint).
    #[arg(long, value_name = "KEY")]
    machine_key: Vec<String>,
}

/// Commit selection shared by `analyze`/`list`.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_COMMIT)]
struct TimelineArgs {
    /// Target ref whose history is used (defaults to HEAD).
    #[arg(long, value_name = "REF")]
    context: Option<String>,

    /// Base ref the target branched off from (defaults to the default branch).
    #[arg(long, value_name = "REF")]
    base: Option<String>,

    /// Only consider commits made on or after this cutoff: an RFC 3339 timestamp,
    /// a `YYYY-MM-DD` date, or a relative duration such as `6 months ago`.
    #[arg(long, value_name = "WHEN")]
    since: Option<String>,
}

/// Per-format report output shared by `analyze`/`list`/`prune`.
///
/// The text report prints to standard output by default; `--no-text` suppresses
/// it, while `--markdown` and `--json` each write that format to a file. A single
/// analysis pass backs every requested format. At least one output must remain
/// selected, so `--no-text` requires at least one of `--markdown`/`--json`.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_OUTPUT)]
struct OutputArgs {
    /// Suppress the text report on standard output. Pair with `--markdown` and/or
    /// `--json` to direct the report to files instead.
    #[arg(long)]
    no_text: bool,

    /// Also write the Markdown report to this path (a relative path resolves
    /// against the working directory).
    #[arg(long, value_name = "PATH")]
    markdown: Option<PathBuf>,

    /// Also write the JSON report to this path (a relative path resolves against
    /// the working directory).
    #[arg(long, value_name = "PATH")]
    json: Option<PathBuf>,
}

/// Run the workspace benchmarks (`cargo bench`) and store the results.
#[derive(Args, Debug)]
struct CollectCommand {
    #[command(flatten)]
    env: EnvArgs,

    /// Benchmark the entire workspace (the default when no `--package` is given);
    /// conflicts with `--package`.
    #[arg(long, help_heading = HEADING_SCOPE, conflicts_with = "package")]
    workspace: bool,

    /// Benchmark only this package; repeatable, e.g. `-p nm -p many_cpus`
    /// (default: the whole workspace).
    #[arg(long = "package", short = 'p', value_name = "NAME", help_heading = HEADING_SCOPE)]
    package: Vec<String>,

    /// Exclude a package from a whole-workspace run; repeatable, e.g.
    /// `--exclude nm --exclude many_cpus`. Conflicts with `--package`.
    #[arg(long, value_name = "NAME", help_heading = HEADING_SCOPE, conflicts_with = "package")]
    exclude: Vec<String>,

    /// Benchmark only this bench target; repeatable (default: every bench target).
    #[arg(long, value_name = "NAME", help_heading = HEADING_SCOPE)]
    bench: Vec<String>,

    /// Activate cargo features for the benchmark build; space- or comma-separated,
    /// repeatable. Forwarded verbatim to `cargo bench` as `--features`.
    #[arg(long, value_name = "FEATURES", help_heading = HEADING_FEATURES)]
    features: Vec<String>,

    /// Activate all cargo features of all selected packages (`--all-features`).
    #[arg(long, help_heading = HEADING_FEATURES)]
    all_features: bool,

    /// Do not activate the `default` cargo feature (`--no-default-features`).
    #[arg(long, help_heading = HEADING_FEATURES)]
    no_default_features: bool,

    /// Harvest and build results without storing them.
    #[arg(long, help_heading = HEADING_ENV)]
    no_store: bool,

    /// Replace an already-stored result for this run instead of refusing it as a
    /// duplicate.
    #[arg(long, help_heading = HEADING_ENV)]
    overwrite: bool,

    /// Treat an already-stored result for this run as a success that writes
    /// nothing, instead of refusing it as a duplicate. Mutually exclusive with
    /// `--overwrite`; the append-only mode the CI collection uses.
    #[arg(long, help_heading = HEADING_ENV, conflicts_with = "overwrite")]
    skip_existing: bool,

    /// Run the whole suite this many times and keep, per metric, the best
    /// (minimum) observed value — a noise-reduction pass for jittery runners.
    /// Every run must produce the same benchmark cases and the same metrics
    /// per case or collection fails.
    #[arg(long = "best-of", value_name = "N", default_value_t = NonZeroUsize::MIN, help_heading = HEADING_ENV)]
    best_of: NonZeroUsize,

    /// Arguments after `--` forwarded verbatim to `cargo bench` after the scope
    /// flags.
    #[arg(last = true, value_name = "ARGS")]
    passthrough: Vec<String>,
}

impl CollectCommand {
    fn into_options(self) -> CollectOptions {
        CollectOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            packages: resolve_packages(self.workspace, self.package),
            excludes: self.exclude,
            benches: self.bench,
            features: self.features,
            all_features: self.all_features,
            no_default_features: self.no_default_features,
            no_store: self.no_store,
            overwrite: self.overwrite,
            skip_existing: self.skip_existing,
            passthrough: self.passthrough,
            verbose: self.env.verbose,
            best_of: self.best_of,
        }
    }
}

/// Import pre-existing engine output into storage (the collect pipeline minus the
/// `cargo bench` run). Internal and hidden.
///
/// It keeps collect's environment/storage flags and adds the required scan
/// directory plus the metadata overrides that let one host synthesize data for
/// another target triple or commit. It has no benchmark-scope or feature flags
/// because it never runs a build.
#[derive(Args, Debug)]
struct ImportCommand {
    #[command(flatten)]
    env: EnvArgs,

    /// The directory tree to scan for pre-existing engine output. Required, with
    /// no default: an ungated harvest of the shared `target/` directory would
    /// sweep stale leftovers from unrelated runs into one import, so the caller
    /// must name the tree it curated.
    #[arg(long, value_name = "PATH", help_heading = HEADING_ENV)]
    target_dir: PathBuf,

    /// Override the target triple the results are partitioned under (and recorded
    /// against), so a single host can synthesize data for another target.
    #[arg(long, value_name = "TRIPLE", help_heading = HEADING_DISCRIMINANT)]
    target_triple: Option<String>,

    /// Override the commit the run is keyed under (default: the current commit).
    /// Resolved through git, so it must name a real commit; it avoids checking the
    /// commit out, not the requirement that it exist.
    #[arg(long, value_name = "COMMIT", help_heading = HEADING_COMMIT)]
    commit: Option<String>,

    /// Store a dirty snapshot keyed by the import-time second instead of a clean
    /// object, as if the working tree had uncommitted changes.
    #[arg(long, help_heading = HEADING_DISCRIMINANT)]
    dirty: bool,

    /// Replace an already-stored result for this run instead of refusing it as a
    /// duplicate.
    #[arg(long, help_heading = HEADING_ENV)]
    overwrite: bool,

    /// Treat an already-stored result for this run as a success that writes
    /// nothing, instead of refusing it as a duplicate. Mutually exclusive with
    /// `--overwrite`.
    #[arg(long, help_heading = HEADING_ENV, conflicts_with = "overwrite")]
    skip_existing: bool,
}

impl ImportCommand {
    fn into_options(self) -> ImportOptions {
        ImportOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            target_dir: self.target_dir,
            target_triple: self.target_triple,
            commit: self.commit,
            dirty: self.dirty,
            overwrite: self.overwrite,
            skip_existing: self.skip_existing,
            verbose: self.env.verbose,
        }
    }
}

/// Generate a starter configuration file.
#[derive(Args, Debug)]
struct InstallCommand {
    /// Path to the configuration file to generate.
    #[arg(long, value_name = "PATH", help_heading = HEADING_ENV)]
    config: Option<PathBuf>,

    /// Emit detailed diagnostic notes to standard error (which path is written,
    /// or that an existing configuration was left unchanged).
    #[arg(long, help_heading = HEADING_ENV)]
    verbose: bool,
}

impl InstallCommand {
    fn into_options(self) -> InstallOptions {
        InstallOptions {
            config_path: self.config,
            verbose: self.verbose,
        }
    }
}

/// Print this machine's hardware fingerprint (the machine key).
#[derive(Args, Debug)]
struct MachineKeyCommand {
    /// Also emit the individual hardware factors that make up the fingerprint to
    /// standard error (the fingerprint version, processor count, memory-region
    /// count and processor models), so a change in the key can be traced to which
    /// factor changed. Per-processor speeds are recorded with collected runs as
    /// hardware provenance, but they are not factors and so are not reported here.
    /// The key itself always goes to standard output.
    #[arg(long, help_heading = HEADING_ENV)]
    verbose: bool,
}

impl MachineKeyCommand {
    fn into_options(self) -> MachineKeyOptions {
        MachineKeyOptions {
            verbose: self.verbose,
        }
    }
}

/// Analyze stored history for notable patterns.
#[derive(Args, Debug)]
struct AnalyzeCommand {
    /// Benchmark-id prefixes to analyze, matched against the qualified identity
    /// (for example, `all_the_time/read_cell` or a family prefix
    /// `overhead/groups_`); repeatable (default: every benchmark).
    #[arg(value_name = "PREFIX")]
    prefixes: Vec<BenchmarkIdPrefix>,

    #[command(flatten)]
    env: EnvArgs,

    #[command(flatten)]
    cache: CacheArg,

    #[command(flatten)]
    output: OutputArgs,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,

    #[command(flatten)]
    timeline: TimelineArgs,

    /// Exclude dirty (uncommitted-tree) snapshots from the analysis.
    #[arg(long, help_heading = HEADING_FILTER)]
    no_dirty: bool,

    /// Also write a condensed Markdown summary — only the most significant findings
    /// — to this path (a relative path resolves against the working directory). The
    /// full `--markdown` report carries every finding; this summary is capped so a
    /// large analysis still fits within a GitHub issue body.
    #[arg(long, value_name = "PATH", help_heading = HEADING_OUTPUT)]
    markdown_summary: Option<PathBuf>,
}

impl AnalyzeCommand {
    fn into_options(self) -> AnalyzeOptions {
        AnalyzeOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            cache: cache_selection(self.cache.cache),
            context: self.timeline.context,
            base: self.timeline.base,
            no_dirty: self.no_dirty,
            since: self.timeline.since,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            prefixes: self.prefixes,
            no_text: self.output.no_text,
            markdown: self.output.markdown,
            json: self.output.json,
            markdown_summary: self.markdown_summary,
            verbose: self.env.verbose,
            timing: false,
        }
    }
}

/// What a `list` invocation enumerates.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum ListSubjectArg {
    /// The runs that would enter a matching `analyze` pass.
    Runs,
    /// Every discriminant set present in storage (no repository required); a
    /// discovery catalog that lists all partitions regardless of the current
    /// machine. Pass a discriminant filter to narrow it.
    Discriminants,
    /// The blessings recorded at the current commit (or, with `--all`, across the
    /// whole analysis window).
    Blessings,
}

impl From<ListSubjectArg> for ListSubject {
    fn from(subject: ListSubjectArg) -> Self {
        match subject {
            ListSubjectArg::Runs => Self::Runs,
            ListSubjectArg::Discriminants => Self::Discriminants,
            ListSubjectArg::Blessings => Self::Blessings,
        }
    }
}

/// List the data set a matching `analyze` would include, without analyzing it.
#[derive(Args, Debug)]
struct ListCommand {
    /// What to list: `runs`, `discriminants`, or `blessings`.
    #[arg(value_name = "runs|discriminants|blessings")]
    subject: ListSubjectArg,

    #[command(flatten)]
    env: EnvArgs,

    #[command(flatten)]
    cache: CacheArg,

    #[command(flatten)]
    output: OutputArgs,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,

    #[command(flatten)]
    timeline: TimelineArgs,

    /// Exclude dirty (uncommitted-tree) snapshots from the listing.
    #[arg(long, help_heading = HEADING_FILTER)]
    no_dirty: bool,

    /// With the `blessings` subject, list the most recent blessing of every
    /// benchmark across the whole analysis window rather than only those at the
    /// current commit. Errors if given with any other subject.
    #[arg(long, help_heading = HEADING_FILTER)]
    all: bool,
}

impl ListCommand {
    fn into_options(self) -> ListOptions {
        ListOptions {
            subject: self.subject.into(),
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            cache: cache_selection(self.cache.cache),
            context: self.timeline.context,
            base: self.timeline.base,
            no_dirty: self.no_dirty,
            since: self.timeline.since,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            no_text: self.output.no_text,
            markdown: self.output.markdown,
            json: self.output.json,
            all: self.all,
            verbose: self.env.verbose,
        }
    }
}

/// Show the raw per-commit data points of one `(benchmark, metric)` series.
///
/// A drill-down sibling of `list runs`: it resolves exactly the data set a matching
/// `analyze`/`list` would, then pivots one named series into a per-commit listing —
/// every commit from the earliest one carrying the series in any matching set up to
/// the analyzed tip, in git first-parent order, pairing the value with the short
/// commit id and the start of the commit's title. A commit with several observations
/// contributes one row per observation, clean before dirty; a commit with no data
/// point reads `n/a`. Both `--benchmark` and `--metric` are required.
#[derive(Args, Debug)]
struct ExamineCommand {
    #[command(flatten)]
    env: EnvArgs,

    #[command(flatten)]
    cache: CacheArg,

    #[command(flatten)]
    output: OutputArgs,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,

    #[command(flatten)]
    timeline: TimelineArgs,

    /// The exact qualified benchmark id to examine, e.g.
    /// `nm/nm::observe/pull` (required). Copy it from an `analyze` finding.
    #[arg(long, value_name = "ID", help_heading = HEADING_SCOPE)]
    benchmark: String,

    /// The metric to examine by its stable name, e.g. `instruction_count` or
    /// `wall_time` (required). Copy it from an `analyze` finding.
    #[arg(long, value_name = "NAME", help_heading = HEADING_SCOPE)]
    metric: String,

    /// Exclude dirty (uncommitted-tree) snapshots from the pivot.
    #[arg(long, help_heading = HEADING_FILTER)]
    no_dirty: bool,
}

impl ExamineCommand {
    fn into_options(self) -> ExamineOptions {
        ExamineOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            cache: cache_selection(self.cache.cache),
            context: self.timeline.context,
            base: self.timeline.base,
            no_dirty: self.no_dirty,
            since: self.timeline.since,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            benchmark: self.benchmark,
            metric: self.metric,
            no_text: self.output.no_text,
            markdown: self.output.markdown,
            json: self.output.json,
            verbose: self.env.verbose,
        }
    }
}

/// Delete stored runs from the data set a matching `analyze`/`list` would resolve.
///
/// You must say what to delete with `--clean`, `--dirty`, `--all`, or
/// `--include-blessings`. Pruning runs never removes a blessing on its own;
/// `--include-blessings` additionally deletes blessing sidecars in the selected
/// range (including on commits with no recorded run) and may be given alone.
/// Pruning walks the selected commits from `--context` back to `--base`; deleting
/// the base branch's own data set requires the `--prune-base` guard.
#[derive(Args, Debug)]
#[command(
    group(
        ArgGroup::new("prune-action")
            .args(["clean", "dirty", "all", "include_blessings"])
            .required(true)
            .multiple(true)
    ),
    group(
        ArgGroup::new("prune-run-kind")
            .args(["clean", "dirty", "all"])
    )
)]
struct PruneCommand {
    /// Restrict removal to these commits (a full or short commit ID, prefix-matched);
    /// repeatable (default: every one of the selected commits).
    #[arg(value_name = "COMMIT")]
    commit: Vec<String>,

    #[command(flatten)]
    env: EnvArgs,

    #[command(flatten)]
    cache: CacheArg,

    /// Preview what would be removed without deleting anything.
    #[arg(long, help_heading = HEADING_ENV)]
    dry_run: bool,

    /// Confirm pruning the base branch's own data set (required when `--context`
    /// resolves to the same commit as `--base`).
    #[arg(long, help_heading = HEADING_ENV)]
    prune_base: bool,

    #[command(flatten)]
    output: OutputArgs,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,

    #[command(flatten)]
    commit_selection: PruneCommitArgs,

    /// Remove only clean runs.
    #[arg(long, help_heading = HEADING_FILTER)]
    clean: bool,

    /// Remove only dirty (uncommitted-tree) snapshots.
    #[arg(long, help_heading = HEADING_FILTER)]
    dirty: bool,

    /// Remove both clean and dirty runs (the same as `--clean --dirty`).
    #[arg(long, help_heading = HEADING_FILTER)]
    all: bool,

    /// Also remove blessing sidecars in the selected range, including on commits
    /// with no recorded run. May be given alone to remove only blessings.
    #[arg(long, help_heading = HEADING_FILTER)]
    include_blessings: bool,
}

/// Commit selection for `prune`: the range of commits whose data is removed.
#[derive(Args, Debug)]
#[command(next_help_heading = HEADING_COMMIT)]
struct PruneCommitArgs {
    /// Target ref whose data set is pruned, walking back until the base ref
    /// (defaults to HEAD).
    #[arg(long, value_name = "REF")]
    context: Option<String>,

    /// Base ref that the context branched off from; pruning stops on reaching it
    /// (defaults to the default branch).
    #[arg(long, value_name = "REF")]
    base: Option<String>,

    /// Only prune commits made on or after this cutoff: an RFC 3339 timestamp, a
    /// `YYYY-MM-DD` date, or a relative duration such as `6 months ago`.
    #[arg(long, value_name = "WHEN")]
    since: Option<String>,
}

impl PruneCommand {
    fn into_options(self) -> PruneOptions {
        // `--all` is the union of the two specific kinds.
        let clean = self.clean || self.all;
        let dirty = self.dirty || self.all;
        PruneOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            cache: cache_selection(self.cache.cache),
            context: self.commit_selection.context,
            base: self.commit_selection.base,
            commit: self.commit,
            since: self.commit_selection.since,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            clean,
            dirty,
            include_blessings: self.include_blessings,
            prune_base: self.prune_base,
            dry_run: self.dry_run,
            no_text: self.output.no_text,
            markdown: self.output.markdown,
            json: self.output.json,
            verbose: self.env.verbose,
        }
    }
}

/// Replay `collect` across a range of historical commits.
///
/// The range is walked newest commit first, so a run that is cut short has filled
/// the most recent — and most comparison-relevant — gaps.
#[derive(Args, Debug)]
struct BackfillCommand {
    /// Oldest commit of the range to backfill, inclusive; a commit ID, tag, or ref such
    /// as `HEAD~20`.
    #[arg(value_name = "FROM")]
    from: String,

    /// Newest commit of the range to backfill, inclusive; a commit ID, tag, or ref such
    /// as `HEAD`. Must be reachable from `<FROM>` along first-parent history.
    #[arg(value_name = "TO")]
    to: String,

    #[command(flatten)]
    env: EnvArgs,

    /// Benchmark the entire workspace (the default when no `--package` is given);
    /// conflicts with `--package`.
    #[arg(long, help_heading = HEADING_SCOPE, conflicts_with = "package")]
    workspace: bool,

    /// Benchmark only this package; repeatable, e.g. `-p nm -p many_cpus`
    /// (default: the whole workspace).
    #[arg(long = "package", short = 'p', value_name = "NAME", help_heading = HEADING_SCOPE)]
    package: Vec<String>,

    /// Exclude a package from a whole-workspace run; repeatable, e.g.
    /// `--exclude nm --exclude many_cpus`. Conflicts with `--package`.
    #[arg(long, value_name = "NAME", help_heading = HEADING_SCOPE, conflicts_with = "package")]
    exclude: Vec<String>,

    /// Benchmark only this bench target; repeatable (default: every bench target).
    #[arg(long, value_name = "NAME", help_heading = HEADING_SCOPE)]
    bench: Vec<String>,

    /// Activate cargo features for the benchmark build; space- or comma-separated,
    /// repeatable. Forwarded verbatim to `cargo bench` as `--features`.
    #[arg(long, value_name = "FEATURES", help_heading = HEADING_FEATURES)]
    features: Vec<String>,

    /// Activate all cargo features of all selected packages (`--all-features`).
    #[arg(long, help_heading = HEADING_FEATURES)]
    all_features: bool,

    /// Do not activate the `default` cargo feature (`--no-default-features`).
    #[arg(long, help_heading = HEADING_FEATURES)]
    no_default_features: bool,

    /// Replace already-stored results for the backfilled commits instead of
    /// skipping them as duplicates.
    #[arg(long, help_heading = HEADING_ENV)]
    overwrite: bool,

    /// Continue past commits whose build or benchmark fails instead of stopping at
    /// the newest failing one.
    #[arg(long, help_heading = HEADING_ENV)]
    ignore_errors: bool,

    /// Run the whole suite this many times per commit and keep, per metric, the
    /// best (minimum) observed value — a noise-reduction pass for jittery runners.
    /// Every run must produce the same benchmark cases and the same metrics
    /// per case or collection fails.
    #[arg(long = "best-of", value_name = "N", default_value_t = NonZeroUsize::MIN, help_heading = HEADING_ENV)]
    best_of: NonZeroUsize,

    /// Arguments after `--` forwarded verbatim to `cargo bench` after the scope
    /// flags.
    #[arg(last = true, value_name = "ARGS")]
    passthrough: Vec<String>,
}

impl BackfillCommand {
    fn into_options(self) -> BackfillOptions {
        BackfillOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            from: self.from,
            to: self.to,
            packages: resolve_packages(self.workspace, self.package),
            excludes: self.exclude,
            benches: self.bench,
            features: self.features,
            all_features: self.all_features,
            no_default_features: self.no_default_features,
            overwrite: self.overwrite,
            ignore_errors: self.ignore_errors,
            passthrough: self.passthrough,
            verbose: self.env.verbose,
            best_of: self.best_of,
        }
    }
}

/// Accept a benchmark's current level on the base branch as intentional.
#[derive(Args, Debug)]
struct BlessCommand {
    /// Benchmark-id prefixes to accept, matched against the qualified identity
    /// (for example, `all_the_time/read_cell` or a family prefix
    /// `overhead/groups_`). At least one is required unless `--all` is given.
    #[arg(value_name = "PREFIX")]
    prefixes: Vec<BenchmarkIdPrefix>,

    #[command(flatten)]
    env: EnvArgs,

    /// Accept every benchmark recorded at the context commit, with no prefixes.
    #[arg(long, conflicts_with = "prefixes")]
    all: bool,

    /// Commit to bless (defaults to HEAD). Use this to bless a commit other than
    /// the one currently checked out.
    #[arg(long, value_name = "REF", help_heading = HEADING_COMMIT)]
    context: Option<String>,

    /// Base ref the context commit must be on (defaults to the default branch).
    #[arg(long, value_name = "REF", help_heading = HEADING_COMMIT)]
    base: Option<String>,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,
}

impl BlessCommand {
    fn into_options(self) -> BlessOptions {
        BlessOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            context: self.context,
            base: self.base,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            prefixes: self.prefixes,
            all: self.all,
            verbose: self.env.verbose,
        }
    }
}

/// Remove blessings recorded at the context commit.
///
/// Only blessings recorded at the context commit are removed. Blessings issued
/// at later commits remain in effect, so the timeline may still be blessed past
/// the context commit.
#[derive(Args, Debug)]
struct UnblessCommand {
    #[command(flatten)]
    env: EnvArgs,

    /// Commit to unbless (defaults to HEAD). Use this to unbless a commit other
    /// than the one currently checked out.
    #[arg(long, value_name = "REF", help_heading = HEADING_COMMIT)]
    context: Option<String>,

    /// Base ref the context commit must be on (defaults to the default branch).
    #[arg(long, value_name = "REF", help_heading = HEADING_COMMIT)]
    base: Option<String>,

    #[command(flatten)]
    discriminants: QueryDiscriminantArgs,
}

impl UnblessCommand {
    fn into_options(self) -> UnblessOptions {
        UnblessOptions {
            config_path: self.env.config,
            repo: self.env.repo,
            local: local_selection(self.env.local),
            context: self.context,
            base: self.base,
            engine: self.discriminants.engine,
            target_triple: self.discriminants.target_triple,
            machine_key: self.discriminants.machine_key,
            verbose: self.env.verbose,
        }
    }
}

/// Resolves the benchmark scope. `--workspace` and `--package` are mutually
/// exclusive at the CLI level, so `--workspace` simply yields the empty package
/// list that means "the whole workspace" — the same as passing no scope at all.
fn resolve_packages(workspace: bool, package: Vec<String>) -> Vec<String> {
    if workspace { Vec::new() } else { package }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    fn parse(args: &[&str]) -> Command {
        Cli::from_args(&["cargo-bench-history"], args)
            .unwrap()
            .into_command()
    }

    #[test]
    fn cli_is_debug_formatted() {
        let cli = Cli::from_args(&["cargo-bench-history"], &["collect"]).unwrap();
        assert!(format!("{cli:?}").contains("Collect"), "{cli:?}");
    }

    #[test]
    fn help_lists_every_command() {
        let help = Cli::help("cargo-bench-history");
        assert!(!help.is_empty(), "help text is non-empty");
        for command in [
            "analyze", "backfill", "bless", "collect", "examine", "install", "list", "prune",
            "unbless",
        ] {
            assert!(help.contains(command), "help lists {command}: {help}");
        }
    }

    #[test]
    fn import_is_hidden_from_help() {
        // `import` parses (it is registered below) but is deliberately kept out of
        // the public help, so it must not appear as an entry in the command list.
        // Match the subcommand name as the first token of a help line rather than a
        // bare substring, so an unrelated word like "important" in a description
        // cannot mask a regression that re-exposes the command.
        let help = Cli::help("cargo-bench-history");
        let listed = help
            .lines()
            .any(|line| line.split_whitespace().next() == Some("import"));
        assert!(!listed, "import is hidden from help: {help}");
    }

    #[test]
    fn import_parses_target_dir_and_metadata_overrides() {
        let command = parse(&[
            "import",
            "--target-dir",
            "curated/target",
            "--target-triple",
            "aarch64-apple-darwin",
            "--commit",
            "release-1.0",
            "--dirty",
            "--overwrite",
        ]);
        let Command::Import(options) = command else {
            panic!("expected import command");
        };
        assert_eq!(options.target_dir, PathBuf::from("curated/target"));
        assert_eq!(
            options.target_triple.as_deref(),
            Some("aarch64-apple-darwin")
        );
        assert_eq!(options.commit.as_deref(), Some("release-1.0"));
        assert!(options.dirty);
        assert!(options.overwrite);
        assert!(!options.skip_existing);
    }

    #[test]
    fn import_requires_target_dir() {
        // The harvest is ungated, so the tree to scan must be named explicitly
        // rather than defaulting to the shared `target/` directory.
        let error = Cli::from_args(&["cargo-bench-history"], &["import"]).unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(error.output.contains("--target-dir"), "{}", error.output);
    }

    #[test]
    fn import_overwrite_and_skip_existing_conflict() {
        let error = Cli::from_args(
            &["cargo-bench-history"],
            &[
                "import",
                "--target-dir",
                "t",
                "--overwrite",
                "--skip-existing",
            ],
        )
        .unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn collect_parses_scope_and_passthrough() {
        let command = parse(&[
            "collect",
            "--package",
            "nm",
            "-p",
            "many_cpus",
            "--bench",
            "nm_observe",
            "--",
            "--noplot",
        ]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert_eq!(
            options.packages,
            vec!["nm".to_owned(), "many_cpus".to_owned()]
        );
        assert_eq!(options.benches, vec!["nm_observe".to_owned()]);
        assert_eq!(options.passthrough, vec!["--noplot".to_owned()]);
        assert!(!options.overwrite);
    }

    #[test]
    fn collect_workspace_and_package_conflict() {
        let error = Cli::from_args(
            &["cargo-bench-history"],
            &["collect", "--workspace", "-p", "nm"],
        )
        .unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn collect_parses_exclude_filters() {
        let command = parse(&["collect", "--exclude", "nm", "--exclude", "many_cpus"]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert!(
            options.packages.is_empty(),
            "exclude implies workspace scope"
        );
        assert_eq!(
            options.excludes,
            vec!["nm".to_owned(), "many_cpus".to_owned()]
        );
    }

    #[test]
    fn collect_parses_feature_selection() {
        let command = parse(&[
            "collect",
            "--features",
            "foo,bar",
            "--features",
            "baz",
            "--no-default-features",
        ]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert_eq!(
            options.features,
            vec!["foo,bar".to_owned(), "baz".to_owned()]
        );
        assert!(!options.all_features);
        assert!(options.no_default_features);
    }

    #[test]
    fn collect_parses_all_features() {
        let command = parse(&["collect", "--all-features"]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert!(options.all_features);
        assert!(options.features.is_empty());
    }

    #[test]
    fn collect_best_of_defaults_to_one_and_parses_a_value() {
        let Command::Collect(options) = parse(&["collect"]) else {
            panic!("expected collect command");
        };
        assert_eq!(
            options.best_of.get(),
            1,
            "--best-of defaults to a single run"
        );

        let Command::Collect(options) = parse(&["collect", "--best-of", "5", "--no-store"]) else {
            panic!("expected collect command");
        };
        assert_eq!(options.best_of.get(), 5);
        assert!(options.no_store, "--best-of coexists with --no-store");
    }

    #[test]
    fn collect_best_of_rejects_zero() {
        let parsed = Cli::from_args(&["cargo-bench-history"], &["collect", "--best-of", "0"]);
        assert!(parsed.is_err(), "--best-of 0 must be rejected");
    }

    #[test]
    fn collect_exclude_and_package_conflict() {
        let error = Cli::from_args(
            &["cargo-bench-history"],
            &["collect", "--exclude", "nm", "-p", "many_cpus"],
        )
        .unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn backfill_workspace_and_package_conflict() {
        let error = Cli::from_args(
            &["cargo-bench-history"],
            &["backfill", "abc", "def", "--workspace", "-p", "nm"],
        )
        .unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn backfill_collects_exclude_filters() {
        let command = parse(&["backfill", "abc", "def", "--exclude", "nm"]);
        let Command::Backfill(options) = command else {
            panic!("expected backfill command");
        };
        assert!(
            options.packages.is_empty(),
            "exclude implies workspace scope"
        );
        assert_eq!(options.excludes, vec!["nm".to_owned()]);
    }

    #[test]
    fn backfill_collects_feature_selection() {
        let command = parse(&[
            "backfill",
            "abc",
            "def",
            "--features",
            "foo",
            "--all-features",
        ]);
        let Command::Backfill(options) = command else {
            panic!("expected backfill command");
        };
        assert_eq!(options.features, vec!["foo".to_owned()]);
        assert!(options.all_features);
        assert!(!options.no_default_features);
    }

    #[test]
    fn backfill_exclude_and_package_conflict() {
        let error = Cli::from_args(
            &["cargo-bench-history"],
            &[
                "backfill",
                "abc",
                "def",
                "--exclude",
                "nm",
                "-p",
                "many_cpus",
            ],
        )
        .unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn collect_parses_overwrite_switch() {
        let command = parse(&["collect", "--overwrite"]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert!(options.overwrite);
    }

    #[test]
    fn collect_parses_skip_existing_switch() {
        let command = parse(&["collect", "--skip-existing"]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert!(options.skip_existing);
        assert!(!options.overwrite);
    }

    #[test]
    fn collect_rejects_skip_existing_with_overwrite() {
        let parsed = Cli::from_args(
            &["cargo-bench-history"],
            &["collect", "--overwrite", "--skip-existing"],
        );
        assert!(
            parsed.is_err(),
            "--skip-existing and --overwrite are mutually exclusive"
        );
    }

    #[test]
    fn collect_parses_repo() {
        let command = parse(&["collect", "--repo", "/work/folo"]);
        let Command::Collect(options) = command else {
            panic!("expected collect command");
        };
        assert_eq!(options.repo, Some(PathBuf::from("/work/folo")));
    }

    #[test]
    fn local_defaults_to_none() {
        let Command::Collect(options) = parse(&["collect"]) else {
            panic!("expected collect command");
        };
        assert_eq!(options.local, None);
    }

    #[test]
    fn local_with_value_selects_an_explicit_path() {
        let Command::Collect(options) = parse(&["collect", "--local=./store"]) else {
            panic!("expected collect command");
        };
        assert_eq!(
            options.local,
            Some(LocalStorageSelection::Path(PathBuf::from("./store")))
        );
    }

    #[test]
    fn bare_local_selects_the_environment_variable() {
        let Command::Analyze(options) = parse(&["analyze", "--local"]) else {
            panic!("expected analyze command");
        };
        assert_eq!(options.local, Some(LocalStorageSelection::FromEnv));
    }

    #[test]
    fn local_requires_equals_for_its_value() {
        // Space-separated form is rejected so a trailing positional can never be
        // mistaken for the `--local` path.
        let Command::Backfill(options) = parse(&["backfill", "--local", "abc", "def"]) else {
            panic!("expected backfill command");
        };
        assert_eq!(options.local, Some(LocalStorageSelection::FromEnv));
        assert_eq!(options.from, "abc");
        assert_eq!(options.to, "def");
    }

    #[test]
    fn cache_defaults_to_none() {
        let Command::Analyze(options) = parse(&["analyze"]) else {
            panic!("expected analyze command");
        };
        assert_eq!(options.cache, None);
    }

    #[test]
    fn cache_with_value_selects_an_explicit_path() {
        let Command::Analyze(options) = parse(&["analyze", "--cache=./mirror"]) else {
            panic!("expected analyze command");
        };
        assert_eq!(
            options.cache,
            Some(CacheSelection::Path(PathBuf::from("./mirror")))
        );
    }

    #[test]
    fn bare_cache_selects_the_environment_variable() {
        let Command::List(options) = parse(&["list", "discriminants", "--cache"]) else {
            panic!("expected list command");
        };
        assert_eq!(options.cache, Some(CacheSelection::FromEnv));
    }

    #[test]
    fn prune_parses_cache() {
        let Command::Prune(options) = parse(&["prune", "--clean", "--cache=./mirror"]) else {
            panic!("expected prune command");
        };
        assert_eq!(
            options.cache,
            Some(CacheSelection::Path(PathBuf::from("./mirror")))
        );
    }

    #[test]
    fn cache_requires_equals_for_its_value() {
        // Like `--local`, the space-separated form binds nothing so a following
        // positional (an analyze prefix) is never swallowed as the cache path.
        let Command::Analyze(options) = parse(&["analyze", "--cache", "all_the_time/read_cell"])
        else {
            panic!("expected analyze command");
        };
        assert_eq!(options.cache, Some(CacheSelection::FromEnv));
        assert_eq!(
            options.prefixes,
            vec![BenchmarkIdPrefix::new("all_the_time/read_cell").unwrap()]
        );
    }

    #[test]
    fn cache_conflicts_with_local() {
        // The read-through cache applies only to the cloud backend, so pairing
        // `--cache` with `--local` is a usage error rather than a silent ignore.
        let parsed = Cli::from_args(
            &["cargo-bench-history"],
            &["analyze", "--local=./store", "--cache=./mirror"],
        );
        assert!(
            parsed.is_err(),
            "--cache and --local are mutually exclusive"
        );

        // The same conflict holds for the other read commands that carry both flags.
        assert!(
            Cli::from_args(
                &["cargo-bench-history"],
                &[
                    "list",
                    "discriminants",
                    "--local=./store",
                    "--cache=./mirror"
                ],
            )
            .is_err(),
            "list must reject --cache with --local"
        );
        assert!(
            Cli::from_args(
                &["cargo-bench-history"],
                &["prune", "--clean", "--local=./store", "--cache=./mirror"],
            )
            .is_err(),
            "prune must reject --cache with --local"
        );
    }

    #[test]
    fn collect_parses_verbose_switch() {
        let Command::Collect(options) = parse(&["collect", "--verbose"]) else {
            panic!("expected collect command");
        };
        assert!(options.verbose);

        let Command::Collect(options) = parse(&["collect"]) else {
            panic!("expected collect command");
        };
        assert!(!options.verbose);
    }

    #[test]
    fn install_maps_to_install_command() {
        let command = parse(&["install"]);
        assert_eq!(command, Command::Install(InstallOptions::default()));
    }

    #[test]
    fn install_captures_config_path() {
        let command = parse(&["install", "--config", "custom/bench.toml"]);
        let Command::Install(options) = command else {
            panic!("expected install command");
        };
        assert_eq!(
            options.config_path,
            Some(PathBuf::from("custom/bench.toml"))
        );
    }

    #[test]
    fn install_parses_verbose_switch() {
        let Command::Install(options) = parse(&["install", "--verbose"]) else {
            panic!("expected install command");
        };
        assert!(options.verbose);

        let Command::Install(options) = parse(&["install"]) else {
            panic!("expected install command");
        };
        assert!(!options.verbose);
    }

    #[test]
    fn machine_key_maps_to_machine_key_command() {
        let command = parse(&["machine-key"]);
        assert_eq!(command, Command::MachineKey(MachineKeyOptions::default()));
    }

    #[test]
    fn machine_key_parses_verbose_switch() {
        let Command::MachineKey(options) = parse(&["machine-key", "--verbose"]) else {
            panic!("expected machine-key command");
        };
        assert!(options.verbose);

        let Command::MachineKey(options) = parse(&["machine-key"]) else {
            panic!("expected machine-key command");
        };
        assert!(!options.verbose);
    }

    #[test]
    fn analyze_parses_verbose_switch() {
        let Command::Analyze(options) = parse(&["analyze", "--verbose"]) else {
            panic!("expected analyze command");
        };
        assert!(options.verbose);

        let Command::Analyze(options) = parse(&["analyze"]) else {
            panic!("expected analyze command");
        };
        assert!(!options.verbose);
    }

    #[test]
    fn analyze_collects_topology_and_repeatable_discriminants() {
        let command = parse(&[
            "analyze",
            "--repo",
            "/work/folo",
            "--context",
            "feature",
            "--base",
            "master",
            "--since",
            "2024-06-01T00:00:00Z",
            "--no-dirty",
            "--engine",
            "callgrind",
            "--engine",
            "criterion",
            "--target-triple",
            "all",
            "--machine-key",
            "ci-pool",
        ]);
        let Command::Analyze(options) = command else {
            panic!("expected analyze command");
        };
        assert_eq!(options.repo, Some(PathBuf::from("/work/folo")));
        assert_eq!(options.context.as_deref(), Some("feature"));
        assert_eq!(options.base.as_deref(), Some("master"));
        assert_eq!(options.since.as_deref(), Some("2024-06-01T00:00:00Z"));
        assert!(options.no_dirty);
        assert_eq!(
            options.engine,
            vec!["callgrind".to_owned(), "criterion".to_owned()]
        );
        assert_eq!(options.target_triple, vec!["all".to_owned()]);
        assert_eq!(options.machine_key, vec!["ci-pool".to_owned()]);
    }

    #[test]
    fn analyze_discriminants_default_to_empty() {
        let Command::Analyze(options) = parse(&["analyze"]) else {
            panic!("expected analyze command");
        };
        assert!(options.engine.is_empty());
        assert!(options.target_triple.is_empty());
        assert!(options.machine_key.is_empty());
        assert!(options.since.is_none());
    }

    #[test]
    fn until_flag_is_rejected_after_removal() {
        // `--until` was removed in favour of `--context` as the timeline's end, so
        // every command that previously accepted it now rejects it as unknown.
        for args in [
            vec!["analyze", "--until", "2024-06-01"],
            vec!["list", "runs", "--until", "2024-06-01"],
            vec![
                "examine",
                "--benchmark",
                "b",
                "--metric",
                "m",
                "--until",
                "2024-06-01",
            ],
            vec!["prune", "--dirty", "--until", "2024-06-01"],
        ] {
            let error = Cli::from_args(&["cargo-bench-history"], &args).unwrap_err();
            assert!(error.status.is_err(), "{args:?} should reject --until");
            assert!(
                error.output.contains("--until"),
                "{args:?} error should name the rejected flag: {}",
                error.output
            );
            assert!(
                error.output.contains("unexpected argument"),
                "{args:?} error should reject --until as an unexpected argument: {}",
                error.output
            );
        }
    }

    #[test]
    fn analyze_output_defaults_to_text_only() {
        let Command::Analyze(options) = parse(&["analyze"]) else {
            panic!("expected analyze command");
        };
        assert!(!options.no_text);
        assert!(options.markdown.is_none());
        assert!(options.json.is_none());
    }

    #[test]
    fn analyze_collects_output_toggles() {
        let Command::Analyze(options) = parse(&[
            "analyze",
            "--no-text",
            "--markdown",
            "out/report.md",
            "--json",
            "out/report.json",
        ]) else {
            panic!("expected analyze command");
        };
        assert!(options.no_text);
        assert_eq!(options.markdown, Some(PathBuf::from("out/report.md")));
        assert_eq!(options.json, Some(PathBuf::from("out/report.json")));
    }

    #[test]
    fn list_requires_a_subject() {
        let parsed = Cli::from_args(&["cargo-bench-history"], &["list"]);
        let early = parsed.unwrap_err();
        assert!(early.status.is_err(), "a missing subject is a parse error");
        for subject in ["runs", "discriminants", "blessings"] {
            assert!(
                early.output.contains(subject),
                "the error names the {subject} subject: {}",
                early.output
            );
        }
    }

    #[test]
    fn list_runs_collects_selection() {
        let command = parse(&[
            "list",
            "runs",
            "--repo",
            "/work/folo",
            "--context",
            "feature",
            "--base",
            "master",
            "--no-dirty",
            "--engine",
            "callgrind",
            "--target-triple",
            "x86_64-unknown-linux-gnu",
            "--machine-key",
            "ci-pool",
            "--no-text",
            "--markdown",
            "list.md",
            "--json",
            "list.json",
            "--verbose",
        ]);
        let Command::List(options) = command else {
            panic!("expected list command");
        };
        assert_eq!(options.subject, ListSubject::Runs);
        assert_eq!(options.repo, Some(PathBuf::from("/work/folo")));
        assert_eq!(options.context.as_deref(), Some("feature"));
        assert_eq!(options.base.as_deref(), Some("master"));
        assert!(options.no_dirty);
        assert_eq!(options.engine, vec!["callgrind".to_owned()]);
        assert_eq!(
            options.target_triple,
            vec!["x86_64-unknown-linux-gnu".to_owned()]
        );
        assert_eq!(options.machine_key, vec!["ci-pool".to_owned()]);
        assert!(options.no_text);
        assert_eq!(options.markdown, Some(PathBuf::from("list.md")));
        assert_eq!(options.json, Some(PathBuf::from("list.json")));
        assert!(options.verbose);
    }

    #[test]
    fn list_discriminants_selects_the_subject() {
        let Command::List(options) = parse(&["list", "discriminants"]) else {
            panic!("expected list command");
        };
        assert_eq!(options.subject, ListSubject::Discriminants);
    }

    #[test]
    fn list_blessings_collects_all_switch() {
        let Command::List(options) = parse(&["list", "blessings", "--all"]) else {
            panic!("expected list command");
        };
        assert_eq!(options.subject, ListSubject::Blessings);
        assert!(options.all);

        let Command::List(options) = parse(&["list", "blessings"]) else {
            panic!("expected list command");
        };
        assert!(!options.all);
    }

    #[test]
    fn examine_collects_selection_scope_and_output() {
        let command = parse(&[
            "examine",
            "--benchmark",
            "nm/nm::observe/pull",
            "--metric",
            "instruction_count",
            "--repo",
            "/work/folo",
            "--context",
            "feature",
            "--base",
            "master",
            "--no-dirty",
            "--engine",
            "callgrind",
            "--target-triple",
            "x86_64-unknown-linux-gnu",
            "--machine-key",
            "ci-pool",
            "--since",
            "2024-01-01",
            "--no-text",
            "--markdown",
            "examine.md",
            "--json",
            "examine.json",
            "--verbose",
        ]);
        let Command::Examine(options) = command else {
            panic!("expected examine command");
        };
        assert_eq!(options.benchmark, "nm/nm::observe/pull");
        assert_eq!(options.metric, "instruction_count");
        assert_eq!(options.repo, Some(PathBuf::from("/work/folo")));
        assert_eq!(options.context.as_deref(), Some("feature"));
        assert_eq!(options.base.as_deref(), Some("master"));
        assert!(options.no_dirty);
        assert_eq!(options.engine, vec!["callgrind".to_owned()]);
        assert_eq!(
            options.target_triple,
            vec!["x86_64-unknown-linux-gnu".to_owned()]
        );
        assert_eq!(options.machine_key, vec!["ci-pool".to_owned()]);
        assert_eq!(options.since.as_deref(), Some("2024-01-01"));
        assert!(options.no_text);
        assert_eq!(options.markdown, Some(PathBuf::from("examine.md")));
        assert_eq!(options.json, Some(PathBuf::from("examine.json")));
        assert!(options.verbose);
    }

    #[test]
    fn examine_requires_benchmark_and_metric() {
        // With neither required scope flag, clap reports both as missing.
        let early = Cli::from_args(&["cargo-bench-history"], &["examine"]).unwrap_err();
        assert!(
            early.status.is_err(),
            "missing required flags are a parse error"
        );
        assert!(early.output.contains("--benchmark"), "{}", early.output);
        assert!(early.output.contains("--metric"), "{}", early.output);

        // Supplying only one still fails, naming the other.
        let missing_metric = Cli::from_args(
            &["cargo-bench-history"],
            &["examine", "--benchmark", "nm/nm::observe/pull"],
        )
        .unwrap_err();
        assert!(missing_metric.status.is_err());
        assert!(
            missing_metric.output.contains("--metric"),
            "{}",
            missing_metric.output
        );
    }

    #[test]
    fn bless_collects_prefixes_discriminants_and_context() {
        let command = parse(&[
            "bless",
            "--engine",
            "callgrind",
            "--context",
            "abc123",
            "all_the_time/read_cell",
            "overhead/groups_",
        ]);
        let Command::Bless(options) = command else {
            panic!("expected bless command");
        };
        assert_eq!(
            options.prefixes,
            vec![
                BenchmarkIdPrefix::new("all_the_time/read_cell").unwrap(),
                BenchmarkIdPrefix::new("overhead/groups_").unwrap()
            ]
        );
        assert_eq!(options.engine, vec!["callgrind".to_owned()]);
        assert_eq!(options.context.as_deref(), Some("abc123"));
        assert!(!options.all);
    }

    #[test]
    fn bless_all_switch_needs_no_prefixes() {
        let Command::Bless(options) = parse(&["bless", "--all"]) else {
            panic!("expected bless command");
        };
        assert!(options.all);
        assert!(options.prefixes.is_empty());
    }

    #[test]
    fn bless_all_conflicts_with_prefixes() {
        let error =
            Cli::from_args(&["cargo-bench-history"], &["bless", "--all", "foo/bar"]).unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("cannot be used with"),
            "{}",
            error.output
        );
    }

    #[test]
    fn bless_rejects_an_empty_prefix() {
        let error = Cli::from_args(&["cargo-bench-history"], &["bless", ""]).unwrap_err();
        assert_eq!(error.status, Err(()));
        assert!(
            error.output.contains("benchmark-id prefix"),
            "{}",
            error.output
        );
    }

    #[test]
    fn unbless_parses_discriminants() {
        let command = parse(&[
            "unbless",
            "--context",
            "abc123",
            "--target-triple",
            "x86_64-unknown-linux-gnu",
            "--machine-key",
            "ci-pool",
        ]);
        let Command::Unbless(options) = command else {
            panic!("expected unbless command");
        };
        assert_eq!(options.context.as_deref(), Some("abc123"));
        assert_eq!(
            options.target_triple,
            vec!["x86_64-unknown-linux-gnu".to_owned()]
        );
        assert_eq!(options.machine_key, vec!["ci-pool".to_owned()]);
    }

    #[test]
    fn prune_collects_commits_selection_and_dry_run() {
        let command = parse(&[
            "prune",
            "abc123",
            "def456",
            "--repo",
            "/work/folo",
            "--context",
            "feature",
            "--base",
            "master",
            "--since",
            "2024-01-01T00:00:00Z",
            "--engine",
            "callgrind",
            "--target-triple",
            "x86_64-unknown-linux-gnu",
            "--machine-key",
            "ci-pool",
            "--dirty",
            "--dry-run",
            "--no-text",
            "--json",
            "prune.json",
            "--verbose",
        ]);
        let Command::Prune(options) = command else {
            panic!("expected prune command");
        };
        assert_eq!(options.repo, Some(PathBuf::from("/work/folo")));
        assert_eq!(options.context.as_deref(), Some("feature"));
        assert_eq!(options.base.as_deref(), Some("master"));
        assert_eq!(
            options.commit,
            vec!["abc123".to_owned(), "def456".to_owned()]
        );
        assert_eq!(options.since.as_deref(), Some("2024-01-01T00:00:00Z"));
        assert_eq!(options.engine, vec!["callgrind".to_owned()]);
        assert_eq!(
            options.target_triple,
            vec!["x86_64-unknown-linux-gnu".to_owned()]
        );
        assert_eq!(options.machine_key, vec!["ci-pool".to_owned()]);
        assert!(options.dirty);
        assert!(!options.clean);
        assert!(options.dry_run);
        assert!(options.no_text);
        assert_eq!(options.json, Some(PathBuf::from("prune.json")));
        assert!(options.verbose);
    }

    #[test]
    fn prune_all_expands_to_clean_and_dirty() {
        let command = parse(&[
            "prune",
            "--target-triple",
            "x86_64-unknown-linux-gnu",
            "--all",
        ]);
        let Command::Prune(options) = command else {
            panic!("expected prune command");
        };
        assert_eq!(
            options.target_triple,
            vec!["x86_64-unknown-linux-gnu".to_owned()]
        );
        assert!(options.commit.is_empty());
        assert!(options.clean, "--all enables clean removal");
        assert!(options.dirty, "--all enables dirty removal");
        assert!(!options.dry_run);
    }

    #[test]
    fn prune_include_blessings_combines_with_a_run_scope() {
        // `--include-blessings` is additive: it must be usable alongside a run scope
        // to prune runs and their blessings in one pass.
        let Command::Prune(options) = parse(&["prune", "--all", "--include-blessings"]) else {
            panic!("expected prune command");
        };
        assert!(options.clean, "--all enables clean removal");
        assert!(options.dirty, "--all enables dirty removal");
        assert!(options.include_blessings, "--include-blessings is set");
    }

    #[test]
    fn prune_include_blessings_alone_is_accepted() {
        let Command::Prune(options) = parse(&["prune", "--include-blessings"]) else {
            panic!("expected prune command");
        };
        assert!(!options.clean);
        assert!(!options.dirty);
        assert!(options.include_blessings);
    }

    #[test]
    fn prune_rejects_combining_clean_and_dirty() {
        // `--clean`, `--dirty`, and `--all` remain mutually exclusive alternatives;
        // `--all` is the way to remove both run kinds.
        let error =
            Cli::from_args(&["cargo-bench-history"], &["prune", "--clean", "--dirty"]).unwrap_err();
        assert!(
            error.output.contains("cannot be used with")
                || error.output.contains("conflict")
                || error.output.contains("cannot be used"),
            "combining --clean and --dirty should be rejected: {}",
            error.output
        );
    }

    #[test]
    fn backfill_collects_range_and_passthrough() {
        let command = parse(&[
            "backfill",
            "abc123",
            "def456",
            "--package",
            "nm",
            "--bench",
            "nm_observe",
            "--overwrite",
            "--ignore-errors",
            "--",
            "--noplot",
        ]);
        let Command::Backfill(options) = command else {
            panic!("expected backfill command");
        };
        assert_eq!(options.from, "abc123");
        assert_eq!(options.to, "def456");
        assert_eq!(options.packages, vec!["nm".to_owned()]);
        assert_eq!(options.benches, vec!["nm_observe".to_owned()]);
        assert!(options.overwrite);
        assert!(options.ignore_errors);
        assert_eq!(options.passthrough, vec!["--noplot".to_owned()]);
    }

    #[test]
    fn backfill_requires_from_and_to() {
        let parsed = Cli::from_args(&["cargo-bench-history"], &["backfill", "abc123"]);
        assert!(parsed.is_err(), "a missing `to` must be rejected");
    }

    #[test]
    fn backfill_parses_verbose_switch() {
        let Command::Backfill(options) = parse(&["backfill", "abc123", "def456", "--verbose"])
        else {
            panic!("expected backfill command");
        };
        assert!(options.verbose);

        let Command::Backfill(options) = parse(&["backfill", "abc123", "def456"]) else {
            panic!("expected backfill command");
        };
        assert!(!options.verbose);
    }

    #[test]
    fn backfill_best_of_defaults_to_one_and_parses_a_value() {
        let Command::Backfill(options) = parse(&["backfill", "abc123", "def456"]) else {
            panic!("expected backfill command");
        };
        assert_eq!(
            options.best_of.get(),
            1,
            "--best-of defaults to a single run"
        );

        let Command::Backfill(options) = parse(&["backfill", "abc123", "def456", "--best-of", "3"])
        else {
            panic!("expected backfill command");
        };
        assert_eq!(options.best_of.get(), 3);
    }

    #[test]
    fn backfill_best_of_rejects_zero() {
        let parsed = Cli::from_args(
            &["cargo-bench-history"],
            &["backfill", "abc123", "def456", "--best-of", "0"],
        );
        assert!(parsed.is_err(), "--best-of 0 must be rejected");
    }

    #[test]
    fn unknown_subcommand_is_rejected() {
        Cli::from_args(&["cargo-bench-history"], &["frobnicate"]).unwrap_err();
    }

    #[test]
    fn collect_rejects_unknown_flag() {
        Cli::from_args(&["cargo-bench-history"], &["collect", "--frobnicate"]).unwrap_err();
    }

    #[test]
    fn help_request_lists_subcommands() {
        let early_exit = Cli::from_args(&["cargo-bench-history"], &["--help"]).unwrap_err();
        assert!(
            early_exit.output.contains("collect"),
            "help should list subcommands: {}",
            early_exit.output
        );
        assert!(
            early_exit.output.contains("install"),
            "{}",
            early_exit.output
        );
    }

    #[test]
    fn help_text_describes_each_command_in_alphabetical_order() {
        let help = Cli::help("cargo-bench-history");

        // Each command is accompanied by its description, not just its bare name.
        assert!(
            help.contains("Analyze stored history"),
            "help should describe `analyze`: {help}"
        );
        assert!(
            help.contains("Replay `collect` across a range"),
            "help should describe `backfill`: {help}"
        );

        // The commands appear in alphabetical order. Each marker is a distinct,
        // non-overlapping substring, so the offsets are strictly increasing
        // exactly when they are sorted.
        let order = ["analyze", "backfill", "collect", "install", "list", "prune"];
        let positions: Vec<usize> = order
            .iter()
            .map(|name| help.find(&format!("\n  {name} ")).unwrap())
            .collect();
        assert!(
            positions.is_sorted(),
            "commands should be listed alphabetically: {help}"
        );
    }
}