onevcs 0.5.0

Version control and remote-host abstraction for agent workflows: host-neutral change requests, sessions, and a rules system.
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
//! What became of one piece of work.
//!
//! `recoverable` answers what is *unpublished*, and nothing answered what was
//! *proposed*, whether it *landed*, or how its checks went — so an agent asking
//! that question left this boundary for `gh pr list` and `gh pr checks`, and a
//! planner that consulted only the absence of an open change request concluded that
//! a change already squash-merged to `main` had never been published. This is the
//! one place those are answered together.
//!
//! Three things decide the shape of what it reports.
//!
//! **Landing is read off content, never off ancestry or off the host.** Publication
//! squashes, so a branch that landed is an ancestor of nothing afterwards and its
//! commits are in the base under no name they kept. What is true of it is that the
//! base already carries what it changed, which is the same question
//! [`crate::vcs::collect`] excludes a branch on — and the reason that exclusion was
//! illegible from outside is that nobody could ask about *one* branch.
//!
//! **Where a branch is comes from one search.** [`crate::workspace::checkouts_of`]
//! is the list `recover` and `publish-branch` locate a branch through, run clones
//! included, so a branch a verb can land is a branch this can report on.
//!
//! **The host is asked, and a host that cannot be reached is reported rather than
//! raised.** Everything above is answerable offline; the host adds what a change
//! request is doing now. A status that failed because a network call did leaves an
//! operator with none of the answer, which is the thing they came here for.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::{Date, Month, Time};

use crate::error::{Error, Result};
use crate::event::EventKind;
use crate::host::{CheckSource, Hosting};
use crate::registry::{Registry, RepoType, Workflow};
use crate::rules::{Approvals, Gate, MergePolicy};
use crate::session::{Lifecycle, Liveness, Provenance, SessionHolder};
use crate::store::{self, Resolution};
use crate::workspace::{Ref, Token};
use crate::{gh, git, guidance, home, policy, provenance, stream, vcs, workspace};

/// The version of the object `onevcs status --json` writes.
///
/// A report leaves this process and is read by whatever consumes the command, which
/// makes it a stored contract like the registry document and the rules file — and
/// like those it *says* which shape it is, rather than leaving a consumer to infer
/// that from which keys it can find. `1` is the initial version and deliberately not
/// a migration boundary: nothing in this build reads a report back, so the number is
/// what a consumer branches on and there is no older shape here to read.
///
/// Every change to what the object carries bumps this in the same change that
/// updates the checked-in goldens under `crates/onevcs/tests/golden/`, which
/// `tests/e2e/accounting.rs` holds to this command's own output byte for byte.
pub const REPORT_VERSION: u32 = 1;

/// A schema version this build reads, checked where a report is read.
///
/// The check is in the conversion, as it is for every other validated value in this
/// crate: a report declaring a version this build does not know does not deserialize
/// at all, rather than deserializing into something a reader then has to remember to
/// question. That matters more here than for most, because the whole purpose of the
/// number is to be *acted on* — a consumer that read a v2 document as a v1 one would
/// be reading fields that moved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u32", into = "u32")]
pub struct ReportVersion(u32);

impl ReportVersion {
    /// The version this build writes.
    pub fn current() -> Self {
        ReportVersion(REPORT_VERSION)
    }
}

impl TryFrom<u32> for ReportVersion {
    type Error = String;

    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        if value == REPORT_VERSION {
            Ok(ReportVersion(value))
        } else {
            Err(format!(
                "a status report declares version {value}; this build reads version \
                 {REPORT_VERSION}"
            ))
        }
    }
}

impl From<ReportVersion> for u32 {
    fn from(version: ReportVersion) -> Self {
        version.0
    }
}

/// Everything `onevcs` knows about one piece of work.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Report {
    /// The schema version this object is written at, so a consumer reads a shape it
    /// was told rather than one it guessed.
    pub version: ReportVersion,
    /// The reference as it was asked for, and how it was read.
    #[serde(rename = "ref")]
    pub reference: Reference,
    /// The identity the work belongs to, and the policy its rules resolve to.
    pub identity: IdentityReport,
    /// The session that holds or held the branch, when one is recorded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<SessionReport>,
    /// The branch itself: who has it, what it carries, and what it records.
    pub branch: BranchReport,
    /// What was proposed for it, and whether that landed.
    pub publication: PublicationReport,
    /// What the host says its checks are doing, or why it could not be asked.
    pub checks: ChecksReport,
    /// The last gate verdict recorded for this work.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gate: Option<GateReport>,
    /// The command that advances the work, or why none does.
    pub next: NextReport,
    /// Anything this report could not read, so a gap is stated rather than left to
    /// look like an answer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
}

/// The reference, and which of the four spellings it turned out to be.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reference {
    /// What was typed.
    pub given: String,
    /// How it resolved.
    pub kind: RefKind,
}

/// Which spelling a reference was read as.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RefKind {
    /// A change request's URL.
    ChangeUrl,
    /// A session token.
    SessionToken,
    /// A branch name.
    Branch,
    /// A commit.
    Commit,
}

/// The identity, and what its rules resolve to for this repository.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IdentityReport {
    /// The identity key.
    pub key: String,
    /// The checkout publication fast-forwards, never works in.
    pub publication_checkout: PathBuf,
    /// Whether work publishes locally or through the remote host.
    pub workflow: Workflow,
    /// Whether the repository is one person's or a team's.
    pub repo_type: RepoType,
    /// The gate the rules resolve to, as the rules file spells it.
    pub gate: Gate,
    /// Whether the rules require approvals.
    pub approvals: Approvals,
}

/// The session that holds or held the branch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionReport {
    /// The token every session-keyed command takes.
    pub token: Token,
    /// Whether it is open or closed.
    pub state: Lifecycle,
    /// Whether the process that opened it is still there.
    pub liveness: Liveness,
    /// The base the branch was cut from.
    pub base: Ref,
    /// The per-run clone.
    pub clone: PathBuf,
    /// The worktree the change was made in.
    pub worktree: PathBuf,
}

/// The branch: everywhere it is, what it is ahead of, and what it records.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchReport {
    /// The branch name.
    pub name: Ref,
    /// The identity's root base, which is what it is compared against.
    pub base: Ref,
    /// The change base a preserved commit recorded, for a stacked change.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub change_base: Option<Ref>,
    /// Every checkout and per-run clone holding it, in search order.
    pub holders: Vec<Holder>,
    /// How many commits it has that the base does not. Absent where nothing on
    /// this host holds the branch, which is not the same as none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ahead: Option<usize>,
    /// What its provenance says. Absent for the same reason `ahead` is.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<BranchProvenance>,
}

/// One repository holding the branch, and what that repository is.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Holder {
    /// Where it is.
    pub path: PathBuf,
    /// Which kind of repository this identity keeps work in.
    pub kind: HolderKind,
    /// The session whose run clone this is, when it is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<Token>,
}

/// Which of the three places an identity keeps a branch this holder is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HolderKind {
    /// The checkout publication fast-forwards.
    PublicationCheckout,
    /// Another checkout registered for this identity.
    RegisteredCheckout,
    /// A per-run clone, which is where work a run stopped in the middle of lives.
    RunClone,
}

/// What a branch's provenance says about how its work came to be there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BranchProvenance {
    /// Every step finished.
    Complete,
    /// A step did not finish, and no verified recovery has cleared it.
    IncompleteUnattested,
    /// A step did not finish, and a recovery attested that a gate cleared it.
    IncompleteAttested,
}

/// What was proposed for the work, and whether it reached the base.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicationReport {
    /// Where the work is. Whether it *landed* is this and nothing beside it: a
    /// second field saying so could disagree with the state that decided it.
    pub state: Landing,
    /// The change request, when one is recorded or open.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub change_url: Option<String>,
    /// The policy this identity's rules publish under.
    pub merge_policy: MergePolicy,
}

/// Where one piece of work has got to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Landing {
    /// The base carries this branch's content: the change reached it, however it
    /// was merged.
    Landed,
    /// A change request is open and the host has been asked to land it once its
    /// checks pass.
    Queued,
    /// A change request is open, awaiting whatever its policy waits for.
    Open,
    /// A change request was opened and is no longer open, and the base does not
    /// carry the work.
    #[serde(rename = "closed-without-landing")]
    Closed,
    /// A change request was opened, and the host could not be asked what became
    /// of it.
    Published,
    /// The branch has nothing the base does not already carry.
    NothingToPublish,
    /// Nothing has been proposed for this branch.
    Unpublished,
}

impl Landing {
    /// Whether the base already carries this branch's content.
    pub fn landed(self) -> bool {
        self == Landing::Landed
    }
}

/// What the host reports about the change request's checks.
///
/// One or the other, never both halves of each: a section carrying an answer *and*
/// the reason there is none could report "could not look" as "nothing blocks this",
/// which is the one thing that turns an ungated merge into one that looks gated.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum ChecksReport {
    /// The host answered, with these checks and from these sources. Empty is an
    /// answer: a change request with no checks on it, or none open at all.
    Reported {
        /// One entry per check the host reports.
        checks: Vec<CheckReport>,
        /// Which of the host's sources the answer was read from.
        sources: Vec<CheckSource>,
    },
    /// The host could not be asked, and this is why. The whole reason this section
    /// degrades rather than failing the command: an unreachable host is a gap in
    /// the answer, and the rest of the answer is still true.
    Unavailable {
        /// What the host, the credential, or `gh` itself said.
        because: String,
    },
}

/// One check, as the host reports it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckReport {
    /// The check's name.
    pub name: String,
    /// Where it is, in the host's own vocabulary.
    // llmlint: ignore[invalid_states_unrepresentable] this is `Check::status` passed
    // through, and the approved contract fixes that field as `String` and enumerates no
    // value set for it — the vocabulary differs per host, which is the thing this crate
    // exists to abstract, and it is recorded as open question 1 in
    // docs/inferred-surface.md for the planner to settle across the three repositories.
    // An enum here would decide that question locally *and* disagree with the type this
    // value is copied from.
    pub status: String,
    /// How it ended, once it has.
    // llmlint: ignore[invalid_states_unrepresentable] the other half of the same open
    // question, for the same reason: `Check::conclusion` is `Option<String>` because the
    // contract names the field and fixes no conclusion vocabulary. Absent means the check
    // has not concluded, which is the one state this report does narrow.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conclusion: Option<String>,
    /// Whether it blocks the merge.
    pub required: bool,
}

/// The last gate verdict recorded for this work, and where its log was kept.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GateReport {
    /// What it ruled.
    pub verdict: Verdict,
    /// What ran.
    pub command: String,
    /// The preserved log, which outlives the tree the gate ran in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub log: Option<PathBuf>,
    /// The session stream that recorded it.
    pub recorded_by: String,
}

/// What a gate said about the work it was handed.
///
/// The two words a `gate-verdict` event is written with, and a third for one this
/// build cannot read: a verdict it did not understand is not a rejection, and
/// reporting it as one would name a gate that never refused anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Verdict {
    /// It verified the change.
    Pass,
    /// It refused the change.
    Fail,
    /// The event named a verdict this build does not read.
    Unrecorded,
}

/// The command that advances the work, or why none does.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NextReport {
    /// The exact invocation, quoted so that running it as printed runs it over
    /// the same arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Why that is the next step, or why there is none.
    pub because: String,
}

/// One piece of work: the identity it belongs to and the branch that carries it.
struct Work {
    /// The identity key.
    // llmlint: ignore[invalid_states_unrepresentable] an identity key is a `String`
    // everywhere this crate spells one — the registry document's own map key,
    // `Recoverable::identity`, `SessionRecord::identity` — so a newtype here would
    // disagree with the types the contract fixes. Every value that reaches this came out
    // of a registry `store::resolve` accepted, which is where a key is decided.
    identity: String,
    /// The branch that carries it, as git's own parser accepted it.
    branch: Ref,
}

pub fn run(registry: &Registry, reference: &str, hosting: &dyn Hosting) -> Result<Report> {
    let mut notes = Vec::new();
    let streams = recorded_streams(&mut notes)?;
    let (work, kind) = resolve(registry, reference, &streams)?;

    let resolution = store::resolve(registry, &work.identity)?;
    let (file, source) = policy::load(registry)?;
    let trailers = provenance::from_rules(&file);
    let normalized = store::normalize(&resolution.identity.origin);
    let resolved = policy::resolve(&file, &source, &normalized, &resolution.publication);
    // Named by git itself, off the remote's own advertised head, so it is a branch
    // name git's parser has already accepted.
    let base = Ref::from_git(git::default_branch(&resolution.publication, "origin")?);

    let holders = holders_of(registry, &resolution, &work.branch)?;
    let sessions = workspace::all()?;
    let session = sessions
        .iter()
        .filter(|record| record.identity == work.identity && record.branch == work.branch)
        .max_by_key(|record| record.state == Lifecycle::Open)
        .map(|record| SessionReport {
            token: record.token.clone(),
            state: record.state,
            liveness: SessionHolder::from(record.clone()).liveness,
            base: record.base.clone(),
            clone: record.clone.clone(),
            worktree: record.worktree.clone(),
        });

    // The copy that holds the work rather than the name, by the rule `branch::locate`
    // takes: a copy whose content the base already carries is spent, and answering
    // from that one would report work that sits under the same name elsewhere as
    // work nobody has.
    let current = vcs::base_commit(&resolution.publication, &base);
    let mut carrier: Option<(PathBuf, String)> = None;
    for holder in &holders {
        let compared = vcs::judged_against(&holder.path, &base, current.as_ref());
        let differs = git::trees_differ(&holder.path, &compared, &work.branch)?;
        if differs {
            carrier = Some((holder.path.clone(), compared));
            break;
        }
        carrier.get_or_insert((holder.path.clone(), compared));
    }

    let mut ahead = None;
    let mut branch_provenance = None;
    let mut change_base = None;
    let mut on_the_branch = OnTheBranch::Nowhere;
    if let Some((repo, compared)) = &carrier {
        let counted = git::log_messages(repo, compared, &work.branch)?.len();
        ahead = Some(counted);
        on_the_branch = if git::trees_differ(repo, compared, &work.branch)? {
            OnTheBranch::Ahead
        } else {
            OnTheBranch::Carried { ahead: counted }
        };
        branch_provenance = Some(judge_provenance(repo, compared, &work.branch, &trailers)?);
        // Read back out of a commit the repository carries, so it is input: a value
        // that is not a branch name is no change base, and the branch-keyed verbs
        // refuse one by name where they are the ones about to act on it.
        change_base = provenance::recorded_change_base(repo, compared, &work.branch, &trailers)?
            .and_then(|recorded| Ref::try_from(recorded).ok());
    }

    // Latest-first by the envelope's own timestamp rather than by the order the
    // streams happened to be listed in: a branch published twice has two records of
    // itself, and the newer one is the one somebody is asking about.
    let relevant = relevant_streams(&streams, &work, session.as_ref());
    let change_url = latest(
        relevant
            .iter()
            .filter_map(|record| record.change_url.clone()),
    );
    let asked_the_host_to_land = relevant.iter().any(|record| record.asked_the_host_to_land);
    let gate = latest(relevant.iter().filter_map(|record| record.gate.clone()));

    let target = change_base.clone().unwrap_or_else(|| base.clone());
    let host = ask_the_host(&resolution.key, &work.branch, &target, hosting);
    let state = landing(
        on_the_branch,
        host.said(),
        match (change_url.is_some(), asked_the_host_to_land) {
            (false, _) => Proposed::Never,
            (true, false) => Proposed::Opened,
            (true, true) => Proposed::OpenedAndAskedToLand,
        },
    );
    let (open, checks) = host.into_parts();
    let change_url = open.or(change_url);

    let next = next_step(&Advance {
        resolution: &resolution,
        work: &work,
        base: &base,
        state,
        change_url: change_url.as_deref(),
        session: session.as_ref(),
        provenance: branch_provenance,
        nobody_has_it: holders.is_empty(),
    });

    Ok(Report {
        version: ReportVersion::current(),
        reference: Reference {
            given: reference.to_owned(),
            kind,
        },
        identity: IdentityReport {
            key: resolution.key.clone(),
            publication_checkout: resolution.publication.clone(),
            workflow: resolution.identity.workflow,
            repo_type: resolution.identity.repo_type,
            gate: resolved.policy.gate.clone(),
            approvals: resolved.policy.approvals,
        },
        session,
        branch: BranchReport {
            name: work.branch.clone(),
            base,
            change_base,
            holders,
            ahead,
            provenance: branch_provenance,
        },
        publication: PublicationReport {
            state,
            change_url,
            merge_policy: resolved.policy.publication,
        },
        checks,
        gate,
        next,
        notes,
    })
}

/// What the branch's own copies say, which is the evidence that stands whatever
/// the host says and whoever merged it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OnTheBranch {
    /// Nothing this identity keeps work in holds the branch.
    Nowhere,
    /// It has commits whose content the base does not carry.
    Ahead,
    /// The base already carries everything it changed, over this many commits of
    /// its own — nought being a branch that is the base.
    Carried {
        /// How many commits it has that the base does not have by name.
        ahead: usize,
    },
}

/// What the host said about a change request from this branch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OnTheHost {
    /// It could not be asked, so it has said nothing — which is not the same as
    /// saying there is nothing.
    Unasked,
    /// It answered, and holds no open change request from this branch.
    NothingOpen,
    /// It answered, and holds one open.
    Open,
}

/// What this host recorded about ever proposing the work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Proposed {
    /// Nothing here opened a change request for it.
    Never,
    /// One was opened, and nothing asked the host to land it.
    Opened,
    /// One was opened, and the host was asked to land it once its checks pass.
    OpenedAndAskedToLand,
}

/// Which of the seven states the work is in.
///
/// Content first, deliberately: the base carrying what a branch changed is the one
/// answer that stays true whatever the host says and whoever merged it, and it is
/// the answer a planner got wrong by consulting the absence of an open change
/// request instead.
fn landing(branch: OnTheBranch, host: OnTheHost, proposed: Proposed) -> Landing {
    match branch {
        OnTheBranch::Carried { ahead: 0 } => return Landing::NothingToPublish,
        OnTheBranch::Carried { .. } => return Landing::Landed,
        OnTheBranch::Ahead | OnTheBranch::Nowhere => {}
    }
    match (host, proposed) {
        (OnTheHost::Open, Proposed::OpenedAndAskedToLand) => Landing::Queued,
        (OnTheHost::Open, _) => Landing::Open,
        (_, Proposed::Never) => Landing::Unpublished,
        // A change request was opened once. Whether it is still open is the host's
        // to say, and a host that would not say has not said it was closed.
        (OnTheHost::NothingOpen, _) => Landing::Closed,
        (OnTheHost::Unasked, _) => Landing::Published,
    }
}

/// What the host says, and — where it says nothing — why.
enum HostAnswer {
    /// No host answers for this identity, or the one that does could not be asked.
    /// It has therefore said nothing at all — including nothing about there being
    /// no change request.
    Unasked {
        /// What the host, the credential, or `gh` itself said.
        because: String,
    },
    /// It answered, and holds no open change request from this branch.
    NothingOpen,
    /// It holds one open, and this is what it says about that change's checks —
    /// which a credential may be allowed to see less of than the change itself.
    Open {
        /// Where a human reads it.
        url: String,
        /// Its checks, or why they could not be read.
        checks: ChecksReport,
    },
}

impl HostAnswer {
    /// What the host said, for the one decision that reads it.
    fn said(&self) -> OnTheHost {
        match self {
            HostAnswer::Unasked { .. } => OnTheHost::Unasked,
            HostAnswer::NothingOpen => OnTheHost::NothingOpen,
            HostAnswer::Open { .. } => OnTheHost::Open,
        }
    }

    /// The change request it holds open, and the section the report prints.
    fn into_parts(self) -> (Option<String>, ChecksReport) {
        let reported = || ChecksReport::Reported {
            checks: Vec::new(),
            sources: Vec::new(),
        };
        match self {
            HostAnswer::Unasked { because } => (None, ChecksReport::Unavailable { because }),
            HostAnswer::NothingOpen => (None, reported()),
            HostAnswer::Open { url, checks } => (Some(url), checks),
        }
    }
}

/// Ask the host what the change request is doing, never failing over the answer.
///
/// Two calls, and each failure is captured rather than raised: an unauthenticated
/// or unreachable host is a section of this report that is unavailable, not a
/// command that produces nothing. A local identity has no host at all, which is
/// the same shape of gap and says so in the same place.
fn ask_the_host(identity: &str, branch: &str, base: &str, hosting: &dyn Hosting) -> HostAnswer {
    let unasked = |because: String| HostAnswer::Unasked { because };
    let Some(slug) = gh::slug(identity) else {
        return unasked(format!(
            "identity {identity:?} is not a {} repository, so no host answers for it",
            gh::HOST
        ));
    };
    let host = match hosting.for_repo(&slug) {
        Ok(host) => host,
        Err(error) => return unasked(error.to_string()),
    };
    let open = match host.find_changes(branch, base) {
        Ok(changes) => changes.into_iter().next(),
        Err(error) => return unasked(error.to_string()),
    };
    let Some(change) = open else {
        return HostAnswer::NothingOpen;
    };
    let url = change.url.to_string();
    let checks = match host.change_checks(&change) {
        Ok(answer) => ChecksReport::Reported {
            checks: answer
                .checks
                .into_iter()
                .map(|check| CheckReport {
                    name: check.name,
                    status: check.status,
                    conclusion: check.conclusion,
                    required: check.required,
                })
                .collect(),
            sources: answer.sources.into_iter().collect(),
        },
        // The change request is open — that much the host did say — and only what
        // its checks are doing is missing.
        Err(error) => ChecksReport::Unavailable {
            because: error.to_string(),
        },
    };
    HostAnswer::Open { url, checks }
}

/// Everything the next step is decided from.
///
/// One value rather than eight arguments, because every one of them is read by the
/// same one decision and a caller that passed two of them in the wrong order would
/// produce a report that reads perfectly.
#[derive(Clone, Copy)]
struct Advance<'a> {
    resolution: &'a Resolution,
    work: &'a Work,
    base: &'a str,
    state: Landing,
    change_url: Option<&'a str>,
    session: Option<&'a SessionReport>,
    provenance: Option<BranchProvenance>,
    nobody_has_it: bool,
}

/// The command that advances this work, or why none applies.
///
/// The three answers `recoverable` could only give by staying silent are here as
/// sentences: the change landed, a live session still holds the branch, or the work
/// is preserved and unpublished and this is the verb that lands it.
fn next_step(seen: &Advance<'_>) -> NextReport {
    let Advance {
        resolution,
        work,
        base,
        state,
        change_url,
        session,
        provenance,
        nobody_has_it,
    } = *seen;
    let says = |because: String| NextReport {
        command: None,
        because,
    };
    let change = change_url.unwrap_or("the change request");
    match state {
        Landing::Landed => says(format!(
            "the work landed: {base} already carries what branch {branch:?} changed, which is what \
             a squash-merge leaves behind. Nothing advances it",
            branch = work.branch,
        )),
        Landing::NothingToPublish => says(format!(
            "branch {branch:?} has nothing {base} does not already carry, so there is nothing to \
             publish",
            branch = work.branch,
        )),
        Landing::Queued => says(format!(
            "the host has queued the merge of {change} and lands it once its required checks pass"
        )),
        Landing::Open => says(format!(
            "{change} is open on the host and lands when what its policy waits for — review, or \
             the host's required checks — is done"
        )),
        Landing::Published => says(format!(
            "{change} was opened for this branch, and the host could not be asked what became of \
             it; the checks section says why"
        )),
        Landing::Closed | Landing::Unpublished => {
            if nobody_has_it {
                return says(format!(
                    "no checkout or run clone of identity {key:?} holds branch {branch:?}, so there \
                     is nothing here to publish. `onevcs import` makes a branch reachable again",
                    key = resolution.key,
                    branch = work.branch,
                ));
            }
            // Open rather than *live*: an open session still holds the branch
            // whether or not the process that opened it is there, and publishing
            // that session is what lands it either way. Whose it is — and whether
            // anybody is still in it — is the session section's answer, which is
            // why liveness is reported beside this rather than folded into it.
            if let Some(session) = session.filter(|session| session.state == Lifecycle::Open) {
                return NextReport {
                    command: Some(guidance::command(["onevcs", "publish", &session.token])),
                    because: format!(
                        "session {token} is open and still holds branch {branch:?} (its owner is \
                         {liveness}), so this is not preserved work: publishing the session is \
                         what lands it",
                        token = session.token,
                        branch = work.branch,
                        liveness = session.liveness.as_str(),
                    ),
                };
            }
            let repo = resolution.publication.to_string_lossy();
            let interrupted = provenance == Some(BranchProvenance::IncompleteUnattested);
            let verb = if interrupted {
                "recover"
            } else {
                "publish-branch"
            };
            NextReport {
                command: Some(guidance::command([
                    "onevcs",
                    verb,
                    &work.branch,
                    "--repo",
                    &repo,
                ])),
                because: if interrupted {
                    format!(
                        "branch {branch:?} is preserved and unpublished, and carries an unattested \
                         incomplete marker: only `recover` may publish it, because publishing it \
                         means attesting that a gate cleared the step that stopped",
                        branch = work.branch,
                    )
                } else {
                    format!(
                        "branch {branch:?} is preserved and unpublished: it has commits {base} does \
                         not carry, and no session holds it",
                        branch = work.branch,
                    )
                },
            }
        }
    }
}

/// Which of the three provenance answers a branch's history gives.
///
/// A marker under a prefix this host cannot read is an incomplete step whatever
/// wrote it, for the reason `recoverable` reports one: nothing recognizes it, so
/// nothing else would refuse it.
fn judge_provenance(
    repo: &Path,
    compared: &str,
    branch: &str,
    trailers: &provenance::Trailers,
) -> Result<BranchProvenance> {
    if !provenance::unrecognized(repo, compared, branch, trailers)?.is_empty()
        || !provenance::unattested(repo, compared, branch, trailers)?.is_empty()
    {
        return Ok(BranchProvenance::IncompleteUnattested);
    }
    Ok(
        match provenance::provenance_of(repo, compared, branch, trailers)? {
            Provenance::IncompleteStep => BranchProvenance::IncompleteAttested,
            Provenance::Complete => BranchProvenance::Complete,
        },
    )
}

fn holders_of(registry: &Registry, resolution: &Resolution, branch: &str) -> Result<Vec<Holder>> {
    let sessions = workspace::all()?;
    let mut holders = Vec::new();
    for path in workspace::checkouts_of(registry, resolution)? {
        if !git::is_repo(&path) || !git::branch_exists(&path, branch) {
            continue;
        }
        let kind = if path == resolution.publication {
            HolderKind::PublicationCheckout
        } else if registry
            .checkouts
            .values()
            .any(|checkout| checkout.path == path)
        {
            HolderKind::RegisteredCheckout
        } else {
            HolderKind::RunClone
        };
        let session = sessions
            .iter()
            .find(|record| record.clone == path)
            .map(|record| record.token.clone());
        holders.push(Holder {
            path,
            kind,
            session,
        });
    }
    Ok(holders)
}

/// What one session's event stream recorded about the work it was written for.
///
/// The stream is what `onevcs` knows it did, and it is the only durable link from a
/// change request's URL back to the branch that opened it: the URL is the host's
/// name for the change, and nothing on the branch carries it.
#[derive(Debug, Clone)]
struct Recorded {
    token: String,
    identity: Option<String>,
    branch: Option<String>,
    change_url: Option<Stamped<String>>,
    asked_the_host_to_land: bool,
    gate: Option<Stamped<GateReport>>,
}

/// The moment an envelope was stamped, in the one form the shared envelope fixes:
/// RFC3339 at millisecond precision in UTC.
///
/// The check is in the conversion, because ordering is the *only* thing this crate
/// does with a timestamp and that form is the whole reason ordering can be a string
/// comparison: it is fixed width, so every field lines up. A value of another shape
/// sorts against these arbitrarily, and what it would decide — which of two change
/// requests a branch has is the newer — would be quietly wrong rather than absent.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Stamp(String);

impl Stamp {
    /// The stamp a value spells, if it spells one at all.
    ///
    /// Two questions, and both have to hold. It has to be a moment — parsed against
    /// the calendar the envelope names, so `9999-99-99T99:99:99.999Z` is refused
    /// rather than accepted for looking like one. And it has to be *this* spelling
    /// of that moment, which is the fixed width that makes ordering these a string
    /// comparison: a shorter year or a dropped millisecond would parse and then sort
    /// against the rest wrongly.
    fn parse(value: &str) -> Option<Self> {
        // `2026-08-07T12:34:56.789Z`, which is what `ids::timestamp` writes: the
        // separators where they are, and every other position a digit.
        const SHAPE: &str = "0000-00-00T00:00:00.000Z";
        if value.len() != SHAPE.len()
            || !value.chars().zip(SHAPE.chars()).all(|(had, want)| {
                if want == '0' {
                    had.is_ascii_digit()
                } else {
                    had == want
                }
            })
        {
            return None;
        }
        let field = |from: usize, to: usize| value[from..to].parse::<u32>().ok();
        // The calendar itself, through the constructors that are it: a month, a day
        // that month has, and a time of day. `time` decides those, not this.
        Date::from_calendar_date(
            i32::try_from(field(0, 4)?).ok()?,
            Month::try_from(u8::try_from(field(5, 7)?).ok()?).ok()?,
            u8::try_from(field(8, 10)?).ok()?,
        )
        .ok()?;
        Time::from_hms_milli(
            u8::try_from(field(11, 13)?).ok()?,
            u8::try_from(field(14, 16)?).ok()?,
            u8::try_from(field(17, 19)?).ok()?,
            u16::try_from(field(20, 23)?).ok()?,
        )
        .ok()?;
        Some(Stamp(value.to_owned()))
    }
}

/// One thing a stream recorded, with the moment it recorded it.
#[derive(Debug, Clone)]
struct Stamped<T> {
    at: Stamp,
    value: T,
}

fn latest<T>(recorded: impl Iterator<Item = Stamped<T>>) -> Option<T> {
    recorded
        .max_by(|left, right| left.at.cmp(&right.at))
        .map(|stamped| stamped.value)
}

/// Every stream this host has, read for what it says about the work it recorded.
///
/// A directory nothing has written a stream into is nought streams; every other way
/// the listing can go wrong is a *gap*, and it says so. The two must not look alike:
/// what a stream decides here is which change request a branch has and what its gate
/// said, and reporting "could not look" as "there is none" is how a report about half
/// the record reads as a report about all of it.
fn recorded_streams(notes: &mut Vec<String>) -> Result<Vec<Recorded>> {
    let directory = home::streams_dir()?;
    let entries = match std::fs::read_dir(&directory) {
        Ok(entries) => entries,
        Err(failure) if failure.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(failure) => {
            notes.push(format!(
                "the event streams at {} could not be listed ({failure}), so nothing any session \
                 recorded is in this report",
                directory.display()
            ));
            return Ok(Vec::new());
        }
    };
    let mut tokens: Vec<String> = Vec::new();
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(failure) => {
                notes.push(format!(
                    "an entry of the event streams at {} could not be read ({failure}), so \
                     whatever session it belongs to is not in this report",
                    directory.display()
                ));
                continue;
            }
        };
        if let Some(token) = entry
            .file_name()
            .to_string_lossy()
            .strip_suffix(".ndjson")
            .map(str::to_owned)
        {
            tokens.push(token);
        }
    }
    tokens.sort();
    Ok(tokens
        .into_iter()
        .map(|token| read_stream(&directory, &token, notes))
        .collect())
}

/// One stream, read as the values it holds and said so where it could not be.
///
/// Every line goes through [`crate::stream::attributed`], which is the seam
/// `EventStream` reads through — so a line this build cannot parse, and one
/// carrying another stream's event, are refused here for the same two reasons they
/// are refused there rather than being interpreted as an envelope this happens to
/// be able to index into. What differs is what a refusal does: this command is
/// asked what became of a piece of work, so a line it could not read becomes a note
/// in the report rather than the whole answer. Nothing safety-critical rests on it
/// — whether the work *landed* is read off the base's content, never off a stream.
fn read_stream(directory: &Path, token: &str, notes: &mut Vec<String>) -> Recorded {
    let mut record = Recorded {
        token: token.to_owned(),
        identity: None,
        branch: None,
        change_url: None,
        asked_the_host_to_land: false,
        gate: None,
    };
    let path = directory.join(format!("{token}.ndjson"));
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        // Listed and then unreadable: a gap, not a session that recorded nothing.
        Err(failure) => {
            notes.push(format!(
                "the event stream at {} could not be read ({failure}), so what it recorded is not \
                 in this report",
                path.display()
            ));
            return record;
        }
    };
    for (index, line) in raw.lines().enumerate() {
        let event = match stream::attributed(line, token, index + 1) {
            Ok(event) => event,
            Err(refusal) => {
                notes.push(format!(
                    "{refusal}, so whatever it recorded is not in this report ({})",
                    path.display()
                ));
                continue;
            }
        };
        // The envelope is versioned and this report orders by its timestamp, so an
        // envelope of a shape this build does not read, or one whose stamp cannot be
        // ordered against the rest, is a gap said out loud rather than a value acted
        // on. Nothing safety-critical rests on either: whether the work *landed* is
        // read off the base's content.
        if event.v != stream::ENVELOPE_VERSION {
            notes.push(format!(
                "line {} of the event stream at {} declares envelope version {}, and this build \
                 reads version {}, so what it recorded is not in this report",
                index + 1,
                path.display(),
                event.v,
                stream::ENVELOPE_VERSION,
            ));
            continue;
        }
        let Some(at) = Stamp::parse(&event.ts) else {
            notes.push(format!(
                "line {} of the event stream at {} is stamped {:?}, which is not the RFC3339 \
                 millisecond UTC the envelope declares, so what it recorded cannot be ordered \
                 against the rest and is not in this report",
                index + 1,
                path.display(),
                event.ts,
            ));
            continue;
        };
        if record.identity.is_none() {
            record.identity = event.labels.extra.get("identity").and_then(text);
        }
        if record.branch.is_none() {
            record.branch = event.payload.get("branch").and_then(text);
        }
        let field = |name: &str| event.payload.get(name).and_then(text);
        match event.kind {
            EventKind::ChangeOpened => {
                if let Some(url) = field("url") {
                    record.change_url = Some(Stamped { at, value: url });
                }
            }
            // Emitted with the change request's URL only where this crate went on to
            // ask the host to land it; the local merge train emits one without.
            EventKind::MergeQueued => {
                record.asked_the_host_to_land |= field("url").is_some();
            }
            EventKind::GateVerdict => {
                record.gate = Some(Stamped {
                    at,
                    value: GateReport {
                        verdict: match field("verdict").as_deref() {
                            Some("pass") => Verdict::Pass,
                            Some("fail") => Verdict::Fail,
                            _ => Verdict::Unrecorded,
                        },
                        command: field("command")
                            .unwrap_or_else(|| "a command the event did not name".to_owned()),
                        log: field("preserved_log").map(PathBuf::from),
                        recorded_by: token.to_owned(),
                    },
                });
            }
            _ => {}
        }
    }
    record
}

fn text(value: &Value) -> Option<String> {
    value
        .as_str()
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
}

/// The streams that recorded this work: the session's own, and the deterministic
/// ones the two branch-keyed verbs write.
fn relevant_streams<'a>(
    streams: &'a [Recorded],
    work: &Work,
    session: Option<&SessionReport>,
) -> Vec<&'a Recorded> {
    let slug = policy::branch_slug(&work.branch);
    let named: BTreeSet<String> = [
        session.map(|session| session.token.to_string()),
        Some(format!("publish-branch-{slug}")),
        Some(format!("recover-{slug}")),
    ]
    .into_iter()
    .flatten()
    .collect();
    streams
        .iter()
        .filter(|record| {
            named.contains(&record.token)
                || (record.branch.as_deref() == Some(&*work.branch)
                    && record.identity.as_deref() == Some(work.identity.as_str()))
        })
        .collect()
}

/// Read one reference as the work it names.
///
/// The four spellings are tried in the order the surface documents them, and the
/// first that matches decides — so a session token is a session token even where a
/// branch of that name exists. Ambiguity is *within* a spelling: one branch name
/// can belong to two identities, and answering about whichever came first would be
/// a report about work nobody asked after.
fn resolve(registry: &Registry, reference: &str, streams: &[Recorded]) -> Result<(Work, RefKind)> {
    if reference.starts_with("http://") || reference.starts_with("https://") {
        return change_url(registry, reference, streams).map(|work| (work, RefKind::ChangeUrl));
    }
    if let Ok(record) = workspace::load(reference) {
        return Ok((
            Work {
                identity: record.identity,
                branch: record.branch.clone(),
            },
            RefKind::SessionToken,
        ));
    }
    // Through the conversion that decides branch names, so what is searched for is a
    // ref rather than the part of a command line that sat where one would.
    if let Ok(named) = Ref::try_from(reference.to_owned()) {
        let found = by_branch(registry, &named)?;
        if !found.is_empty() {
            return one(found, reference, "branch").map(|work| (work, RefKind::Branch));
        }
    }
    if reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
        let found = by_commit(registry, reference)?;
        if !found.is_empty() {
            return one(found, reference, "commit").map(|work| (work, RefKind::Commit));
        }
    }
    Err(Error::Invalid {
        reason: format!(
            "{reference:?} names no work this host knows: it is not a change request `onevcs` \
             opened, a session token it printed, a branch any checkout or run clone of a \
             registered identity holds, or a commit one of those branches carries. `onevcs repos` \
             lists the identities and `onevcs recoverable` lists the preserved branches"
        ),
    })
}

/// The one candidate, or a refusal naming every one of them.
fn one(found: Vec<Work>, reference: &str, spelling: &str) -> Result<Work> {
    let named: Vec<String> = found
        .iter()
        .map(|work| format!("{} in identity {:?}", work.branch, work.identity))
        .collect();
    let mut found = found;
    if found.len() == 1 {
        return Ok(found.remove(0));
    }
    Err(Error::Invalid {
        reason: format!(
            "{reference:?} is an ambiguous {spelling}: {count} pieces of work answer to it — \
             {candidates}. Ask about one of them by a reference only it has: a session token, or \
             the URL of its change request",
            count = named.len(),
            candidates = named.join("; "),
        ),
    })
}

/// The work whose change request one URL names.
fn change_url(registry: &Registry, url: &str, streams: &[Recorded]) -> Result<Work> {
    let recorded = streams
        .iter()
        .find(|record| {
            record
                .change_url
                .as_ref()
                .is_some_and(|recorded| recorded.value == url)
        })
        .ok_or_else(|| Error::Invalid {
            reason: format!(
                "no change request at {url} was opened through `onevcs` on this host, so nothing \
                 here records which branch it carries. Ask about the branch by name instead"
            ),
        })?;
    let branch = recorded.branch.clone().ok_or_else(|| Error::Invalid {
        reason: format!(
            "the event stream for {token:?} records the change request at {url} and names no \
             branch, so nothing here can tell which work it carries. `onevcs events {token}` is \
             what it does hold",
            token = recorded.token,
        ),
    })?;
    // A stream is a file written by whichever process produced it, so the branch it
    // names is input: it goes on to be handed to git as a ref, and one git would not
    // accept is refused by the conversion that decides branch names rather than met by
    // whichever command reached it first.
    let branch = Ref::try_from(branch).map_err(|reason| Error::Invalid {
        reason: format!(
            "the event stream for {token:?} records the change request at {url} as carrying \
             {reason}, so nothing here can look for it. `onevcs events {token}` is what that \
             stream holds",
            token = recorded.token,
        ),
    })?;
    if let Some(identity) = &recorded.identity {
        if registry.identities.contains_key(identity) {
            return Ok(Work {
                identity: identity.clone(),
                branch,
            });
        }
    }
    // A branch-keyed verb's stream carries no identity label, so the identity is the
    // one whose checkouts hold the branch — the same search everything else here uses.
    one(by_branch(registry, &branch)?, url, "change request")
}

/// Every identity holding a branch of this name.
fn by_branch(registry: &Registry, branch: &Ref) -> Result<Vec<Work>> {
    let mut found = Vec::new();
    for identity in identities(registry) {
        let resolution = store::resolve(registry, &identity)?;
        for path in workspace::checkouts_of(registry, &resolution)? {
            if git::is_repo(&path) && git::branch_exists(&path, branch) {
                found.push(Work {
                    identity: identity.clone(),
                    branch: branch.clone(),
                });
                break;
            }
        }
    }
    Ok(found)
}

/// Every branch of every identity that carries one commit.
///
/// The identity's own root base is not one of them: every branch that ever landed
/// is reachable from it, so answering with the base would report the repository
/// rather than the work.
fn by_commit(registry: &Registry, commit: &str) -> Result<Vec<Work>> {
    let mut found: Vec<Work> = Vec::new();
    for identity in identities(registry) {
        let resolution = store::resolve(registry, &identity)?;
        let root = git::default_branch(&resolution.publication, "origin").ok();
        for path in workspace::checkouts_of(registry, &resolution)? {
            if !git::is_repo(&path) || !git::has_commit(&path, &crate::host::Sha(commit.to_owned()))
            {
                continue;
            }
            for branch in git::branches(&path)? {
                if root.as_deref() == Some(branch.as_str()) {
                    continue;
                }
                if !git::is_ancestor(&path, commit, &branch)? {
                    continue;
                }
                // git's own ref listing, so its parser has already accepted every
                // name in it.
                let branch = Ref::from_git(branch);
                if found
                    .iter()
                    .any(|work| work.identity == identity && work.branch == branch)
                {
                    continue;
                }
                found.push(Work {
                    identity: identity.clone(),
                    branch,
                });
            }
        }
    }
    Ok(found)
}

/// Every identity with a registered checkout, in key order.
fn identities(registry: &Registry) -> Vec<String> {
    let mut keys: Vec<String> = registry
        .checkouts
        .values()
        .map(|checkout| checkout.identity.clone())
        .collect();
    keys.sort_unstable();
    keys.dedup();
    keys
}

impl Report {
    /// The report as a human reads it.
    pub fn render(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "work: {} [{}]\n",
            self.branch.name, self.identity.key
        ));
        out.push_str(&format!(
            "identity:\n  key: {}\n  publication checkout: {}\n  workflow: {}\n  repo_type: {}\n  \
             gate: {}\n  approvals: {}\n",
            self.identity.key,
            self.identity.publication_checkout.display(),
            spell_workflow(self.identity.workflow),
            spell_repo_type(self.identity.repo_type),
            policy::spell_gate(&self.identity.gate),
            spell_approvals(self.identity.approvals),
        ));
        match &self.session {
            Some(session) => out.push_str(&format!(
                "session:\n  token: {}\n  state: {} ({})\n  base: {}\n  clone: {}\n  worktree: {}\n",
                session.token,
                match session.state {
                    Lifecycle::Open => "open",
                    Lifecycle::Closed => "closed",
                },
                session.liveness.as_str(),
                session.base,
                session.clone.display(),
                session.worktree.display(),
            )),
            None => out.push_str("session: none recorded for this branch\n"),
        }
        out.push_str("branch:\n");
        out.push_str(&format!("  name: {}\n", self.branch.name));
        out.push_str(&format!("  base: {}\n", self.branch.base));
        if let Some(change_base) = &self.branch.change_base {
            out.push_str(&format!("  change base recorded: {change_base}\n"));
        }
        match self.branch.ahead {
            Some(ahead) => out.push_str(&format!(
                "  ahead of {}: {ahead} commit(s)\n",
                self.branch.base
            )),
            None => out.push_str("  ahead: unknown — nothing on this host holds the branch\n"),
        }
        out.push_str(&format!(
            "  provenance: {}\n",
            match self.branch.provenance {
                Some(BranchProvenance::Complete) => "complete",
                Some(BranchProvenance::IncompleteUnattested) => "incomplete (unattested)",
                Some(BranchProvenance::IncompleteAttested) => "incomplete (attested)",
                None => "unknown — nothing on this host holds the branch",
            }
        ));
        if self.branch.holders.is_empty() {
            out.push_str("  held by: nothing this identity keeps work in\n");
        } else {
            out.push_str("  held by:\n");
            for holder in &self.branch.holders {
                let what = match holder.kind {
                    HolderKind::PublicationCheckout => "publication checkout".to_owned(),
                    HolderKind::RegisteredCheckout => "registered checkout".to_owned(),
                    HolderKind::RunClone => match &holder.session {
                        Some(token) => format!("run clone of session {token}"),
                        None => "run clone".to_owned(),
                    },
                };
                out.push_str(&format!("    {} ({what})\n", holder.path.display()));
            }
        }
        out.push_str("publication:\n");
        out.push_str(&format!(
            "  state: {}\n",
            spell_landing(self.publication.state)
        ));
        out.push_str(&format!(
            "  landed: {}\n",
            if self.publication.state.landed() {
                "yes"
            } else {
                "no"
            }
        ));
        out.push_str(&format!(
            "  change request: {}\n",
            self.publication
                .change_url
                .as_deref()
                .unwrap_or("none recorded")
        ));
        out.push_str(&format!(
            "  merge policy: {}\n",
            policy::spell(self.publication.merge_policy)
        ));
        match &self.checks {
            ChecksReport::Unavailable { because } => {
                out.push_str(&format!("checks: unavailable — {because}\n"));
            }
            ChecksReport::Reported { checks, .. } if checks.is_empty() => {
                out.push_str("checks: none reported on this work\n");
            }
            ChecksReport::Reported { checks, sources } => {
                out.push_str("checks:\n");
                for check in checks {
                    out.push_str(&format!(
                        "  {}\t{}\t{}\t{}\n",
                        check.name,
                        check.status,
                        check.conclusion.as_deref().unwrap_or("-"),
                        if check.required {
                            "required"
                        } else {
                            "not required"
                        },
                    ));
                }
                out.push_str(&format!(
                    "  sources: {}\n",
                    sources
                        .iter()
                        .map(spell_source)
                        .collect::<Vec<_>>()
                        .join(", ")
                ));
            }
        }
        match &self.gate {
            Some(gate) => {
                out.push_str(&format!(
                    "gate:\n  verdict: {}\n  command: {}\n  recorded by: {}\n",
                    spell_verdict(gate.verdict),
                    gate.command,
                    gate.recorded_by
                ));
                if let Some(log) = &gate.log {
                    out.push_str(&format!("  log: {}\n", log.display()));
                }
            }
            None => out.push_str("gate: no verdict recorded for this work\n"),
        }
        out.push_str("next:\n");
        match &self.next.command {
            Some(command) => out.push_str(&format!("  {command}\n")),
            None => out.push_str("  nothing advances this work\n"),
        }
        out.push_str(&format!("  because: {}\n", self.next.because));
        for note in &self.notes {
            out.push_str(&format!("note: {note}\n"));
        }
        out
    }
}

fn spell_landing(state: Landing) -> &'static str {
    match state {
        Landing::Landed => "landed",
        Landing::Queued => "queued",
        Landing::Open => "open",
        Landing::Closed => "closed without landing",
        Landing::Published => "published (the host could not be asked what became of it)",
        Landing::NothingToPublish => "nothing to publish",
        Landing::Unpublished => "unpublished",
    }
}

fn spell_workflow(workflow: Workflow) -> &'static str {
    match workflow {
        Workflow::Local => "local",
        Workflow::Remote => "remote",
    }
}

fn spell_repo_type(repo_type: RepoType) -> &'static str {
    match repo_type {
        RepoType::SingleOwner => "single-owner",
        RepoType::Team => "team",
    }
}

fn spell_approvals(approvals: Approvals) -> &'static str {
    match approvals {
        Approvals::Required => "required",
        Approvals::None => "none",
    }
}

fn spell_verdict(verdict: Verdict) -> &'static str {
    match verdict {
        Verdict::Pass => "pass",
        Verdict::Fail => "fail",
        Verdict::Unrecorded => "a verdict this build does not read",
    }
}

fn spell_source(source: &CheckSource) -> &'static str {
    match source {
        CheckSource::StatusChecks => "status-checks",
        CheckSource::Actions => "actions",
        CheckSource::BranchRules => "branch-rules",
    }
}

/// The report is a *type's* serialization contract, and this is the only place it
/// can be held to one.
///
/// The fourth `#[cfg(test)]` module in this crate, for the reason the other three
/// exist: what it exercises is reachable no other way. `tests/e2e/accounting.rs`
/// drives the real CLI and holds its bytes to the goldens below, which is the half a
/// consumer meets — but a consumer also *reads* those bytes back, and the types that
/// answer for that are deliberately private, so proving they round-trip from outside
/// the crate would mean making a dozen of them public for a test's benefit. The two
/// halves read the same two files, so neither can drift from the other.
#[cfg(test)]
mod round_trip {
    use super::{Report, ReportVersion, REPORT_VERSION};
    use serde_json::Value;

    /// The same bytes `tests/e2e/accounting.rs` holds the real CLI's output to.
    const FULL: &str = include_str!("../tests/golden/status-report-v1.json");
    const MINIMAL: &str = include_str!("../tests/golden/status-report-v1-minimal.json");

    /// One golden as the object a consumer parses.
    fn parsed(golden: &str) -> Value {
        serde_json::from_str(golden).expect("a golden is JSON")
    }

    #[test]
    fn both_checked_in_goldens_read_back_as_reports_and_write_themselves_again() {
        for (name, golden) in [("full", FULL), ("minimal", MINIMAL)] {
            let report: Report = serde_json::from_str(golden)
                .unwrap_or_else(|e| panic!("the {name} golden reads back as a report: {e}"));
            assert_eq!(
                serde_json::to_value(&report).expect("a report serializes"),
                parsed(golden),
                "the {name} golden and the report it reads back as disagree"
            );
        }

        // The values arrive as the validated shapes they were written from, rather
        // than as text a reader would have to check again.
        let full: Report = serde_json::from_str(FULL).expect("the full golden");
        assert_eq!(full.version, ReportVersion::current());
        assert_eq!(&*full.branch.name, "feature/full");
        assert_eq!(
            full.branch.change_base.as_deref(),
            Some("feature/below"),
            "a recorded change base reads back as the branch name it is"
        );
        assert_eq!(
            &*full.session.expect("the full golden names a session").token,
            "s-000000000000"
        );

        // …and a field the minimal golden omits reads back as absent rather than as
        // a value, which is the other half of writing it out only when it is held.
        let minimal: Report = serde_json::from_str(MINIMAL).expect("the minimal golden");
        assert!(minimal.session.is_none());
        assert!(minimal.gate.is_none());
        assert!(minimal.branch.change_base.is_none());
        assert!(minimal.publication.change_url.is_none());
        assert!(minimal.notes.is_empty());
    }

    #[test]
    fn a_report_declaring_a_version_this_build_does_not_read_is_refused_where_it_is_read() {
        // The number exists to be acted on, so a document this build cannot read is
        // refused at the boundary rather than read as the shape it is not.
        for declared in [0, REPORT_VERSION + 1, u32::MAX] {
            let mut document = parsed(FULL);
            document["version"] = Value::from(declared);
            let refusal = serde_json::from_value::<Report>(document)
                .expect_err("a version this build does not read is refused")
                .to_string();
            assert!(
                refusal.contains(&format!("declares version {declared}"))
                    && refusal.contains(&format!("this build reads version {REPORT_VERSION}")),
                "the refusal names neither the version nor the one this build reads: {refusal}"
            );
        }

        // A key nobody declared is refused for the same reason the registry document
        // refuses one: it is usually a typo for one that matters, and half-reading a
        // document is how a consumer acts on a field it never saw.
        let mut document = parsed(FULL);
        document["landed"] = Value::Bool(true);
        assert!(serde_json::from_value::<Report>(document).is_err());
    }
}