oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
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
//! Shared readiness path (ADR-0020). Reports drift and names the fix; never
//! applies it (ADR-0003).

use std::cell::OnceCell;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use clap::Args;

use oakum::plan::aggregate::BumpFile;
use oakum::plan::{Package, PackageId, Workspace};
use oakum::state::{ChangedPackage, HandSet, RetiredPackage};
use oakum::tags::{Behind, Drift, Untagged};
use semver::Version;
use serde::Serialize;

use super::changelog::{self, EntryRefusal};
use super::check_report::{CheckReport, ScopeRow};
use super::config::{
    intent_names_unmanaged, load_config, require_config, tag_managed_ids, LoadedConfig,
    PlanIntentSource, ALL_PRIVATE_GUIDANCE,
};
use super::coverage::{self, BranchBumpFiles, Covering};
use super::fs::{link_staging_dir, repo_path_display, stray_staging_files, stray_staging_message};
use super::git::{Git, Op};
use super::install_pin;
use super::intent::{load_coverage_intent, load_plan_bump_files, PlanIntent};
use super::lockfiles;
use super::owned_files;
use super::repository::{self, Repository};
use super::tags::{self, CommitTags};
use super::verdict::{carry, first_line, named, LookReport, Refusal, Verdict};
use super::version::extra_file_repo_path;
use super::workflow::npm_workspace;
use super::workspace::discover_validated;
use super::CliError;

/// `pending` is drift ∪ untagged-pending; `current` matches a reachable tag.
#[derive(Debug)]
pub(super) struct TagEvaluation {
    drift: Vec<Drift>,
    /// Drift whose manifest version has no changelog section: set by hand.
    hand_set_drift: BTreeSet<PackageId>,
    /// Owed no tag, but its next version would repeat a released one.
    behind: Vec<Behind>,
    untagged: Vec<Untagged>,
    current: Vec<(PackageId, Version)>,
    retired: Vec<RetiredPackage>,
}

#[derive(Clone, Debug)]
pub(super) struct PendingRelease {
    id: PackageId,
    version: Version,
}

impl PendingRelease {
    #[must_use]
    pub(super) fn new(id: PackageId, version: Version) -> Self {
        Self { id, version }
    }

    #[must_use]
    pub(super) fn id(&self) -> &PackageId {
        &self.id
    }

    #[must_use]
    pub(super) fn version(&self) -> &Version {
        &self.version
    }
}

impl TagEvaluation {
    #[must_use]
    pub(super) fn is_clean(&self) -> bool {
        self.drift.is_empty() && self.untagged.is_empty()
    }

    #[must_use]
    pub(super) fn pending(&self) -> Vec<PendingRelease> {
        let mut pending: Vec<PendingRelease> = self
            .drift
            .iter()
            .map(|item| PendingRelease::new(item.id().clone(), item.manifest().clone()))
            .chain(
                self.untagged
                    .iter()
                    .map(|item| PendingRelease::new(item.id().clone(), item.version().clone())),
            )
            .collect();
        pending.sort_by(|left, right| left.id.cmp(&right.id));
        pending
    }

    #[must_use]
    pub(super) fn current(&self) -> Vec<PendingRelease> {
        let mut current: Vec<PendingRelease> = self
            .current
            .iter()
            .map(|(id, version)| PendingRelease::new(id.clone(), version.clone()))
            .collect();
        current.sort_by(|left, right| left.id.cmp(&right.id));
        current
    }
}

#[derive(Debug, Args)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each is an independent command-line switch"
)]
pub(super) struct CheckArgs {
    /// Fail on what the coverage and notes looks report: a changed package no intent names, or a bump file whose note would reach no changelog.
    #[arg(long)]
    strict: bool,
    #[arg(long, value_name = "REF", help = super::FROM_PLAN)]
    from: Option<String>,
    /// The release notes body the version job passes `version`, so the
    /// changelogs look renders the entries it will write. `-` reads stdin.
    #[arg(long, value_name = "PATH")]
    notes_file: Option<PathBuf>,
    /// Fail when the newest local tags are missing from the remote.
    #[arg(long)]
    remote: bool,
    /// Print the versioned `CheckReport` JSON document instead of the report.
    /// Refusals still reach stderr, and a run that refuses before the first
    /// look writes no document.
    #[arg(long)]
    json: bool,
    /// Also trace the plan the pending intent makes: each bump, and each
    /// dependency onto a bumped package, whether it cascades and why, with the
    /// declared range when a range decided it.
    #[arg(long, conflicts_with = "json")]
    explain: bool,
    /// How many of the newest local tags `--remote` requires on the remote.
    #[arg(
        long,
        default_value_t = 3,
        value_name = "N",
        value_parser = clap::value_parser!(u32).range(1..=20),
        requires = "remote"
    )]
    remote_lookback: u32,
}

pub(super) fn run(args: &CheckArgs) -> Result<(), CliError> {
    let repo = repository::discover()?;
    let git = Git::at_repository(&repo)?.offline();
    refuse_treeless(&git)?;
    let config = load_config(&repo)?;
    require_config(&config)?;
    let loaded = Loaded::discover(&repo, config)?;
    // Before any look, so the runs that refuse describe themselves too.
    let plan = LookPlan::check(
        Gate::of(args.strict),
        args.remote.then_some(args.remote_lookback),
    );
    let scope = Scope::of(&git, &loaded, args, &plan);
    if !args.json {
        super::say_out(&scope.to_string());
    }
    let context = LookContext {
        git: &git,
        repo: &repo,
        loaded: &loaded,
        // The base the report named, resolved once. The failure travels too,
        // rather than being re-derived: a second resolution that succeeded
        // where the first did not would run a coverage look the report has
        // already said is not happening.
        base: scope.base.as_deref().map_err(String::as_str),
        from: args.from.as_deref(),
        notes_file: args.notes_file.as_deref(),
        pins: OnceCell::new(),
    };
    let (verdict, evaluation) = plan.look(&context);
    for (_, line) in verdict.said() {
        super::say_err(line);
    }
    if !args.json {
        for line in verdict
            .changed(COVERAGE)
            .map(super::reasons::summary_lines)
            .unwrap_or_default()
        {
            super::say_out(&line);
        }
        let settled = plan.settle(verdict.error(), evaluation).map(|_| ());
        if !args.explain {
            return settled;
        }
        return match (
            settled,
            super::release_state::explain(&git, &repo, &loaded.config, args.from.as_deref()),
        ) {
            (settled, Ok(explain)) => {
                super::say_out(&explain_lines(&explain));
                settled
            }
            // Every plan failure measured is one a look also refuses, so the
            // look's refusal already says why.
            (Err(refused), Err(_)) => {
                super::say_out("explain: not traced, check refused above");
                Err(refused)
            }
            (Ok(()), Err(unexplained)) => Err(unexplained),
        };
    }
    // The document is the report, so it is written whether or not the run
    // refuses; the refusal still reaches stderr and still sets the exit code.
    let report = CheckReport::of(
        &verdict,
        scope.row(),
        &plan.names(),
        &LookPlan::check(Gate::Reports, Some(args.remote_lookback)).names(),
    );
    let written = serde_json::to_string_pretty(&report)
        .map_err(|err| CliError::unverified(format!("the check report could not be built: {err}")))
        .and_then(|document| {
            super::deliver_out(&document).map_err(|err| CliError::undelivered("report", &err))
        });
    // The run's own verdict keeps its class. A delivery that failed after a
    // finding was established must not restate the run as unverified — that is
    // ADR-0034's split run backwards, the inversion `carry` was written to stop
    // one layer down.
    match (plan.settle(verdict.error(), evaluation), written) {
        (Err(established), Err(undelivered)) => Err(established.recast(format!(
            "{}\nalso {}: {}",
            established.detail(),
            undelivered.outcome(),
            undelivered.detail()
        ))),
        (settled, Ok(())) => settled.map(|_| ()),
        (Ok(_), Err(undelivered)) => Err(undelivered),
    }
}

/// Every `check` read runs offline, so a partial clone missing trees or
/// commits fails its looks either way; this names why and what brings them
/// in. Refetching alone leaves the filter in config, so the next fetch leaves
/// them out again (measured, git 2.56). A config git cannot read is left to
/// the looks, which report it in the run's own shape.
fn refuse_treeless(git: &Git) -> Result<(), CliError> {
    let Ok(Some(stdout)) = git.optional_text(Op::PartialCloneFilters) else {
        return Ok(());
    };
    match treeless(&stdout) {
        Some(refusal) => Err(CliError::unverified(refusal)),
        None => Ok(()),
    }
}

/// The refusal for the first remote whose filter leaves out history, from
/// `config -z --get-regexp` output (`<key>\n<value>\0` entries).
fn treeless(stdout: &str) -> Option<String> {
    stdout.split('\0').find_map(|entry| {
        let (key, filter) = entry.trim_start_matches('\n').split_once('\n')?;
        (!keeps_history(filter)).then(|| refusal(key, filter))
    })
}

fn refusal(key: &str, filter: &str) -> String {
    let remote = key
        .strip_prefix("remote.")
        .and_then(|rest| rest.strip_suffix(".partialclonefilter"))
        .unwrap_or(key);
    format!(
        "unverified: this clone fetches `{remote}` with `--filter={filter}`, which leaves out more than file contents, and `check` would fetch what its history reads need; bring them in and keep them with `git fetch --refetch --filter=blob:none {}` and `git config {} blob:none`; in CI, check out with no filter",
        tags::shell_quote(remote),
        tags::shell_quote(key),
    )
}

/// Whether a filter leaves out file contents alone, so every commit and tree
/// is present: `blob:none`, `blob:limit=<n>`, `sparse:oid=<blob>`, or a
/// `combine:` of those, whose parts git percent-encodes and may nest. Any
/// other filter, `tree:<depth>` and `object:type=` among them, does not.
fn keeps_history(filter: &str) -> bool {
    let Some(parts) = filter.strip_prefix("combine:") else {
        return filter == "blob:none"
            || filter.starts_with("blob:limit=")
            || filter.starts_with("sparse:oid=");
    };
    parts
        .split('+')
        .all(|part| percent_decoded(part).is_some_and(|part| keeps_history(&part)))
}

/// `None` for an escape that is not two hex digits or decodes to invalid UTF-8.
fn percent_decoded(text: &str) -> Option<String> {
    let mut bytes = Vec::with_capacity(text.len());
    let mut rest = text.as_bytes();
    while let Some((&byte, tail)) = rest.split_first() {
        if byte == b'%' {
            let hex = std::str::from_utf8(tail.get(..2)?).ok()?;
            bytes.push(u8::from_str_radix(hex, 16).ok()?);
            rest = &tail[2..];
        } else {
            bytes.push(byte);
            rest = tail;
        }
    }
    String::from_utf8(bytes).ok()
}

/// An empty trace still prints a line: the reader asked, and silence would
/// read as the flag doing nothing.
fn explain_lines(explain: &oakum::plan::Explain) -> String {
    if explain.is_empty() {
        return String::from("explain: no package is planned to bump");
    }
    let mut lines = String::from("explain:");
    for entry in explain.entries() {
        lines.push_str("\n  ");
        lines.push_str(&entry.to_string());
    }
    lines
}

/// One look: its name, as the scope report announces it, and what it does.
/// The report is derived from this table, so it cannot name a look that does
/// not run; the fold walks it in this order, so the announced order is the
/// execution order and the tie-break order — measured before the table: a
/// `submodules` look announced but never run, and a stale install pin
/// deciding the exit code over a git that could not run at all.
#[derive(Clone, Copy)]
struct Look {
    name: &'static str,
    run: Run,
}

/// What a look reads beyond [`LookContext`], fixed when the plan is built, so a
/// plan cannot carry a look without the value that look reads.
#[derive(Clone, Copy)]
enum Run {
    Plain(fn(&LookContext<'_>) -> LookReport),
    /// Takes whether `--strict` makes its finding refuse the run.
    Gated(fn(&LookContext<'_>, bool) -> LookReport, Gate),
    Remote {
        lookback: u32,
    },
}

/// Whether a gated look's finding refuses the run or only reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Gate {
    Reports,
    Blocks,
}

impl Gate {
    fn of(strict: bool) -> Self {
        if strict {
            Self::Blocks
        } else {
            Self::Reports
        }
    }
}

impl Look {
    fn perform(&self, context: &LookContext<'_>) -> LookReport {
        match self.run {
            Run::Plain(run) => run(context),
            Run::Gated(run, gate) => run(context, gate == Gate::Blocks),
            Run::Remote { lookback } => {
                LookReport::from_result(evaluate_remote(context.git, lookback))
            }
        }
    }

    fn blocks(&self) -> bool {
        matches!(self.run, Run::Gated(_, Gate::Blocks))
    }
}

/// What every look reads, read once per run.
struct LookContext<'a> {
    git: &'a Git,
    repo: &'a Repository,
    loaded: &'a Loaded,
    /// `Err` carries why the base could not be named.
    base: Result<&'a str, &'a str>,
    /// The `--from` the user typed, apart from `base`: commits-only intent
    /// reads each package's own range unless one was given.
    from: Option<&'a str>,
    notes_file: Option<&'a Path>,
    /// Read by the first look that asks, so the install-pin and schema looks
    /// judge one reading of the pins.
    pins: OnceCell<Result<Option<install_pin::Pins>, CliError>>,
}

impl LookContext<'_> {
    fn pins(&self) -> &Result<Option<install_pin::Pins>, CliError> {
        self.pins.get_or_init(|| install_pin::read_pin(self.repo))
    }
}

/// The tag look, passed apart from the others because exactly one runs and
/// the caller that needs its value must not have to ask whether it was
/// filled — `check` and `tag-drift` discard it; `release` reads it. As one
/// of [`Look`] it was a channel
/// any look could fill and none had to: the fill was asserted rather than
/// typed, and a look table without a tag look compiled and panicked on every
/// clean run (measured: 117 of 132 release tests failed on that mutant).
#[derive(Clone, Copy)]
struct TagLook {
    name: &'static str,
    run: fn(&LookContext<'_>) -> Result<(TagEvaluation, LookReport), CliError>,
}

/// The looks before the tag look. [`LookPlan::check`] composes the order and
/// carries the reasoning for it.
const BEFORE_TAGS: [Look; 1] = [MANAGEMENT];

/// The looks one run performs, in order. The scope report names these and
/// [`Self::decide`] runs these, so the announcement cannot name a look that
/// does not run — the property the single table used to carry, and the one a
/// separately-composed name list silently lost (measured: dropping the tag
/// look from that list passed all 588 unit tests).
struct LookPlan {
    before: &'static [Look],
    tag: TagLook,
    after: Vec<Look>,
}

impl LookPlan {
    /// `check`'s own order. Management is the most fundamental thing wrong
    /// with a repository, but it is one look among several: refusing on it
    /// alone would hide a stale install pin or an unfinished write. Tags run
    /// before the install pin so that a git which cannot run at all is the
    /// first line a reader meets, not a pin string that differs.
    fn check(gate: Gate, remote_lookback: Option<u32>) -> Self {
        Self {
            before: &BEFORE_TAGS,
            tag: TAGS,
            after: [
                INSTALL_PIN,
                SCHEMA,
                CHANGELOGS,
                STAGING,
                LOCKFILES,
                notes_look(gate),
                coverage_look(gate),
            ]
            .into_iter()
            .chain(remote_lookback.map(remote_look))
            .collect(),
        }
    }

    /// `tag-drift` is `check`'s tag look and the pin, in `check`'s order.
    fn tag_drift() -> Self {
        Self {
            before: &[],
            tag: TAGS,
            after: Vec::from([INSTALL_PIN]),
        }
    }

    /// The tag state `release` gates on: the evaluation, the pin and coverage.
    /// Coverage reports rather than gates: a decision, not a placeholder.
    fn release() -> Self {
        Self {
            before: &[],
            tag: RELEASE_TAGS,
            after: Vec::from([INSTALL_PIN, coverage_look(Gate::Reports)]),
        }
    }

    fn names(&self) -> Vec<&'static str> {
        self.before
            .iter()
            .map(|look| look.name)
            .chain(std::iter::once(self.tag.name))
            .chain(self.after.iter().map(|look| look.name))
            .collect()
    }

    /// Whether this plan runs the look `--remote` asks for. Read off the
    /// plan rather than the flag, so the sentence describes what runs.
    fn runs_remote(&self) -> bool {
        self.names().contains(&REMOTE)
    }

    /// The looks the report lists. The remote look is left out because the
    /// sentence gives it its own clause either way — naming it here too said
    /// it twice. Still derived from the plan, so it cannot name a look that
    /// does not run, or omit one that does beyond the one it hands on.
    fn listed_names(&self) -> Vec<&'static str> {
        self.names()
            .into_iter()
            .filter(|name| *name != REMOTE)
            .collect()
    }
}

const MANAGEMENT: Look = Look {
    name: "management",
    run: Run::Plain(|context| evaluate_management(context.loaded)),
};

const TAGS: TagLook = TagLook {
    name: "tags",
    run: look_tags_and_pending,
};

/// The tag state `release` reads: the same evaluation, without `check`'s
/// pending refusal — pending tags are what `release` is for.
const RELEASE_TAGS: TagLook = TagLook {
    name: "tags",
    run: |context| {
        let (tags, unread) = evaluate_tags(context.git, context.repo, context.loaded)?;
        Ok((tags, LookReport::refusing(unread)))
    },
};

const INSTALL_PIN: Look = Look {
    name: "install pin",
    run: Run::Plain(|context| LookReport::from_result(evaluate_install_pin(context))),
};

/// Reports and never refuses, `--strict` included: a stale schema costs
/// editor hints, and a stale README a reader's guide, not correctness
/// (ADR-0038).
const SCHEMA: Look = Look {
    name: "schema",
    run: Run::Plain(|context| {
        let standing = install_pin::standing(context.pins());
        LookReport {
            lines: owned_files::schema_note(
                context.repo,
                context.loaded.config.names_committed_schema(),
                &standing,
            )
            .into_iter()
            .chain(owned_files::readme_note(context.repo, &standing))
            .collect(),
            ..LookReport::default()
        }
    }),
};

const CHANGELOGS: Look = Look {
    name: "changelogs",
    run: Run::Plain(evaluate_changelogs),
};

const STAGING: Look = Look {
    name: "staging",
    run: Run::Plain(|context| evaluate_staging(context.repo, context.loaded)),
};

/// Only `check` asks: `version` rewrites the entries a bump invalidates and
/// names the ones it leaves.
const LOCKFILES: Look = Look {
    name: "lockfiles",
    run: Run::Plain(|context| {
        lockfiles::evaluate_pnpm_lock(context.repo, &context.loaded.workspace)
    }),
};

const DROPPED_NOTES: &str = "notes";
const COVERAGE: &str = "coverage";
/// Asked for by `--remote`, and announced by the scope report's own clause.
const REMOTE: &str = "remote";

fn notes_look(gate: Gate) -> Look {
    Look {
        name: DROPPED_NOTES,
        run: Run::Gated(evaluate_dropped_notes, gate),
    }
}

fn coverage_look(gate: Gate) -> Look {
    Look {
        name: COVERAGE,
        run: Run::Gated(
            |context, strict| {
                evaluate_coverage(
                    context.git,
                    context.repo,
                    context.loaded,
                    context.base,
                    strict,
                )
            },
            gate,
        ),
    }
}

fn remote_look(lookback: u32) -> Look {
    Look {
        name: REMOTE,
        run: Run::Remote { lookback },
    }
}

/// Pending tags are a finding like the others and compete with them on that
/// footing; the detail travels with the refusal, one block.
fn look_tags_and_pending(
    context: &LookContext<'_>,
) -> Result<(TagEvaluation, LookReport), CliError> {
    let (tags, unread) = evaluate_tags(context.git, context.repo, context.loaded)?;
    let refusals = refuse_if_pending(&tags)
        .err()
        .map(|error| Refusal {
            error,
            lines: pending_lines(
                &tags,
                super::release::tag_namer(
                    context.repo,
                    &context.loaded.config,
                    &context.loaded.workspace,
                ),
                |id| shares_changelog(&context.loaded.workspace, &context.loaded.config, id),
            ),
        })
        .into_iter()
        .chain(refuse_if_behind(&tags))
        .chain(unread)
        .collect();
    let report = LookReport {
        retired: Some(tags.retired.clone()),
        ..LookReport::refusing(refusals)
    };
    Ok((tags, report))
}

/// Every look runs and every report is kept, so one unverified state does not
/// hide another — measured before the fold: a stale install pin returned early
/// and erased the coverage refusal, and a refused sibling dropped a tag
/// evaluation that had answered. Reports are said, the verdict is returned.
impl LookPlan {
    /// Run every look and fold the reports. Separate from [`Self::decide`] so
    /// `check --json` can render the same `Verdict` the prose is rendered from,
    /// rather than a second traversal that could disagree with it (ADR-0036).
    fn look(&self, context: &LookContext<'_>) -> (Verdict, Option<TagEvaluation>) {
        let mut reports = Vec::new();
        for look in self.before {
            reports.push((look.name, look.perform(context)));
        }
        let evaluation = match (self.tag.run)(context) {
            Ok((tags, report)) => {
                reports.push((self.tag.name, report));
                Some(tags)
            }
            Err(refusal) => {
                reports.push((self.tag.name, LookReport::from_result(Err(refusal))));
                None
            }
        };
        for look in &self.after {
            reports.push((look.name, look.perform(context)));
        }
        (carry(reports), evaluation)
    }

    fn decide(&self, context: &LookContext<'_>) -> Result<TagEvaluation, CliError> {
        let (verdict, evaluation) = self.look(context);
        for (_, line) in verdict.said() {
            super::say_err(line);
        }
        self.settle(verdict.error(), evaluation)
    }

    /// The one place a verdict and a tag evaluation become a result, so the
    /// prose and the document cannot reach different conclusions from the same
    /// run — including the pair where nothing refused and no evaluation
    /// arrived, which is a look that did not happen wearing a clean exit.
    fn settle(
        &self,
        error: Option<CliError>,
        evaluation: Option<TagEvaluation>,
    ) -> Result<TagEvaluation, CliError> {
        match (error, evaluation) {
            (Some(refusal), _) => Err(refusal),
            (None, Some(tags)) => Ok(tags),
            // The tag look answers or refuses, and a refusal is a verdict, so
            // this pair cannot arise. Stated as a refusal rather than a panic:
            // the name is the one the table announced.
            (None, None) => Err(CliError::unverified(format!(
                "unverified: the `{}` look neither answered nor refused",
                self.tag.name
            ))),
        }
    }
}

/// What this run of `check` covers, said out loud before the looks begin. A
/// silent exit 0 collapses every look at once, which is what `AGENTS.md`
/// forbids — but so would claiming completion here, since this prints first so
/// that a run which refuses describes itself too. So it states the scope and
/// the intent, never the verdict: the looks asked for and the looks not asked
/// for are listed apart, and what became of them is the exit code's to say.
struct Scope {
    selected: usize,
    packages: usize,
    /// `Err` carries why the base could not be named. The coverage look raises
    /// the real failure; this only has to avoid claiming a ref it does not have.
    base: Result<String, String>,
    /// The looks `--strict` decides, empty without it. Intent, not outcome: a
    /// look that could not run is still named here, and its own row carries
    /// `unverified`. The reverse loses information — an empty list would not
    /// say whether `--strict` was asked for at all.
    gating: GatedLooks,
    remote: bool,
    /// Taken from the plan that runs, never composed a second time.
    look_names: Vec<&'static str>,
}

/// The looks `--strict` decides, as `check --json` names them. Private and
/// built only by [`Self::of`], so every name is a look from this table that
/// the plan carries, once, in table order.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub(super) struct GatedLooks(Vec<&'static str>);

impl GatedLooks {
    /// Takes the plan rather than names, so a list built without one cannot
    /// reach the wire, and reads each look's own gate, so the list names what
    /// the plan will do. `LookPlan::release` omits the notes look, which is the
    /// shape the filter anticipates.
    fn of(plan: &LookPlan) -> Self {
        Self(
            [COVERAGE, DROPPED_NOTES]
                .into_iter()
                .filter(|name| {
                    plan.after
                        .iter()
                        .any(|look| look.name == *name && look.blocks())
                })
                .collect(),
        )
    }

    /// `check`'s own set, for a test in a sibling module that cannot build a
    /// plan.
    #[cfg(test)]
    pub(super) fn of_check(strict: bool) -> Self {
        Self::of(&LookPlan::check(Gate::of(strict), None))
    }

    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Scope {
    /// The document's half of this report. Beside the fields themselves, so a
    /// transposition is a rename rather than a silent reorder.
    fn row(&self) -> ScopeRow {
        ScopeRow::of(
            self.selected,
            self.packages,
            self.base.as_deref().map_err(String::as_str),
            self.gating.clone(),
        )
    }

    fn of(git: &Git, loaded: &Loaded, args: &CheckArgs, plan: &LookPlan) -> Self {
        let Loaded {
            config, workspace, ..
        } = loaded;
        let packages = workspace.packages().count();
        let selected = workspace
            .packages()
            .filter(|package| config.selected(&package.id().name))
            .count();
        // The selection is a subset of the workspace, which is structural here
        // and only site discipline for any later constructor: `9 of 1` renders
        // without complaint.
        debug_assert!(selected <= packages, "{selected} of {packages}");
        Self {
            selected,
            packages,
            base: resolved_base(git, args.from.as_deref()),
            gating: GatedLooks::of(plan),
            // Both read off the plan, not the flag: the sentence describes
            // what runs, and the two are the same answer only by convention.
            remote: plan.runs_remote(),
            look_names: plan.listed_names(),
        }
    }
}

/// The base this run diffs from, confirmed before the report quotes it. An
/// explicit `--from` is taken verbatim by [`resolve_from_ref`], so the report
/// announced a ref git does not have and the diff then failed on it —
/// measured: `--from no-such-ref` announced that ref and the diff then failed
/// on it with `fatal: ambiguous argument`.
fn resolved_base(git: &Git, from: Option<&str>) -> Result<String, String> {
    let base = super::generate::resolve_from_ref(git, from).map_err(|err| {
        err.downcast_ref::<CliError>()
            .map_or_else(|| err.to_string(), CliError::detail)
    })?;
    // A default base is a merge-base or a ref git has already verified; only
    // one the user typed can be missing.
    if from.is_none() {
        return Ok(base);
    }
    match git.predicate(Op::RefExists { reference: &base }) {
        Ok(true) => Ok(base),
        Ok(false) => Err(format!("git has no `{base}`")),
        Err(err) => Err(err.detail()),
    }
}

impl std::fmt::Display for Scope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            selected, packages, ..
        } = self;
        write!(f, "check: {selected} of {packages} package(s) selected")?;
        match &self.base {
            // Both endpoints, because only one of them is a commit the
            // reader chose: `diffing from <sha>` reads as a comparison against
            // the tree in front of them, and the coverage look reads neither
            // the index nor the worktree.
            Ok(base) => write!(f, ", diffing `{base}...HEAD`")?,
            // One line of why, inside the parentheses; the coverage look
            // raises the whole failure on stderr.
            Err(why) => write!(f, "; no base ref to diff from ({})", first_line(why))?,
        }
        write!(f, "\ncheck: looking at {}", named(&self.look_names))?;
        // Both read the plan from a base, so both are dropped with no base.
        // Saying so beats leaving the reader no line explaining the refusal
        // those looks then raise.
        let needing_base: Vec<&'static str> = [COVERAGE, DROPPED_NOTES]
            .into_iter()
            .filter(|name| self.look_names.contains(name))
            .collect();
        if self.base.is_err() && !needing_base.is_empty() {
            write!(
                f,
                "; {} cannot run without a base ref",
                needing_base.join(" and ")
            )?;
        }
        if self.gating.is_empty() {
            // One clause for every look `--strict` gates, so adding one does
            // not add a near-identical sentence beside the last. A look that
            // cannot run is not a look that reports.
            let ungated: Vec<&'static str> = needing_base
                .iter()
                .copied()
                .filter(|_| self.base.is_ok())
                .collect();
            if !ungated.is_empty() {
                let verb = if ungated.len() == 1 {
                    "reports"
                } else {
                    "report"
                };
                write!(
                    f,
                    "; {} {verb} without gating (`--strict` gates)",
                    ungated.join(" and ")
                )?;
            }
        }
        if self.remote {
            return write!(f, "; looking at the {REMOTE}");
        }
        write!(f, "; not looking at the {REMOTE} (`--remote` asks for it)")
    }
}

/// A staging file means a write did not finish and the file it was replacing
/// may be stale; that is unverified, not clean. The directories are the ones
/// `version` stages into: `.changeset/`, the root, and beside each file
/// [`staging_refusal`] lists as written or the file a link there names.
fn evaluate_staging(repo: &Repository, loaded: &Loaded) -> LookReport {
    match staging_refusal(repo, loaded) {
        Ok(report) => report,
        Err(refusal) => LookReport::from_result(Err(refusal)),
    }
}

/// Files `version` writes in each package directory, besides declared
/// extra-files.
const PACKAGE_WRITES: [&str; 3] = ["Cargo.toml", "package.json", "CHANGELOG.md"];

/// Files `version` writes for the workspace as a whole: the cargo workspace
/// manifest and lock, the pnpm lock, and the catalog.
fn workspace_writes(workspace: &Workspace) -> Vec<PathBuf> {
    let mut written = Vec::new();
    written.extend(workspace.cargo_root_manifest().map(PathBuf::from));
    if let Some(root) = workspace.cargo_workspace_root() {
        written.push(Path::new(root).join("Cargo.lock"));
    }
    if let Some(dir) = workspace.pnpm_lock_dir() {
        written.push(Path::new(dir).join("pnpm-lock.yaml"));
    }
    written.extend(workspace.catalog_file().map(PathBuf::from));
    written
}

fn staging_refusal(repo: &Repository, loaded: &Loaded) -> Result<LookReport, CliError> {
    let mut dirs: BTreeSet<String> = [String::from(".changeset"), String::from(".")].into();
    // A file written through a link stages beside the file it names.
    let mut written = workspace_writes(&loaded.workspace);
    for package in loaded.workspace.packages() {
        let dir = package.manifest_dir();
        if !dir.is_empty() {
            dirs.insert(dir.to_owned());
        }
        for name in PACKAGE_WRITES {
            written.push(PathBuf::from(package.file_path(name)));
        }
        for extra in loaded.config.extra_files_for(&package.id().name) {
            written.push(extra_file_repo_path(package, extra.path())?);
        }
    }
    // A regular file stages beside itself; the root is already in.
    dirs.extend(
        written
            .iter()
            .filter_map(|path| path.parent().map(repo_path_display))
            .filter(|parent| !parent.is_empty()),
    );
    dirs.extend(
        written
            .iter()
            .filter_map(|path| link_staging_dir(repo.dir(), path)),
    );
    let mut strays = Vec::new();
    for sub in &dirs {
        strays.extend(stray_staging_files(repo.dir(), sub)?);
    }
    if strays.is_empty() {
        return Ok(LookReport::default());
    }
    Ok(LookReport::refusing(vec![Refusal {
        error: CliError::unverified(format!(
            "unverified: {} oakum staging file(s) left behind",
            strays.len()
        )),
        lines: strays
            .iter()
            .map(|path| stray_staging_message(path))
            .collect(),
    }]))
}

/// Config, workspace and reachable tags, read once per run: each shells out,
/// and every look here needs the same ones.
pub(super) struct Loaded {
    pub(super) config: LoadedConfig,
    pub(super) workspace: Workspace,
    pub(super) reachable: tags::Reachable,
}

impl Loaded {
    fn load(repo: &Repository) -> Result<Self, CliError> {
        let config = load_config(repo)?;
        Self::discover(repo, config)
    }

    pub(super) fn discover(repo: &Repository, config: LoadedConfig) -> Result<Self, CliError> {
        let workspace = discover_validated(repo, &config)?;
        Ok(Self {
            config,
            workspace,
            reachable: tags::Reachable::default(),
        })
    }
}

/// A changelog `version` would refuse to splice is drift `check` can see
/// before the version job fails in CI. Only `check` asks: `release` never
/// reads the title line; it takes the `## <version>` section and falls back
/// to the release title only when that section is missing or empty.
fn evaluate_changelogs(context: &LookContext<'_>) -> LookReport {
    let (refused, stood_in) = refused_entries(context);
    let mut report = LookReport::refusing(
        foreign_changelogs(context.repo, context.loaded)
            .into_iter()
            .chain(refused)
            .collect(),
    );
    report.lines = stood_in;
    report
}

/// The pending plan's entries, rendered as `version` renders them. One `version`
/// would refuse after the merge whatever it records is an error here. One that
/// renders only with stand-ins for the commit and pull request of bump files
/// the base lacks passes, and its note names what stood in: a PR cannot
/// supply them.
fn refused_entries(context: &LookContext<'_>) -> (Vec<Refusal>, Vec<String>) {
    let entries = match super::version::refused_entries(
        context.repo,
        context.git,
        &context.loaded.config,
        &context.loaded.workspace,
        context.from,
        context.base,
        context.notes_file,
    ) {
        Ok(entries) => entries,
        Err(err) => return (vec![Refusal::bare(CliError::from(err))], Vec::new()),
    };
    let (mut refused, mut unsettled) = (Vec::new(), Vec::new());
    for entry in entries {
        match entry {
            EntryRefusal::Refused(line) => refused.push(line),
            EntryRefusal::Unsettled(line) => unsettled.push(line),
        }
    }
    let mut refusals = Vec::new();
    if !refused.is_empty() {
        refusals.push(Refusal {
            error: CliError::new(format!(
                "{} pending changelog entry(ies) `oakum version` would refuse to write",
                refused.len()
            )),
            lines: refused,
        });
    }
    let stood_in = if unsettled.is_empty() {
        Vec::new()
    } else {
        std::iter::once(format!(
            "changelogs: {} pending entry(ies) rendered with stand-ins for the commit and pull request of bump files the base does not hold yet; `version` renders them with the real ones if the merge's subject carries the pull request:",
            unsettled.len()
        ))
        .chain(unsettled.into_iter().map(|line| format!("  {line}")))
        .collect()
    };
    (refusals, stood_in)
}

fn foreign_changelogs(repo: &Repository, loaded: &Loaded) -> Option<Refusal> {
    let reports = match changelog::foreign_changelogs(repo.dir(), &loaded.workspace, |package| {
        loaded.config.version_managed(package)
    }) {
        Ok(reports) => reports,
        Err(err) => {
            return Some(Refusal::bare(CliError::unverified(format!(
                "unverified: {err}"
            ))))
        }
    };
    (!reports.is_empty()).then(|| Refusal {
        error: CliError::unverified(format!(
            "unverified: {} changelog(s) `oakum version` would refuse to append to",
            reports.len()
        )),
        lines: reports,
    })
}

/// A bump file whose note renders no changelog section loses what its author
/// wrote, silently — `version` consumes the file and the release says nothing.
/// Reported always, gated under `--strict`, which is the shape the coverage
/// look already uses: a repository green today stays green until it opts in.
fn evaluate_dropped_notes(context: &LookContext<'_>, strict: bool) -> LookReport {
    let dropped = match dropped_note_lines(context) {
        Ok(dropped) => dropped,
        Err(err) => return LookReport::from_result(Err(err)),
    };
    if dropped.is_empty() {
        return LookReport::default();
    }
    if !strict {
        return LookReport {
            lines: dropped,
            ..LookReport::default()
        };
    }
    LookReport::refusing(vec![Refusal {
        error: CliError::new(format!(
            "{} bump file note(s) have a heading that would reach no changelog",
            dropped.len()
        )),
        lines: dropped,
    }])
}

/// The highest level decides: the note renders once per contribution, so it
/// reaches a changelog if any levelled entry would render it. Reading the
/// lowest would let a `none` entry beside a real one hide the drop.
fn dropped_headings_of(file: &BumpFile) -> Vec<&'static str> {
    file.entries
        .iter()
        .map(|(_, level)| *level)
        .max()
        .map_or_else(Vec::new, |level| {
            changelog::dropped_headings(&file.note, level)
        })
}

/// Both halves mirror the coverage look, which reads the same source: a base
/// git cannot name is a look that did not happen, and every other failure keeps
/// the class it arrived with, so a malformed bump file stays a finding rather
/// than becoming a look nobody took.
fn dropped_note_lines(context: &LookContext<'_>) -> Result<Vec<String>, CliError> {
    // Unused but required: this look answers alongside coverage, and a run
    // with no base must refuse both alike.
    context
        .base
        .map_err(|why| CliError::unverified(format!("unverified: {why}")))?;
    let files = load_plan_bump_files(
        context.git,
        context.repo,
        &context.loaded.workspace,
        &context.loaded.config,
        context.from,
    )?;
    Ok(files
        .iter()
        .filter_map(|file| {
            let dropped = dropped_headings_of(file);
            (!dropped.is_empty()).then(|| {
                format!(
                    "`{}` has a heading with nothing under it ({})",
                    file.id,
                    changelog::heading_list(&dropped)
                )
            })
        })
        .collect())
}

pub(super) fn run_tags_only() -> Result<(), CliError> {
    let repo = repository::discover()?;
    let git = Git::at_repository(&repo)?;
    let loaded = Loaded::load(&repo)?;
    let context = LookContext {
        git: &git,
        repo: &repo,
        loaded: &loaded,
        base: Err("tag-drift does not diff"),
        from: None,
        notes_file: None,
        pins: OnceCell::new(),
    };
    LookPlan::tag_drift().decide(&context).map(|_| ())
}

/// The tag state, for `release`: Ok even when tags are pending, which `check`
/// refuses. The gate's other looks are `check`'s alone.
pub(super) fn evaluate(
    git: &Git,
    repo: &Repository,
    loaded: &Loaded,
    pins: Result<Option<install_pin::Pins>, CliError>,
    from: Option<&str>,
) -> Result<TagEvaluation, CliError> {
    let base = resolved_base(git, from);
    let context = LookContext {
        git,
        repo,
        loaded,
        base: base.as_deref().map_err(String::as_str),
        from,
        notes_file: None,
        pins: OnceCell::from(pins),
    };
    LookPlan::release().decide(&context)
}

/// `include`/`exclude` left nothing selected, so no plan can name a package.
///
/// Kept apart from [`manages_nothing`], which returns `false` here: the two are
/// different facts about a config that can never release, and `check` is silent
/// on this one because emptying a selection is a decision someone wrote down.
pub(super) fn selection_is_empty(config: &LoadedConfig, workspace: &Workspace) -> bool {
    !workspace
        .packages()
        .any(|package| config.selected(&package.id().name))
}

/// The state [`evaluate_management`] refuses on, as a question. `status`
/// reports it rather than refusing, and both must decide it the same way.
pub(super) fn manages_nothing(config: &LoadedConfig, workspace: &Workspace) -> bool {
    let mut selected = workspace
        .packages()
        .filter(|package| config.selected(&package.id().name))
        .peekable();
    if selected.peek().is_none() {
        return false;
    }
    !selected.any(|package| config.version_managed(package) || config.tag_managed(package))
}

/// A config under which no selected package can produce work on either axis.
/// Every plan is then empty and every release a no-op that reports success.
/// Measured in a repository whose members are all `private` and whose migrated
/// config left `private-packages` at its default.
///
/// An empty selection stays silent. It produces the same empty plan, but
/// `include` and `exclude` are the only keys that empty one, so it is a
/// decision someone wrote down, and the invariant against collapsing "we
/// didn't look" into "it's fine" does not reach a user who said not to look. A package left in the selection
/// and unmanaged by default had no decision written about it, and that is the
/// state worth reporting. Both axes count, because [ADR-0027] makes them
/// independent and a repository that only tags its private packages is doing
/// real work.
///
/// `check` asks; `release` does not, because a release with nothing to do says
/// so in its own words.
///
/// [ADR-0027]: ../../../docs/decisions/0027-private-packages-version-opt-in.md
fn evaluate_management(loaded: &Loaded) -> LookReport {
    let Loaded {
        config, workspace, ..
    } = loaded;
    if !manages_nothing(config, workspace) {
        return LookReport::default();
    }
    // The guidance is the detail; the refusal stays short, like every sibling.
    LookReport::refusing(vec![Refusal {
        error: CliError::unverified(String::from(
            "unverified: this config manages no package on either axis",
        )),
        lines: vec![String::from(ALL_PRIVATE_GUIDANCE)],
    }])
}

fn refuse_if_pending(tags: &TagEvaluation) -> Result<(), CliError> {
    if tags.is_clean() {
        return Ok(());
    }
    Err(CliError::tag_drift(tags.drift.len() + tags.untagged.len()))
}

/// Apart from the pending tags: nothing here is owed a tag, so it is not
/// counted as bumped without one.
fn refuse_if_behind(tags: &TagEvaluation) -> Option<Refusal> {
    (!tags.behind.is_empty()).then(|| Refusal {
        error: CliError::new(format!(
            "{} package(s) below their highest tag",
            tags.behind.len()
        )),
        lines: tags
            .behind
            .iter()
            .map(|item| behind_tag_line(item.id(), item.manifest(), item.tagged()))
            .collect(),
    })
}

fn pending_lines(
    tags: &TagEvaluation,
    tag_name: impl Fn(&PackageId, &Version) -> Option<String>,
    shared: impl Fn(&PackageId) -> bool,
) -> Vec<String> {
    let drift = tags.drift.iter().map(|item| {
        let (id, version) = (item.id(), item.manifest());
        if tags.hand_set_drift.contains(id) {
            return hand_set_above_tag_line(id, version, item.tagged(), tag_name(id, version));
        }
        format!(
            "{id}: manifest {version} is above tagged {} (local tags; run `git fetch --tags` if the remote is ahead)",
            item.tagged()
        )
    });
    let untagged = tags.untagged.iter().map(|item| {
        let (id, version) = (item.id(), item.version());
        if item.has_section() {
            format!("{id}: never released; {version} has a changelog section and no tag yet, which `oakum release` cuts")
        } else {
            hand_set_line(id, version, tag_name(id, version), shared(id))
        }
    });
    drift.chain(untagged).collect()
}

/// The fix for a manifest below its highest tag, which `version` would bump
/// to a version already released or below one.
fn behind_tag_line(id: &PackageId, version: &Version, tagged: &Version) -> String {
    format!(
        "{id}: manifest {version} is below tagged {tagged}, so its next version would repeat or fall below a released one; set the manifest to {tagged}, or to the version you meant above it"
    )
}

fn shares_changelog(workspace: &Workspace, config: &LoadedConfig, id: &PackageId) -> bool {
    workspace
        .get(id)
        .is_some_and(|package| changelog::shares_changelog(workspace, config, package))
}

/// A tag that exists only on a remote reads as no tag; tagging again would cut
/// a second one on another commit.
fn hand_set_line(id: &PackageId, version: &Version, tag: Option<String>, shared: bool) -> String {
    let how = tag.map_or_else(String::new, |tag| format!(" (`git tag {tag} <commit>`)"));
    let heading = if shared {
        format!(
            "; its changelog is shared, so only a `## {}@{version}` heading is its section",
            id.name
        )
    } else {
        String::new()
    };
    format!(
        "{id}: never released, but the manifest is {version}; tag the version you meant{how}, or run `git fetch --tags` if its tag is on a remote{heading}"
    )
}

/// The fix for a manifest set by hand above its highest tag.
fn hand_set_above_tag_line(
    id: &PackageId,
    version: &Version,
    tagged: &Version,
    tag: Option<String>,
) -> String {
    let how = tag.map_or_else(String::new, |tag| format!(" (`git tag {tag} <commit>`)"));
    format!(
        "{id}: manifest {version} is above tagged {tagged} and has no changelog section, so it was set by hand; tag the version you meant{how}, set the manifest back to {tagged}, or run `git fetch --tags` if its tag is on a remote"
    )
}

/// What [`hand_set_versions`] found: the hand-set versions, each with the line
/// naming its fix, and the changelogs it could not read.
pub(super) struct HandSetLook {
    found: Vec<HandSet>,
    unread: Vec<String>,
    /// Placeholders above their tag, or with tags unread, whose changelog
    /// could not be read to tell whether they were released. `version`'s
    /// changelog write refuses each; `status` never writes, so for it the
    /// look did not happen.
    placeholders_unread: Vec<String>,
}

impl HandSetLook {
    /// `version`'s disposition: a hand-set version is a finding, and a
    /// changelog it could not read leaves the plan unverified.
    pub(super) fn refuse(self) -> Result<(), CliError> {
        if !self.found.is_empty() {
            let lines: Vec<&str> = self.found.iter().map(HandSet::fix).collect();
            let mut message = format!(
                "the plan bumps a version set by hand:\n  {}",
                lines.join("\n  ")
            );
            for detail in &self.unread {
                let _ = write!(message, "\n  also unverified: {detail}");
            }
            return Err(CliError::new(message));
        }
        unverified(&self.unread, &[])
    }

    /// `status`'s: the hand-set versions are reported, not refused, but a
    /// changelog it could not read leaves the plan unverified, naming what
    /// was found anyway.
    pub(super) fn reported(self) -> Result<Vec<HandSet>, CliError> {
        let unread = [self.unread, self.placeholders_unread].concat();
        unverified(&unread, &self.found)?;
        Ok(self.found)
    }
}

fn behind_hand_set(item: &Behind) -> HandSet {
    let fix = behind_tag_line(item.id(), item.manifest(), item.tagged());
    HandSet::new(item.id().clone(), item.manifest().clone(), fix)
}

/// A placeholder whose changelog shows no earlier release, whether or not it
/// has its own section.
fn is_fresh_placeholder(repo: &Repository, package: &Package, owner: changelog::Owner) -> bool {
    oakum::tags::is_placeholder(package.version())
        && matches!(
            changelog::has_earlier_section(repo.dir(), package, owner),
            Ok(false)
        )
}

/// A tag-read failure that also names the changelogs already found unread, so
/// fixing one does not reveal the other on the next run.
fn naming_unread<'a>(err: CliError, unread: impl Iterator<Item = &'a CliError>) -> CliError {
    if err.exit_code() != 2 {
        return err;
    }
    let mut message = format!("unverified: {}", err.detail());
    for unread in unread {
        let _ = write!(message, "\n  also unverified: {}", unread.detail());
    }
    err.recast(message)
}

fn unverified(unread: &[String], found: &[HandSet]) -> Result<(), CliError> {
    if unread.is_empty() {
        return Ok(());
    }
    let mut message = format!("unverified: {}", unread.join("\n  "));
    for entry in found {
        let _ = write!(message, "\n  also set by hand: {}", entry.fix());
    }
    Err(CliError::unverified(message))
}

/// ADR-0014 *Untagged versions*: a version no tag records and no changelog
/// section names was set by hand, and `version` must not bump past it,
/// whether or not an older tag exists. A pending version that has its section
/// was written by `version` and is stacked on.
///
/// A manifest below its highest tag was set by hand too: the plan would bump
/// it to a version already released or below one.
///
/// Only packages the plan bumps count: a hand-set version elsewhere is
/// `check`'s to report, and must not stop a release that leaves it alone. Tags
/// are read whenever the plan bumps a package oakum tags, tagged yet or not,
/// other than a fresh placeholder.
pub(super) fn hand_set_versions<T>(
    git: &Git,
    repo: &Repository,
    config: &LoadedConfig,
    workspace: &Workspace,
    bumped: &BTreeMap<PackageId, T>,
) -> Result<HandSetLook, CliError> {
    let mut look = HandSetLook {
        found: Vec::new(),
        unread: Vec::new(),
        placeholders_unread: Vec::new(),
    };
    let planned: Vec<&Package> = workspace
        .packages()
        .filter(|package| bumped.contains_key(package.id()))
        .filter(|package| config.tag_managed(package))
        .collect();
    if planned.is_empty() {
        return Ok(look);
    }
    let mut candidates = Vec::new();
    let mut placeholders_unread = Vec::new();
    let mut fresh = BTreeSet::new();
    for &package in &planned {
        let owner = changelog::Owner::of(workspace, config, package);
        let mut read = match changelog::has_version_section(repo.dir(), package, owner) {
            Ok(true) => {
                if is_fresh_placeholder(repo, package, owner) {
                    fresh.insert(package.id());
                }
                continue;
            }
            Ok(false) => None,
            Err(err) => Some(err),
        };
        // A placeholder is hand-set only above a tag, so tags are read for one
        // only when its changelog has an earlier section: a fresh package
        // never needs them. One whose changelog could not be read, as opposed
        // to one read and refused, waits for the tags to say whether that
        // mattered.
        if oakum::tags::is_placeholder(package.version()) {
            if let Some(err) = read.take_if(|err| err.exit_code() != 1) {
                placeholders_unread.push((package, err));
                continue;
            }
            match changelog::has_earlier_section(repo.dir(), package, owner) {
                Ok(true) => {}
                Ok(false) => {
                    fresh.insert(package.id());
                    continue;
                }
                Err(err) => {
                    placeholders_unread.push((package, err));
                    continue;
                }
            }
        }
        candidates.push((package, owner, read));
    }
    // A fresh placeholder is below a tag only if its changelog lost every
    // earlier section, so under change files it reads no tags and versions in
    // a shallow clone. Commits-only planning has read them already.
    let commits_only = matches!(config.plan_intent_source()?, PlanIntentSource::CommitsOnly);
    let needs_tags: BTreeSet<&PackageId> = planned
        .iter()
        .map(|package| package.id())
        .filter(|id| commits_only || !fresh.contains(id))
        .collect();
    if needs_tags.is_empty() {
        return Ok(look);
    }
    let tagged = tags::reachable_tags(git)
        .and_then(|reachable| tagged_versions(git, config, workspace, reachable))
        .map(|(tagged, _)| tagged)
        .map_err(|err| naming_unread(err, placeholders_unread.iter().map(|(_, unread)| unread)))?;
    look.placeholders_unread = placeholders_unread
        .into_iter()
        .filter(|(package, _)| {
            tagged
                .get(package.id())
                .is_some_and(|tag| package.version().cmp_precedence(tag).is_gt())
        })
        .map(|(_, err)| err.detail())
        .collect();
    look.found.extend(
        oakum::tags::behind(workspace, &tagged, |package| {
            needs_tags.contains(package.id())
        })
        .iter()
        .map(behind_hand_set),
    );
    let tag_name = super::release::tag_namer(repo, config, workspace);
    for (package, owner, read) in candidates {
        let (id, version) = (package.id(), package.version());
        let above = match tagged.get(id) {
            Some(tag) if version.cmp_precedence(tag).is_gt() => Some(tag),
            Some(_) => continue,
            None if oakum::tags::is_placeholder(version) => continue,
            None => None,
        };
        let fix = match read {
            None => match above {
                Some(tag) => hand_set_above_tag_line(id, version, tag, tag_name(id, version)),
                None => hand_set_line(id, version, tag_name(id, version), owner.shared()),
            },
            Some(err) if err.exit_code() == 1 => err.detail(),
            Some(err) => {
                look.unread.push(err.detail());
                continue;
            }
        };
        look.found
            .push(HandSet::new(id.clone(), version.clone(), fix));
    }
    Ok(look)
}

fn tagged_versions(
    git: &Git,
    config: &LoadedConfig,
    workspace: &Workspace,
    reachable: Vec<CommitTags>,
) -> Result<(BTreeMap<PackageId, Version>, Vec<RetiredPackage>), CliError> {
    let bare_candidates = tag_managed_ids(workspace, config);
    let retirement = super::retired::without_retired(git, workspace, &bare_candidates, reachable)?;
    let owned: Vec<Vec<&str>> = retirement
        .groups
        .iter()
        .map(CommitTags::tags)
        .map(|tags| tags.iter().map(String::as_str).collect())
        .collect();
    let slices: Vec<&[&str]> = owned.iter().map(Vec::as_slice).collect();
    let tagged =
        oakum::tags::current_versions(&slices, workspace, |id| bare_candidates.contains(id))
            .map_err(|err| CliError::unverified(err.to_string()))?;
    Ok((tagged, retirement.packages))
}

/// The packages whose tags stay history, for `status`: `None` when the tags
/// could not be read or a rename stops the walk, which `check` names.
pub(super) fn retired_packages(
    git: &Git,
    config: &LoadedConfig,
    workspace: &Workspace,
) -> Option<Vec<RetiredPackage>> {
    tags::reachable_tags(git)
        .and_then(|reachable| tagged_versions(git, config, workspace, reachable))
        .ok()
        .map(|(_, retired)| retired)
}

/// Pins that disagree, or none at all; `tool-version` has no say (ADR-0038).
/// A repository with no `_config.toml` has not adopted oakum, so it owes no
/// pin; only `tag-drift` reaches this look without one.
fn evaluate_install_pin(context: &LookContext<'_>) -> Result<(), CliError> {
    if context.loaded.config.is_default() {
        return Ok(());
    }
    install_pin::agreement(context.pins(), npm_workspace(context.repo.path()))
}

/// The tag state, and apart from it the placeholders whose changelog would
/// decide whether they owe a tag: refusals neither `check` nor `release` may
/// drop.
fn evaluate_tags(
    git: &Git,
    repo: &Repository,
    loaded: &Loaded,
) -> Result<(TagEvaluation, Vec<Refusal>), CliError> {
    let _ = repo.ambient_path()?;
    let Loaded {
        config,
        workspace,
        reachable,
    } = loaded;
    let _ = config.plan_intent_source()?;
    let (tagged, retired) = tagged_versions(git, config, workspace, reachable.tags(git)?)?;
    let (untagged, unread) = oakum::tags::untagged_pending(
        workspace,
        &tagged,
        |package| config.tag_managed(package),
        |package| {
            let owner = changelog::Owner::of(workspace, config, package);
            changelog::has_version_section(repo.dir(), package, owner)
        },
    );
    let drift = oakum::tags::drift(workspace, &tagged, |package| config.tag_managed(package));
    // A section that could not be read leaves the plain drift line, which
    // still fails the look.
    let hand_set_drift = drift
        .iter()
        .filter_map(|item| workspace.get(item.id()))
        .filter(|package| {
            let owner = changelog::Owner::of(workspace, config, package);
            matches!(
                changelog::has_version_section(repo.dir(), package, owner),
                Ok(false)
            )
        })
        .map(|package| package.id().clone())
        .collect();
    let evaluation = TagEvaluation {
        drift,
        hand_set_drift,
        behind: oakum::tags::behind(workspace, &tagged, |package| config.tag_managed(package)),
        untagged,
        current: oakum::tags::tagged_current(workspace, &tagged, |package| {
            config.tag_managed(package)
        }),
        retired,
    };
    Ok((evaluation, unread.into_iter().map(Refusal::bare).collect()))
}

/// Packages a bump file names that the config cannot version-manage, whether
/// the selection dropped them or the opt-in is unset. `status` reaches this
/// through `compose_managed` while composing a plan; `check` composes none, so
/// it asks the question directly.
fn intent_named_unmanaged(
    config: &LoadedConfig,
    workspace: &Workspace,
    files: &[oakum::plan::BumpFile],
) -> Vec<PackageId> {
    let mut named = BTreeSet::new();
    for file in files {
        for (id, level) in &file.entries {
            // Not `standing`: a gate that asked a narrower question than the
            // pipeline would pass a tree `status` and `version` both reject.
            if config.refuses_intent(workspace, id, *level) {
                named.insert(id.clone());
            }
        }
    }
    named.into_iter().collect()
}

fn evaluate_coverage(
    git: &Git,
    repo: &Repository,
    loaded: &Loaded,
    base: Result<&str, &str>,
    strict: bool,
) -> LookReport {
    // The look's own early exits carry one refusal each; only its tail can
    // establish two at once.
    match coverage_refusals(git, repo, loaded, base, strict) {
        Ok(report) => report,
        Err(refusal) => LookReport::from_result(Err(refusal)),
    }
}

fn coverage_refusals(
    git: &Git,
    repo: &Repository,
    loaded: &Loaded,
    base: Result<&str, &str>,
    strict: bool,
) -> Result<LookReport, CliError> {
    // `unverified`, not an error: a base git does not have is a look that could
    // not happen, and ADR-0034 exists so a CI step can tell that from a
    // repository that failed a check. Routing it through `CliError::new` moved
    // a shallow-checkout `--from` off exit 2 and onto exit 1.
    let base = base.map_err(|why| CliError::unverified(format!("unverified: {why}")))?;
    let from = Some(base);
    let Loaded {
        config, workspace, ..
    } = loaded;
    let PlanIntent {
        files,
        commit_types,
        dropped,
        ..
    } = load_coverage_intent(git, repo, workspace, config, base)?;
    // Read before anything is built from it: a `?` between constructing the
    // report and returning it would discard the whole look.
    let source = config.plan_intent_source()?;
    let branch = match source {
        PlanIntentSource::ChangeFiles => Some(BranchBumpFiles::read(git, base)?),
        PlanIntentSource::CommitsOnly => None,
    };
    // Coverage reads the branch's own intent; the unmanaged-package refusal
    // reads every file, since one pending on the base can never be honoured
    // either.
    let covering = match &branch {
        Some(branch) => Covering::ChangeFiles {
            files: branch.own(&files),
            commits: super::intent::releaseless_commits(git, workspace, config, base)?,
        },
        None => Covering::CommitsOnly {
            commits: files.clone(),
            types: commit_types.unwrap_or_default(),
        },
    };
    // The unmanaged half is `status`'s to report: a package the config cannot
    // plan is information, not a decision, and ADR-0027 records private-package
    // silence as something a changesets migratee keeps without a config change.
    // `check` gates; it reads only the coverage half.
    // `unseen` is what the look could not read, not what it found: this half
    // reads commits while intent is read off disk, so a change that is only
    // staged, only edited or not yet tracked is in neither and would otherwise
    // leave exit 0 standing for a question nobody asked.
    let coverage::Uncovered {
        // Every field, not `..`: a field added to the coverage answer fails
        // here first, until this look decides what it says.
        committed: oakum::state::Coverage {
            unmanaged: _,
            changed,
        },
        outside_head,
    } = coverage::changed_by_standing_and_unseen(
        git,
        workspace,
        &covering,
        from,
        branch.as_ref(),
        |package| config.standing(package),
        |path| super::fs::read_resolved_text(repo.dir(), std::path::Path::new(path)),
    )?;
    // `generate` writes intent for every commit in the range, so it is named
    // only while the branch has no bump file of its own to duplicate, and with this
    // look's base: bare, it resolves its own and can find nothing here.
    let generate = (config.generate_allowed() && covering.files().is_empty())
        .then(|| super::tags::shell_quote(base));
    let hint = |package: &ChangedPackage| super::reasons::cover_hint(package, generate.as_deref());
    // The worktree half is advisory in both directions. It never gates when it
    // answers — `--strict` decides what a finding costs, and a change outside
    // `HEAD` is not a finding — so failing to obtain it does not gate either.
    // Said, never silent: what the run could not read is the one thing this
    // look exists to stop it passing over.
    let (unseen, unreadable_worktree) = match outside_head {
        Ok(unseen) => (unseen.lines(hint), None),
        Err(err) => (
            Vec::new(),
            Some(format!(
                "the working tree could not be read, so this run looked only at commits: {}",
                err.detail()
            )),
        ),
    };
    let named_unmanaged = intent_named_unmanaged(config, workspace, &files);
    let uncovered_lines: Vec<String> = changed
        .iter()
        .filter(|package| !package.is_covered())
        .map(|package| {
            let reason = super::reasons::uncovered_reason(package)
                .map_or_else(String::new, |reason| format!("; {reason}"));
            format!(
                "{}: changed{} with no covering intent{reason}; {}",
                package.id(),
                super::reasons::via_clause(package),
                hint(package)
            )
        })
        .collect();
    let mut unseen_lines = unseen;
    unseen_lines.extend(unreadable_worktree);
    // Unlike changed-but-unmanaged, which is `status`'s alone: a commit asking
    // for a release is intent this run would otherwise drop without a word.
    unseen_lines.extend(dropped.lines());
    // The refusal names the first offender; the detail names the rest.
    let unmanaged = named_unmanaged.first().map(|id| Refusal {
        error: CliError::new(intent_names_unmanaged(&id.name)),
        lines: named_unmanaged
            .iter()
            .skip(1)
            .map(|id| intent_names_unmanaged(&id.name))
            .collect(),
    });
    // Both refusals travel: ranking, `also` marking and duplicate suppression
    // belong to `carry`.
    let gated = strict && !uncovered_lines.is_empty();
    let (mut lines, uncovered_refusal) = if gated {
        let refusal = Refusal {
            error: CliError::uncovered(uncovered_lines.len()),
            lines: uncovered_lines,
        };
        (Vec::new(), Some(refusal))
    } else {
        (uncovered_lines, None)
    };
    // Reported whether or not the look gates: `--strict` decides what a
    // finding costs, never whether a run admits what it did not read.
    lines.extend(unseen_lines);
    Ok(LookReport {
        lines,
        refusals: [unmanaged, uncovered_refusal]
            .into_iter()
            .flatten()
            .collect(),
        changed: Some(changed),
        retired: None,
    })
}

fn evaluate_remote(git: &Git, remote_lookback: u32) -> Result<(), CliError> {
    let Some(remote) = tags::first_remote(git)? else {
        return Err(CliError::unverified(
            "unverified: --remote set but this repository has no remotes",
        ));
    };
    let advertised = tags::remote_tag_names(git, &remote)?;
    let local = tags::reachable_tags(git)?;
    let local_names: BTreeSet<String> = local.iter().flat_map(CommitTags::tags).cloned().collect();
    if local_names.is_empty() {
        if advertised.is_empty() {
            return Ok(());
        }
        return Err(CliError::unverified(format!(
            "unverified: remote {remote:?} advertises tags but none are reachable locally; \
             run `git fetch --tags -- {remote}` (a prior fetch --no-tags leaves no local tagOpt to detect)"
        )));
    }
    let lookback = remote_lookback as usize;
    let missing: Vec<String> = newest_local_tags(&local_names, lookback)
        .into_iter()
        .filter(|name| !advertised.contains(name))
        .collect();
    if missing.is_empty() {
        return Ok(());
    }
    Err(CliError::unverified(format!(
        "unverified: newest local tags missing from remote {remote:?}: {}; \
         push the tags (`git push --tags -- {remote}`) or confirm the remote did not drop them",
        missing.join(", ")
    )))
}

fn newest_local_tags(local: &BTreeSet<String>, n: usize) -> Vec<String> {
    let mut tags: Vec<String> = local.iter().cloned().collect();
    tags.sort_by(|left, right| compare_tag_names(left, right));
    let skip = tags.len().saturating_sub(n);
    tags.into_iter().skip(skip).collect()
}

fn compare_tag_names(left: &str, right: &str) -> std::cmp::Ordering {
    match (tag_version(left), tag_version(right)) {
        (Some(left), Some(right)) => left.cmp(&right),
        (Some(_), None) => std::cmp::Ordering::Greater,
        (None, Some(_)) => std::cmp::Ordering::Less,
        (None, None) => left.cmp(right),
    }
}

fn tag_version(name: &str) -> Option<semver::Version> {
    oakum::tags::version_from_tag(name)
}

#[cfg(test)]
mod tests {
    /// The filters as `git clone` stores them (measured, git 2.56).
    #[test]
    fn only_filters_leaving_out_file_contents_keep_the_history() {
        for kept in [
            "blob:none",
            "blob:limit=1k",
            "sparse:oid=HEAD:a/b/f",
            "combine:blob:none+blob:limit=1k+sparse:oid=HEAD:a/b/f",
            "combine:blob%3Anone+blob%3Alimit=1k",
            "combine:combine:blob:none+blob:limit=1k",
            "combine:blob:none+combine:blob:limit=1k%2bblob:none",
        ] {
            assert!(super::keeps_history(kept), "{kept}");
        }
        for lacking in [
            "tree:0",
            "tree:1",
            "object:type=commit",
            "object:type=tree",
            "combine:tree:0+blob:none",
            "combine:tree%3A0+blob:none",
            "combine:combine:tree:0+blob:none",
            "combine:blob:none+combine:blob:limit=1k%2btree:0",
            "combine:blob:limit=1%zz",
            "combine:blob%3",
            "",
        ] {
            assert!(!super::keeps_history(lacking), "{lacking}");
        }
    }

    /// The commands paste into a shell whatever the remote is named.
    #[test]
    fn the_remedy_names_the_remote_as_a_shell_reads_it() {
        let message = super::treeless(
            "remote.aaa.partialclonefilter\nblob:none\0remote.my.fork.partialclonefilter\ntree:0\0",
        )
        .expect("my.fork leaves out trees");
        assert!(
            message.contains("`my.fork` with `--filter=tree:0`")
                && message.contains("--filter=blob:none my.fork`")
                && message.contains("git config remote.my.fork.partialclonefilter blob:none"),
            "{message}"
        );
        let message = super::refusal("remote.a b.partialclonefilter", "tree:0");
        assert!(
            message.contains("--filter=blob:none 'a b'`")
                && message.contains("git config 'remote.a b.partialclonefilter' blob:none"),
            "{message}"
        );
    }

    /// `settle`'s third arm is documented unreachable, which is why no
    /// integration test can drive it — and why the private method is the only
    /// place it can be pinned. Without it, the claim that both renders reach
    /// one conclusion is unverified.
    #[test]
    fn nothing_refused_and_no_evaluation_is_a_look_that_did_not_happen() {
        let refusal = super::LookPlan::check(super::Gate::Reports, None)
            .settle(None, None)
            .expect_err("a look that neither answered nor refused");
        assert_eq!(refusal.class(), crate::cli::Outcome::Unverified);
        assert!(refusal.detail().contains("tags"), "{}", refusal.detail());
    }

    use super::*;

    #[test]
    fn newest_local_tags_orders_changeset_and_hyphen_shapes() {
        let names = BTreeSet::from([
            "demo@0.9.0".into(),
            "demo@0.10.0".into(),
            "demo-v0.11.0".into(),
            "other/v0.8.0".into(),
        ]);
        assert_eq!(
            newest_local_tags(&names, 3),
            vec![
                "demo@0.9.0".to_string(),
                "demo@0.10.0".to_string(),
                "demo-v0.11.0".to_string(),
            ]
        );
    }

    #[test]
    fn newest_local_tags_keeps_hyphen_prerelease_starting_with_v() {
        let names = BTreeSet::from([
            "demo@0.9.0".into(),
            "demo@0.10.0".into(),
            "demo-v1.0.0-v1".into(),
            "other/v0.8.0".into(),
        ]);
        assert_eq!(
            newest_local_tags(&names, 3),
            vec![
                "demo@0.9.0".to_string(),
                "demo@0.10.0".to_string(),
                "demo-v1.0.0-v1".to_string(),
            ]
        );
    }

    #[test]
    fn release_looks_are_named() {
        assert_eq!(
            super::LookPlan::release().names(),
            ["tags", "install pin", "coverage"]
        );
        // `release` runs the coverage look and reports rather than gates.
        // Without this, flipping that decision passes the whole suite.
        assert!(super::GatedLooks::of(&super::LookPlan::release()).is_empty());
    }

    /// One set decides both renders. A second source of truth — a `strict`
    /// flag beside the field — leaves every other test green, so this pairs a
    /// gating `Scope` with the render and fails when they stop agreeing.
    #[test]
    fn the_ungated_clause_and_the_document_read_one_gating_set() {
        let scope = |gate: super::Gate| {
            let plan = super::LookPlan::check(gate, None);
            super::Scope {
                selected: 1,
                packages: 1,
                base: Ok(String::from("HEAD~1")),
                gating: super::GatedLooks::of(&plan),
                remote: false,
                look_names: plan.listed_names(),
            }
        };

        let gated = scope(super::Gate::Blocks);
        assert!(!gated.to_string().contains("without gating"), "{gated}");
        assert_eq!(
            serde_json::to_value(gated.row()).expect("a row")["gating"],
            serde_json::json!(["coverage", "notes"])
        );

        let ungated = scope(super::Gate::Reports);
        assert!(
            ungated
                .to_string()
                .contains("coverage and notes report without gating"),
            "{ungated}"
        );
        assert_eq!(
            serde_json::to_value(ungated.row()).expect("a row")["gating"],
            serde_json::json!([])
        );
    }

    /// The filter is unreachable from any plan the CLI builds today, so it is
    /// pinned here rather than through a command.
    #[test]
    fn gated_looks_names_only_the_looks_the_plan_carries() {
        use super::{coverage_look, notes_look, Gate, GatedLooks, LookPlan, TAGS};
        let names = |gated: GatedLooks| gated.0;
        assert_eq!(
            names(GatedLooks::of(&LookPlan::check(Gate::Blocks, None))),
            [super::COVERAGE, super::DROPPED_NOTES]
        );
        let release_blocking = LookPlan {
            before: &[],
            tag: TAGS,
            after: Vec::from([coverage_look(Gate::Blocks)]),
        };
        assert_eq!(names(GatedLooks::of(&release_blocking)), [super::COVERAGE]);
        // Out of table order, so the result's order is the table's.
        let reversed = LookPlan {
            before: &[],
            tag: TAGS,
            after: Vec::from([notes_look(Gate::Blocks), coverage_look(Gate::Blocks)]),
        };
        assert_eq!(
            names(GatedLooks::of(&reversed)),
            [super::COVERAGE, super::DROPPED_NOTES]
        );
        assert!(GatedLooks::of(&LookPlan::tag_drift()).is_empty());
        assert!(GatedLooks::of(&LookPlan::check(Gate::Reports, None)).is_empty());
    }

    /// `min` here would let a `none` entry beside a real one read as the
    /// coverage-only shape, and the drop would go unreported.
    #[test]
    fn the_highest_level_in_a_file_decides_whether_its_note_drops() {
        use oakum::plan::aggregate::BumpFile;
        use oakum::plan::bump::BumpLevel;
        use oakum::plan::{Ecosystem, PackageId};

        let file = |entries: Vec<(&str, BumpLevel)>| BumpFile {
            id: String::from("mixed.md"),
            entries: entries
                .into_iter()
                .map(|(name, level)| (PackageId::new(Ecosystem::Cargo, name), level))
                .collect(),
            note: String::from("### Added\n"),
        };
        assert_eq!(
            super::dropped_headings_of(&file(vec![
                ("other", BumpLevel::None),
                ("demo", BumpLevel::Minor),
            ])),
            ["Added"]
        );
        assert_eq!(
            super::dropped_headings_of(&file(vec![
                ("other", BumpLevel::None),
                ("demo", BumpLevel::None),
            ])),
            [""; 0]
        );
        assert_eq!(super::dropped_headings_of(&file(Vec::new())), [""; 0]);
    }

    /// The sentence names every look and invents none. A literal drifted in
    /// both directions with the suite green: `submodules` announced as a look
    /// that does not exist, and `staging` dropped while it still ran.
    #[test]
    fn the_announcement_names_every_look() {
        // The remote look runs, is reported as running, and is named by its
        // own clause rather than twice.
        let asked = super::LookPlan::check(super::Gate::Reports, Some(3));
        assert_eq!(asked.names().last(), Some(&super::REMOTE));
        assert!(asked.runs_remote());
        assert!(!asked.listed_names().contains(&super::REMOTE));
        assert!(!super::LookPlan::check(super::Gate::Reports, None).runs_remote());
        let names = super::LookPlan::check(super::Gate::Reports, None).names();
        // The announcement is the plan's own list, so this pins the sentence
        // against the looks rather than against itself.
        assert_eq!(
            names,
            [
                "management",
                "tags",
                "install pin",
                "schema",
                "changelogs",
                "staging",
                "lockfiles",
                "notes",
                "coverage"
            ]
        );
        let sentence = super::named(&names);
        for look in &names {
            assert!(
                sentence.contains(look),
                "{look} is not announced: {sentence}"
            );
        }
        // A list, not a run-on: the last item takes the `and`.
        assert!(sentence.ends_with("and coverage"), "{sentence}");
        assert_eq!(sentence.matches(", and ").count(), 1, "{sentence}");
        assert_eq!(
            sentence.split(", ").count(),
            names.len(),
            "one item per look: {sentence}"
        );
    }
}