oakum 0.6.2

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
//! 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 clap::Args;

use oakum::plan::aggregate::BumpFile;
use oakum::plan::{PackageId, Workspace};
use oakum::tags::{Drift, Untagged};
use semver::Version;

use super::changelog;
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;
use super::fs::{repo_path_display, stray_staging_files, stray_staging_message};
use super::git::{Git, Op};
use super::install_pin;
use super::intent::load_plan_bump_files;
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::{add, CliError};

/// `pending` is drift ∪ untagged-pending; `current` matches a reachable tag.
#[derive(Debug)]
pub(super) struct TagEvaluation {
    drift: Vec<Drift>,
    untagged: Vec<Untagged>,
    current: Vec<(PackageId, Version)>,
}

#[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)]
pub(super) struct CheckArgs {
    /// Fail when a changed package is not named by the enabled intent mechanism.
    #[arg(long)]
    strict: bool,
    /// Git ref to diff from (exclusive). Same default as `generate` / `status`.
    #[arg(long, value_name = "REF")]
    from: Option<String>,
    /// Fail when newest local tags are missing from the remote (ADR-0016).
    #[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 (ADR-0036).
    #[arg(long)]
    json: 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().map_err(CliError::from_boxed)?;
    let config = load_config(&repo).map_err(CliError::from_boxed)?;
    require_config(&config)?;
    let loaded = Loaded::discover(&repo, config)?;
    let git = Git::at_repository(&repo).map_err(CliError::from_boxed)?;
    // Before any look, so the runs that refuse describe themselves too.
    let plan = LookPlan::check(args.remote);
    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),
        strict: Some(args.strict),
        remote_lookback: Some(args.remote_lookback),
        pins: OnceCell::new(),
    };
    if !args.json {
        return plan.decide(&context).map(|_| ());
    }
    // 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 (verdict, evaluation) = plan.look(&context);
    for (_, line) in verdict.said() {
        super::say_err(line);
    }
    let report = CheckReport::of(
        &verdict,
        scope.row(),
        &plan.names(),
        &LookPlan::check(true).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),
    }
}

/// 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: fn(&LookContext<'_>) -> LookReport,
}

/// 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>,
    /// Read by the looks `--strict` gates — coverage and notes. `None` when
    /// the caller runs neither, so a caller cannot invent a gate nobody asked
    /// for.
    strict: Option<bool>,
    /// Read by the remote look alone, and asked for only by `--remote`.
    remote_lookback: Option<u32>,
    /// 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 either side of the tag look. [`LookPlan::check`] composes the
/// order and carries the reasoning for it.
const BEFORE_TAGS: [Look; 1] = [MANAGEMENT];
const AFTER_TAGS: [Look; 6] = [
    INSTALL_PIN,
    SCHEMA,
    CHANGELOGS,
    STAGING,
    DROPPED_NOTES,
    COVERAGE,
];

/// 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(remote: bool) -> Self {
        Self {
            before: &BEFORE_TAGS,
            tag: TAGS,
            after: AFTER_TAGS
                .into_iter()
                .chain(remote.then_some(REMOTE))
                .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.
    fn release() -> Self {
        Self {
            before: &[],
            tag: RELEASE_TAGS,
            after: Vec::from([INSTALL_PIN, COVERAGE]),
        }
    }

    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.name)
    }

    /// 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.name)
            .collect()
    }
}

const MANAGEMENT: Look = Look {
    name: "management",
    run: |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: |context| LookReport::from_result(evaluate_install_pin(context)),
};

/// Reports and never refuses, `--strict` included: a stale schema costs
/// editor hints, not correctness (ADR-0038).
const SCHEMA: Look = Look {
    name: "schema",
    run: |context| LookReport {
        lines: owned_files::schema_note(
            context.repo,
            context.loaded.config.names_committed_schema(),
            &install_pin::standing(context.pins()),
        )
        .into_iter()
        .collect(),
        refusals: Vec::new(),
    },
};

const CHANGELOGS: Look = Look {
    name: "changelogs",
    run: |context| evaluate_changelogs(context.repo, context.loaded),
};

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

const DROPPED_NOTES: Look = Look {
    name: "notes",
    run: |context| match context.strict {
        Some(strict) => evaluate_dropped_notes(context, strict),
        // Unreachable for the same reason the coverage look's arm is, and a
        // refusal rather than a panic for the same reason.
        None => LookReport::from_result(Err(CliError::unverified(
            "unverified: the notes look ran without a strictness decision, so it did not look",
        ))),
    },
};

const COVERAGE: Look = Look {
    name: "coverage",
    run: |context| match context.strict {
        Some(strict) => evaluate_coverage(
            context.git,
            context.repo,
            context.loaded,
            context.base,
            strict,
        ),
        // Unreachable while every table carrying this look is built beside a
        // caller that decides: a refusal rather than a panic, because the
        // look not running is a look that did not happen.
        None => LookReport::from_result(Err(CliError::unverified(
            "unverified: the coverage look ran without a strictness decision, so it did not look",
        ))),
    },
};

/// Asked for by `--remote`, and announced by the scope report's own clause.
const REMOTE: Look = Look {
    name: "remote",
    run: |context| {
        LookReport::from_result(match context.remote_lookback {
            Some(lookback) => evaluate_remote(context.git, lookback),
            None => Err(CliError::unverified(
                "unverified: the remote look ran without a lookback, so it did not look",
            )),
        })
    },
};

/// 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,
                ),
            ),
        })
        .into_iter()
        .chain(unread)
        .collect();
    Ok((tags, LookReport::refusing(refusals)))
}

/// 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.run)(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.run)(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: Vec<&'static str>,
    remote: bool,
    /// Taken from the plan that runs, never composed a second time.
    look_names: Vec<&'static str>,
}

/// The looks `--strict` decides, filtered to the ones a plan carries.
/// `LookPlan::release` omits the notes look, which is the shape this
/// anticipates; every plan reaching `Scope` today carries both.
fn gated_looks(look_names: &[&'static str]) -> Vec<&'static str> {
    [COVERAGE.name, DROPPED_NOTES.name]
        .into_iter()
        .filter(|name| look_names.contains(name))
        .collect()
}

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: if args.strict {
                gated_looks(&plan.listed_names())
            } else {
                Vec::new()
            },
            // 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)
    })?;
    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.name, DROPPED_NOTES.name]
            .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.name);
        }
        write!(
            f,
            "; not looking at the {} (`--remote` asks for it)",
            REMOTE.name
        )
    }
}

/// 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 repository root (lockfiles),
/// every package directory (manifest, changelog), and every declared
/// extra-file's directory.
fn evaluate_staging(repo: &Repository, loaded: &Loaded) -> LookReport {
    match staging_refusal(repo, loaded) {
        Ok(report) => report,
        Err(refusal) => LookReport::from_result(Err(refusal)),
    }
}

fn staging_refusal(repo: &Repository, loaded: &Loaded) -> Result<LookReport, CliError> {
    let mut dirs: BTreeSet<String> = [String::from(".changeset"), String::from(".")].into();
    for package in loaded.workspace.packages() {
        let dir = package.manifest_dir();
        if !dir.is_empty() {
            dirs.insert(dir.to_owned());
        }
        for extra in loaded.config.extra_files_for(&package.id().name) {
            let path = extra_file_repo_path(package, extra.path()).map_err(CliError::from_boxed)?;
            let parent = path.parent().map(repo_path_display).unwrap_or_default();
            dirs.insert(if parent.is_empty() {
                String::from(".")
            } else {
                parent
            });
        }
    }
    let mut strays = Vec::new();
    for sub in &dirs {
        strays.extend(stray_staging_files(repo.dir(), sub).map_err(CliError::from_boxed)?);
    }
    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 and workspace, read once per run: discovery shells out, and every
/// look here needs the same two.
struct Loaded {
    config: LoadedConfig,
    workspace: Workspace,
}

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

    fn discover(repo: &Repository, config: LoadedConfig) -> Result<Self, CliError> {
        let workspace = add::discover_workspace(repo).map_err(CliError::from_boxed)?;
        config.validate_workspace_selection(&workspace)?;
        Ok(Self { config, workspace })
    }
}

/// 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(repo: &Repository, loaded: &Loaded) -> LookReport {
    let reports = match changelog::foreign_changelogs(repo.dir(), &loaded.workspace, |package| {
        loaded.config.version_managed(package)
    }) {
        Ok(reports) => reports,
        Err(err) => {
            return LookReport::from_result(Err(CliError::unverified(format!("unverified: {err}"))))
        }
    };
    if reports.is_empty() {
        return LookReport::default();
    }
    LookReport::refusing(vec![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,
            refusals: Vec::new(),
        };
    }
    LookReport::refusing(vec![Refusal {
        error: CliError::new(format!(
            "{} bump file note(s) 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 file_drops_its_note(file: &BumpFile) -> bool {
    file.entries
        .iter()
        .map(|(_, level)| *level)
        .max()
        .is_some_and(|level| changelog::note_renders_nothing(&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> {
    let from = Some(
        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,
        from,
    )
    .map_err(CliError::from_boxed)?;
    Ok(files
        .iter()
        .filter(|file| file_drops_its_note(file))
        .map(|file| format!("`{}` has a heading with nothing under it", file.id))
        .collect())
}

pub(super) fn run_tags_only() -> Result<(), CliError> {
    let repo = repository::discover().map_err(CliError::from_boxed)?;
    let git = Git::at_repository(&repo).map_err(CliError::from_boxed)?;
    let loaded = Loaded::load(&repo)?;
    let context = LookContext {
        git: &git,
        repo: &repo,
        loaded: &loaded,
        base: Err("tag-drift does not diff"),
        // `tag-drift` runs neither look that reads these.
        strict: None,
        remote_lookback: None,
        pins: OnceCell::new(),
    };
    LookPlan::tag_drift().decide(&context).map(|_| ())
}

/// `release` runs the coverage look and reports rather than gates on it: a
/// decision, not a placeholder. At module scope so a test can assert it —
/// flipped inside the function, the whole suite passed.
const NOT_STRICTLY: Option<bool> = Some(false);

/// 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,
    from: Option<&str>,
) -> Result<TagEvaluation, CliError> {
    let loaded = Loaded::load(repo)?;
    let base = resolved_base(git, from);
    let context = LookContext {
        git,
        repo,
        loaded: &loaded,
        base: base.as_deref().map_err(String::as_str),
        strict: NOT_STRICTLY,
        remote_lookback: None,
        pins: OnceCell::new(),
    };
    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()))
}

fn pending_lines(
    tags: &TagEvaluation,
    tag_name: impl Fn(&PackageId, &Version) -> Option<String>,
) -> Vec<String> {
    let drift = tags.drift.iter().map(|item| {
        format!(
            "{}: manifest {} is above tagged {} (local tags; run `git fetch --tags` if the remote is ahead)",
            item.id(),
            item.manifest(),
            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))
        }
    });
    drift.chain(untagged).collect()
}

/// 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>) -> String {
    let how = tag.map_or_else(String::new, |tag| format!(" (`git tag {tag} <commit>`)"));
    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"
    )
}

/// 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. A
/// pending version that has its section was written by `version` and is
/// stacked on, as drift above a tag is.
///
/// 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 only when one of those could be hand-set.
pub(super) fn refuse_hand_set_untagged<T>(
    git: &Git,
    repo: &Repository,
    config: &LoadedConfig,
    workspace: &Workspace,
    bumped: &BTreeMap<PackageId, T>,
) -> Result<(), CliError> {
    let mut candidates = Vec::new();
    for package in workspace
        .packages()
        .filter(|package| bumped.contains_key(package.id()))
        .filter(|package| config.tag_managed(package))
        .filter(|package| !oakum::tags::is_placeholder(package.version()))
    {
        match changelog::has_version_section(repo.dir(), package) {
            Ok(true) => {}
            Ok(false) => candidates.push((package, None)),
            Err(err) => candidates.push((package, Some(err))),
        }
    }
    if candidates.is_empty() {
        return Ok(());
    }
    let tagged = tagged_versions(git, config, workspace)?;
    let tag_name = super::release::tag_namer(repo, config, workspace);
    let mut hand_set = Vec::new();
    let mut unread = Vec::new();
    for (package, read) in candidates {
        if tagged.contains_key(package.id()) {
            continue;
        }
        match read {
            None => hand_set.push(hand_set_line(
                package.id(),
                package.version(),
                tag_name(package.id(), package.version()),
            )),
            Some(err) => unread.push(err.detail()),
        }
    }
    if !hand_set.is_empty() {
        let mut message = format!(
            "the plan would bump past a version no tag records:\n  {}",
            hand_set.join("\n  ")
        );
        for detail in &unread {
            let _ = write!(message, "\n  also unverified: {detail}");
        }
        return Err(CliError::new(message));
    }
    if unread.is_empty() {
        Ok(())
    } else {
        Err(CliError::unverified(format!(
            "unverified: {}",
            unread.join("\n  ")
        )))
    }
}

fn tagged_versions(
    git: &Git,
    config: &LoadedConfig,
    workspace: &Workspace,
) -> Result<BTreeMap<PackageId, Version>, CliError> {
    let groups = tags::reachable_tags(git)?;
    let owned: Vec<Vec<&str>> = 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 bare_candidates = tag_managed_ids(workspace, config);
    oakum::tags::current_versions(&slices, workspace, |id| bare_candidates.contains(id))
        .map_err(|err| CliError::unverified(err.to_string()))
}

/// 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().map_err(CliError::from_boxed)?;
    let Loaded { config, workspace } = loaded;
    let _ = config.plan_intent_source()?;
    let tagged = tagged_versions(git, config, workspace)?;
    let (untagged, unread) = oakum::tags::untagged_pending(
        workspace,
        &tagged,
        |package| config.tag_managed(package),
        |package| changelog::has_version_section(repo.dir(), package),
    );
    let evaluation = TagEvaluation {
        drift: oakum::tags::drift(workspace, &tagged, |package| config.tag_managed(package)),
        untagged,
        current: oakum::tags::tagged_current(workspace, &tagged, |package| {
            config.tag_managed(package)
        }),
    };
    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 `retain_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, _) in &file.entries {
            // Not `standing`: `retain_managed` refuses on any intent-named
            // package it cannot version, an excluded one included, and a gate
            // that asked a narrower question than the pipeline would pass a
            // tree `status` and `version` both reject.
            if workspace
                .get(id)
                .is_some_and(|package| !config.version_managed(package))
            {
                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 files =
        load_plan_bump_files(git, repo, workspace, config, from).map_err(CliError::from_boxed)?;
    // 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()?;
    // 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 {
        // Both fields, not `..`: `Coverage` is the wire shape templates read
        // and must not grow one. One of several places that would say so —
        // every construction site fails first with a missing field.
        committed:
            oakum::state::Coverage {
                uncovered,
                unmanaged: _,
            },
        outside_head,
    } = coverage::changed_by_standing_and_unseen(
        git,
        workspace,
        &files,
        from,
        matches!(source, PlanIntentSource::ChangeFiles),
        |package| config.standing(package),
    )?;
    // `generate` writes intent for every commit in the range, so it is named
    // only while no bump file is pending for it to duplicate, and with this
    // look's base: bare, it resolves its own and can find nothing here.
    let hint = match source {
        PlanIntentSource::ChangeFiles if config.generate_allowed() && files.is_empty() => format!(
            "add a bump file with `oakum add --packages <package>:<level>`, or write it from conventional commits with `oakum generate --from {}` (or `none` / empty frontmatter under --strict)",
            super::tags::shell_quote(base)
        ),
        PlanIntentSource::ChangeFiles => String::from(
            "add a bump file with `oakum add --packages <package>:<level>` (or `none` / empty frontmatter under --strict)",
        ),
        PlanIntentSource::CommitsOnly => String::from(
            "name the package in a conventional commit (or a path that maps to it)",
        ),
    };
    let hint = hint.as_str();
    // 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 mut uncovered_lines = Vec::new();
    for id in &uncovered {
        uncovered_lines.push(format!("{id}: changed with no covering intent; {hint}"));
    }
    let mut unseen_lines = unseen;
    unseen_lines.extend(unreadable_worktree);
    // 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.is_empty();
    let (mut lines, uncovered_refusal) = if gated {
        let refusal = Refusal {
            error: CliError::uncovered(uncovered.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(),
    })
}

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 {
    /// `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(false)
            .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(),
            ]
        );
    }

    /// `release` gates on the tag state, the pin and coverage — named, so a
    /// reordered `LOOKS` cannot shift what it gates on.
    #[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_eq!(super::NOT_STRICTLY, Some(false));
    }

    /// 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 = |gating: Vec<&'static str>| super::Scope {
            selected: 1,
            packages: 1,
            base: Ok(String::from("HEAD~1")),
            gating,
            remote: false,
            look_names: Vec::from([super::COVERAGE.name, super::DROPPED_NOTES.name]),
        };

        let gated = scope(Vec::from([super::COVERAGE.name, super::DROPPED_NOTES.name]));
        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(Vec::new());
        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() {
        assert_eq!(
            super::gated_looks(&super::LookPlan::check(false).listed_names()),
            [super::COVERAGE.name, super::DROPPED_NOTES.name]
        );
        assert_eq!(
            super::gated_looks(&[super::DROPPED_NOTES.name]),
            [super::DROPPED_NOTES.name]
        );
        let gated = super::gated_looks(&[super::STAGING.name]);
        assert!(gated.is_empty(), "{gated:?}");
    }

    /// `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!(super::file_drops_its_note(&file(vec![
            ("other", BumpLevel::None),
            ("demo", BumpLevel::Minor),
        ])));
        assert!(!super::file_drops_its_note(&file(vec![
            ("other", BumpLevel::None),
            ("demo", BumpLevel::None),
        ])));
        assert!(!super::file_drops_its_note(&file(Vec::new())));
    }

    /// 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(true);
        assert_eq!(asked.names().last(), Some(&super::REMOTE.name));
        assert!(asked.runs_remote());
        assert!(!asked.listed_names().contains(&super::REMOTE.name));
        assert!(!super::LookPlan::check(false).runs_remote());
        let names = super::LookPlan::check(false).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",
                "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}"
        );
    }
}