onevcs-testing 0.19.1

In-memory and file-backed implementations of onevcs's Vcs and RemoteHost interfaces, for driving a real onevcs in a test.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
//! The repository side: one implementation of [`Vcs`] over either store.
//!
//! What it is not: git. It answers the questions the interface asks, records what
//! it was asked, and emits the events the real implementation emits. What it
//! cannot do is tell you whether a tree is dirty or whether a merge conflicts,
//! because there is no tree — a journey that needs those drives the real `Git`.
//!
//! Publishing is the one operation that reaches past the repository: the host side
//! of it is *performed*, against the [`Hosting`] the publication was handed, and
//! the repository side of it is neither performed nor claimed. What that leaves
//! out is written where each piece is left out.

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

use serde_json::{json, Map, Value};

use std::collections::BTreeSet;

use onevcs::rules::{Approvals, Drafts};
use onevcs::testing::EmissionResult;
use onevcs::{
    ArmedMerge, ChangeRequest, ChangeSpec, Check, CheckState, DraftReason, Error, EventKind,
    FailureKind, HeldBy, Holding, Hosting, Identity, Landed, Lifecycle, MergeOutcome, MergePolicy,
    PreservedBranch, Provenance, Publication, PublishOutcome, PublishRequest, Recoverable,
    RemoteHost, Result, Scope, Session, SessionRecord, SessionRequest, SessionToken, Sha, Vcs,
};

use crate::events::{self, Emission};
use crate::remote::DEFAULT_HOST;
use crate::state::{self, VcsState};
use crate::store::{FileStore, MemoryStore, Store};

/// The base a session is cut from when the request names none.
///
/// The real implementation asks the origin for its default branch, and this
/// provider has no origin to ask.
pub const DEFAULT_BASE: &str = "main";

/// The policy a publication takes when nothing was seeded and nothing requested.
///
/// The policy the contract's own `default:` names, which is what the real
/// implementation resolves to for a registry with no rules file.
pub const DEFAULT_PUBLICATION: MergePolicy = MergePolicy::ChangeOpen;

/// The approvals a publication takes when nothing was seeded: the contract's own
/// `default:`, as [`DEFAULT_PUBLICATION`] is.
pub const DEFAULT_APPROVALS: Approvals = Approvals::Required;

/// The repository side of a run, over whichever store holds its state.
///
/// The two flavours below are this one behaviour with a different store under it,
/// so neither can learn something the other does not know.
#[derive(Debug)]
pub struct Repository<T> {
    store: T,
    root: PathBuf,
    trees: Trees,
}

/// What a session's worktree path means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Trees {
    /// The path is named and nothing is created there: the in-memory provider
    /// touches no filesystem beyond the event stream.
    Named,
    /// The directory is created, so a journey has somewhere to write work.
    Created,
}

/// A repository provider that keeps its state in this process: no disk, no
/// visibility to a second process, and the fastest of the two.
///
/// Its sessions name a worktree under the system temporary directory and **do not
/// create it** — nothing here touches the filesystem except the event stream, which
/// is the record a journey reads.
pub type MemoryVcs = Repository<MemoryStore<VcsState>>;

/// A repository provider that keeps its state in one JSON document, so several
/// `onevcs` invocations see one another's effects.
///
/// Its sessions name a worktree beside that document **and create it**, so a
/// journey that writes a file into a session's tree has somewhere to write it.
pub type FileVcs = Repository<FileStore<VcsState>>;

impl MemoryVcs {
    /// A repository provider knowing nothing.
    pub fn new() -> Self {
        Self::seeded(VcsState::default())
    }

    /// A repository provider that starts from a scenario.
    pub fn seeded(state: VcsState) -> Self {
        Self {
            store: MemoryStore::new(state),
            root: std::env::temp_dir().join("onevcs-testing-memory"),
            trees: Trees::Named,
        }
    }

    /// Everything it knows.
    pub fn state(&self) -> VcsState {
        self.store
            .snapshot()
            .expect("an in-memory store always answers")
    }
}

impl Default for MemoryVcs {
    fn default() -> Self {
        Self::new()
    }
}

impl FileVcs {
    /// A repository provider keeping its state at `path`: whatever is already
    /// there, or nothing.
    ///
    /// Attaching rather than replacing, so a second provider over the same path
    /// picks up what the first one left — which is what a journey driving several
    /// invocations reaches for this flavour to get.
    pub fn create(path: impl Into<PathBuf>) -> Result<Self> {
        Self::over(FileStore::attach(path, &VcsState::default())?)
    }

    /// A repository provider that starts from a scenario, keeping its state at
    /// `path` and replacing whatever was there.
    pub fn seeded(path: impl Into<PathBuf>, state: VcsState) -> Result<Self> {
        Self::over(FileStore::replace(path, &state)?)
    }

    fn over(store: FileStore<VcsState>) -> Result<Self> {
        let root = store
            .path()
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."))
            .join("worktrees");
        Ok(Self {
            store,
            root,
            trees: Trees::Created,
        })
    }

    /// Everything it knows, read back out of its document.
    pub fn state(&self) -> Result<VcsState> {
        self.store.snapshot()
    }
}

impl<T: Store<VcsState>> Vcs for Repository<T> {
    fn resolve_identity(&self, origin_or_path: &str) -> Result<Identity> {
        self.store.with(|state| {
            state::identity_of(state, origin_or_path)
                .cloned()
                .ok_or_else(|| Error::Invalid {
                    reason: format!(
                        "{origin_or_path:?} does not name a repository this provider knows; {}",
                        state::known(state)
                    ),
                })
        })
    }

    fn open_session(&self, req: SessionRequest) -> Result<Session> {
        let root = self.root.clone();
        let (session, emission) = self.store.with(|state| {
            let identity = state::identity_of(state, &req.repo)
                .cloned()
                .ok_or_else(|| Error::Invalid {
                    reason: format!(
                        "{:?} does not name a repository this provider knows; {}",
                        req.repo,
                        state::known(state)
                    ),
                })?;
            // Consecutive and predictable, so a journey can name the session it is
            // about to open — the one thing a digest-shaped token takes away.
            let token = SessionToken(format!("s-testing-{}", state.sessions.len() + 1));
            let run_root = root.join(&token.0);
            // Both names are checked before they are recorded, because both go on to
            // spell a ref for whoever holds the session — and a provider that
            // accepted a name git refuses would let a journey pass where the real
            // run stops.
            let base = req.base.clone().unwrap_or_else(|| DEFAULT_BASE.to_owned());
            state::named_branch(&base, "the base")?;
            for (key, value) in &req.labels {
                state::label_pair(key, value)?;
            }
            // Never a conflict: a provider has no base to merge into a continued
            // branch, so every session it opens opens clean — which is also why its
            // `session-opened` below never carries the `conflict` key the real one
            // writes over a merge it left in progress, and why `refuse_conflicts`
            // has nothing here to refuse.
            let session = Session {
                worktree: run_root.join("worktree"),
                branch: state::requested_branch(&req, &token)?,
                base,
                token: token.clone(),
                conflict: None,
            };
            state.sessions.push(session.clone());
            state
                .session_identities
                .insert(token.clone(), identity.origin.clone());
            if !req.labels.is_empty() {
                state
                    .session_labels
                    .insert(token.clone(), req.labels.clone());
            }
            let emission = Emission {
                stream: token.0.clone(),
                identity: Some(identity.origin.clone()),
                kind: EventKind::SessionOpened,
                result: EmissionResult::Success,
                payload: object(json!({
                    "token": token.0,
                    "identity": identity.origin,
                    "branch": session.branch,
                    "base": session.base,
                    "worktree": session.worktree.display().to_string(),
                    // Synthetic, and named anyway: a consumer reading this event
                    // reads the same keys whichever implementation produced it.
                    "clone": run_root.join("clone").display().to_string(),
                    "execution_checkout": run_root.join("checkout").display().to_string(),
                    "publication_checkout": run_root.join("checkout").display().to_string(),
                    // A run root of its own, which is the one placement a provider
                    // that keeps no pool can make — and the one every real session
                    // gets on a host that configures none.
                    "placement": {"kind": "run-root"},
                })),
            };
            Ok((session, emission))
        })?;
        if self.trees == Trees::Created {
            std::fs::create_dir_all(&session.worktree).map_err(|e| Error::Invalid {
                reason: format!("cannot create {}: {e}", session.worktree.display()),
            })?;
        }
        events::emit(&emission);
        Ok(session)
    }

    fn adopt_session(&self, token: SessionToken) -> Result<Session> {
        self.store.with(|state| {
            state::session_of(state, &token)
                .cloned()
                .ok_or_else(|| Error::Invalid {
                    reason: format!(
                        "no session {:?} is open; `onevcs session open` prints a token",
                        token.0
                    ),
                })
        })
    }

    fn preserve(&self, s: &Session, provenance: Provenance) -> Result<PreservedBranch> {
        let (branch, emission) = self.store.with(|state| {
            let identity = state::identity_for(state, &s.token)?;
            let branch = PreservedBranch {
                branch: s.branch.clone(),
                base: s.base.clone(),
                provenance,
                change_url: None,
                change_base: None,
            };
            let row = Recoverable {
                identity: identity.clone(),
                branch: branch.clone(),
                checkout: s.worktree.clone(),
                tip: None,
                stopped_because: format!("session {} was left open", s.token.0),
                recover_command: recover_command(&s.branch, &s.worktree, provenance),
                // Preserved work this provider was handed is work nobody published:
                // there is no base here whose history could record a landing, and no
                // tree to compare content against, so the one answer it can give is
                // the one it knows.
                landed: Landed::No,
                // Both answered where the row is *read* rather than frozen in here:
                // whether a session still holds its branch is a fact about the session
                // now, and there is no tree here to count a diff's lines against.
                held_by: None,
                net_negative: None,
                // The session that preserved it is the session that answers for it,
                // and what it was opened with is what the row carries.
                session: Some(s.token.clone()),
                labels: state
                    .session_labels
                    .get(&s.token)
                    .cloned()
                    .unwrap_or_default(),
                // A preservation onto an origin is a thing only a real repository can
                // do — there is no git here and no remote to push to — so this provider
                // answers what a scenario wrote down and nothing else. A hand-written
                // state may still seed one, exactly as it seeds a hold.
                on_origin: None,
                // Whether a branch may be retired is decided from every copy of it this
                // host holds, its base on the origin, and this host's records — none of
                // which a provider has — so this provider classifies nothing, and a row
                // it answers carries no classification rather than an invented one.
                retirement: None,
            };
            // Preserving the same branch twice replaces its row rather than listing
            // it twice, which is what `recoverable` does across the checkouts a
            // branch is reachable from.
            state.preserved.retain(|kept| {
                kept.identity != row.identity || kept.branch.branch != row.branch.branch
            });
            state.preserved.push(row);
            let emission = Emission {
                stream: s.token.0.clone(),
                // No identity label, because the real implementation carries none
                // here: the label is stamped where a session is opened, and work is
                // preserved against a stream a later process opened fresh. Claiming
                // it would be drift in the direction that looks like more
                // information.
                identity: None,
                kind: EventKind::CommitPreserved,
                result: EmissionResult::Success,
                payload: object(json!({
                    "branch": s.branch,
                    "sha": events::stable_sha(&[&s.token.0, &s.branch, spell(provenance)]),
                    "provenance": spell(provenance),
                })),
            };
            Ok((branch, emission))
        })?;
        events::emit(&emission);
        Ok(branch)
    }

    fn session(&self, token: &SessionToken) -> Result<SessionRecord> {
        self.store.with(|state| {
            let session = state::session_of(state, token)
                .cloned()
                .ok_or_else(|| unknown_session(token))?;
            let identity = state::identity_for(state, token)?;
            // Read off what was preserved rather than remembered separately: the
            // real implementation reads the branch, so a session whose work was
            // preserved behind an incomplete-step marker answers the same here.
            let provenance = state
                .preserved
                .iter()
                .find(|row| row.identity == identity && row.branch.branch == session.branch)
                .map_or(Provenance::Complete, |row| row.branch.provenance);
            Ok(SessionRecord {
                lifecycle: if state.closed_sessions.contains(token) {
                    Lifecycle::Closed
                } else {
                    Lifecycle::Open
                },
                session,
                identity,
                provenance,
                // A retry link is a fact about run clones under a state root, and
                // this provider keeps none: its sessions are records in a store, so
                // there is no second copy of a branch for one to tell apart.
                retried_by: None,
            })
        })
    }

    fn close_session(&self, token: &SessionToken) -> Result<Session> {
        self.store.with(|state| {
            let session = state::session_of(state, token)
                .cloned()
                .ok_or_else(|| unknown_session(token))?;
            let emission = Emission {
                stream: token.0.clone(),
                // No identity label, because the real implementation carries none
                // here: closing opens the stream fresh, and the label is stamped
                // where a session is opened.
                identity: None,
                kind: EventKind::SessionClosed,
                result: EmissionResult::Success,
                payload: object(json!({"token": token.0, "branch": session.branch})),
            };
            // Match the real provider's observable ordering: a follower reads the
            // stream before consulting this state, so the terminator must exist
            // before `Closed` can be returned to that concurrent reader.
            events::emit(&emission);
            state.closed_sessions.insert(token.clone());
            Ok(session)
        })
    }

    /// Publish a session's branch, as far as a provider honestly can.
    ///
    /// The host side is performed rather than described: a change request is really
    /// opened against the [`Hosting`] this was handed, really adopted when one is
    /// already open, and really merged under the policy — so the six host methods
    /// are exercised and what the host recorded is what a journey reads back.
    ///
    /// The repository side is not, and none of it is claimed. There is no origin to
    /// fetch from, no tree to build in, no push, and no lock to queue behind, so no
    /// `fetch`, `push`, `lock-wait`, `lock-acquired`, or `merge-queued` event is
    /// emitted. What is emitted is what was decided: the change that was opened, and
    /// the merge that landed.
    fn publish(
        &self,
        token: &SessionToken,
        request: &PublishRequest,
        hosting: &dyn Hosting,
    ) -> Result<Publication> {
        let (publication, emissions) = self.store.with(|state| {
            let session = state::session_of(state, token)
                .cloned()
                .ok_or_else(|| unknown_session(token))?;
            let identity = state::identity_for(state, token)?;
            // The publication rule the crate next door states, applied rather than
            // restated: a reason that would not render as itself is refused here
            // exactly where the real implementation refuses it, before any host is
            // asked and before anything is recorded.
            if let Some(reason) = &request.draft {
                reason.checked()?;
            }
            let resolved = state.policy.unwrap_or(DEFAULT_PUBLICATION);
            let policy = match request.policy {
                Some(requested) => resolved.narrow(requested)?,
                None => resolved,
            };
            let published = |outcome, emissions| {
                (
                    Publication {
                        session: token.clone(),
                        branch: session.branch.clone(),
                        policy,
                        outcome,
                    },
                    emissions,
                )
            };
            // A publication that defers its checks asks the host nothing: everything it
            // decides is decided here, from what this provider holds, and it is refused
            // whole — before anything is recorded — exactly where the real one refuses.
            if request.defer_checks || request.adopt.is_some() {
                let approvals = state.approvals.unwrap_or(DEFAULT_APPROVALS);
                let adopt = deferred(
                    state, &session, &identity, request, policy, approvals, token,
                )?;
                let number = adopt
                    .path_segments()
                    .and_then(|mut segments| segments.nth(3))
                    .unwrap_or_default()
                    .to_owned();
                let emission = Emission {
                    stream: token.0.clone(),
                    identity: Some(identity.clone()),
                    kind: EventKind::ChangeOpened,
                    result: EmissionResult::Success,
                    payload: object(json!({
                        "url": adopt.to_string(),
                        "host": "github",
                        "id": number,
                        "base": session.base,
                    })),
                };
                let (publication, emissions) = published(
                    PublishOutcome::ChangeReviewDraftUnchecked(adopt),
                    vec![emission],
                );
                state.publications.push(publication.clone());
                return Ok((publication, emissions));
            }
            // A session that has already landed has nothing the base does not carry,
            // which is what the real implementation reports for the same reason. One
            // whose change request is merely open or queued has *not* landed, and
            // publishing it again adopts that change rather than opening a second —
            // so it falls through to the host, as it does there.
            if state.publications.iter().any(|earlier| {
                earlier.session == *token && matches!(earlier.outcome, PublishOutcome::Merged(_))
            }) {
                let (publication, emissions) =
                    published(PublishOutcome::NothingToPublish, Vec::new());
                state.publications.push(publication.clone());
                return Ok((publication, emissions));
            }

            let (outcome, emissions) = if policy == MergePolicy::LocalDirect {
                // The same refusal the real publication makes at the same boundary: a
                // local-direct publication opens no change request, so there is
                // nothing to draft and the work would land carrying the very pin the
                // draft exists to hold back.
                match &request.draft {
                    Some(reason) => (
                        failed(&Error::Invalid {
                            reason: format!(
                                "{branch:?} was asked to publish as {asked}, and this identity \
                                 publishes with local-direct, which opens no change request at \
                                 all",
                                branch = session.branch,
                                asked = asked_for(reason),
                            ),
                        }),
                        Vec::new(),
                    ),
                    None => record_local_landing(&identity, &session, token),
                }
            } else {
                match slug(&identity) {
                    Some(slug) => {
                        // Recorded as it happens, as next door: a publication that
                        // fails after opening, drafting or lifting keeps that record.
                        let mut emissions = Vec::new();
                        let outcome = match publish_as_change(
                            hosting,
                            &Publishing {
                                slug: &slug,
                                identity: &identity,
                                session: &session,
                                policy,
                                approvals: state.approvals.unwrap_or(DEFAULT_APPROVALS),
                                drafts: state.drafts.unwrap_or_default(),
                                request,
                                token,
                            },
                            &mut emissions,
                        ) {
                            Ok(outcome) => outcome,
                            // Once a publication has started, what stops it is an outcome
                            // rather than a refusal — the same split the real
                            // implementation keeps, so a caller reads one shape.
                            Err(error) => failed(&error),
                        };
                        (outcome, emissions)
                    }
                    None => (refusal(&identity), Vec::new()),
                }
            };
            let (publication, emissions) = published(outcome, emissions);
            state.publications.push(publication.clone());
            Ok((publication, emissions))
        })?;
        for emission in &emissions {
            events::emit(emission);
        }
        Ok(publication)
    }

    /// The same rows [`Vcs::recoverable`] answers with.
    ///
    /// This provider is *handed* its preserved work, and what it is handed is work
    /// nobody published: there is no base here whose history could record a landing
    /// and no tree to compare content against, so it withholds nothing and the wider
    /// question has the same answer as the narrower one.
    fn preserved(&self, scope: Scope) -> Result<Vec<Recoverable>> {
        self.recoverable(scope)
    }

    fn recoverable(&self, scope: Scope) -> Result<Vec<Recoverable>> {
        self.store.with(|state| {
            let wanted = match &scope {
                Scope::All => None,
                Scope::Repo(repo) => Some(
                    state::identity_of(state, repo)
                        .map(|identity| identity.origin.clone())
                        .ok_or_else(|| Error::Invalid {
                            reason: format!(
                                "{repo:?} does not name a repository this provider knows; {}",
                                state::known(state)
                            ),
                        })?,
                ),
            };
            // Newest first, as the real implementation reports them.
            Ok(state
                .preserved
                .iter()
                .rev()
                .filter(|row| wanted.as_ref().is_none_or(|key| *key == row.identity))
                .cloned()
                .map(|row| held(state, row))
                .collect())
        })
    }
}

/// Say which live session still holds a row's branch, when one of this provider's
/// does.
///
/// Read here rather than written when the work was preserved, because closing the
/// session is what ends the hold and a row that had frozen the answer would go on
/// saying somebody is in there. What makes it *live* is the same thing that makes it
/// live for the real implementation in-process: the session is open, and the process
/// that opened it is this one. A row a scenario seeded the answer into keeps it — a
/// hand-written state says what it means to say.
fn held(state: &VcsState, row: Recoverable) -> Recoverable {
    if row.held_by.is_some() {
        return row;
    }
    let holder = state.sessions.iter().find(|session| {
        session.branch == row.branch.branch
            && state.session_identities.get(&session.token) == Some(&row.identity)
            && !state.closed_sessions.contains(&session.token)
    });
    Recoverable {
        held_by: holder.map(|session| HeldBy {
            token: Some(session.token.clone()),
            worktree: session.worktree.clone(),
            holding: Holding::OwnerRunning,
        }),
        ..row
    }
}

/// The refusal a session this provider never opened meets.
fn unknown_session(token: &SessionToken) -> Error {
    Error::Invalid {
        reason: format!(
            "no session {:?} is open; `onevcs session open` prints a token",
            token.0
        ),
    }
}

/// The `owner/name` slug an identity key spells, when it is a GitHub one.
///
/// The host is checked rather than assumed, exactly as the real implementation
/// checks it: a GitLab origin has the same three segments, and a provider that
/// published one anyway would let a journey pass where the real run answers that
/// nobody has implemented that host.
fn slug(identity: &str) -> Option<String> {
    let mut parts = identity.split('/');
    let (host, owner, name) = (parts.next()?, parts.next()?, parts.next()?);
    if parts.next().is_some() || host != DEFAULT_HOST || owner.is_empty() || name.is_empty() {
        return None;
    }
    Some(format!("{owner}/{name}"))
}

/// The draft a deferred publication pushes into, held to what the real implementation
/// holds it to: `adopt` named, no draft reason, a policy that keeps the change request
/// for review, a change request of the session's repository, and this provider's newest
/// record of it — a publication of it, which is the record a repository side keeps here
/// — naming the session's branch. With no record at all the refusal is
/// [`Error::UnrecordedChangeHead`], as there. A standings read's record is the real
/// state root's, which a provider does not read.
fn deferred(
    state: &VcsState,
    session: &Session,
    identity: &str,
    request: &PublishRequest,
    policy: MergePolicy,
    approvals: Approvals,
    token: &SessionToken,
) -> Result<url::Url> {
    let refused = |reason: String| Error::Invalid { reason };
    let adopt = match (request.defer_checks, &request.adopt) {
        (true, Some(adopt)) => adopt,
        (true, None) => {
            return Err(refused(
                "--defer-checks publishes into a draft that is already open: name it with \
                 --adopt <URL>. Nothing was pushed"
                    .to_owned(),
            ))
        }
        (false, _) => {
            return Err(refused(
                "--adopt names the draft a --defer-checks publication pushes into, and this \
                 publication does not defer its checks. Nothing was pushed"
                    .to_owned(),
            ))
        }
    };
    if request.draft.is_some() {
        return Err(refused(
            "--defer-checks pushes into a draft held for review, and a draft reason asks for a \
             different draft. Nothing was pushed"
                .to_owned(),
        ));
    }
    if policy != MergePolicy::ChangeOpen || approvals != Approvals::Required {
        return Err(refused(format!(
            "--defer-checks is for a change request held for review — a change-open identity \
             whose approvals are required — and {identity} does not hold this one for review. \
             Nothing was pushed"
        )));
    }
    // Parsed as a change request's URL — `https://<host>/<owner>/<name>/pull/<number>`
    // with a number of digits — and held to the session's repository, as the real one
    // holds it, rather than matched by its prefix.
    let segments: Vec<&str> = adopt
        .path_segments()
        .map(|segments| segments.collect())
        .unwrap_or_default();
    let named = match segments.as_slice() {
        [owner, name, "pull", number, ..]
            if adopt.scheme() == "https"
                && !number.is_empty()
                && number.chars().all(|c| c.is_ascii_digit()) =>
        {
            adopt
                .host_str()
                .map(|host| format!("{}/{owner}/{name}", host.to_ascii_lowercase()))
        }
        _ => None,
    };
    if named.as_deref() != Some(identity) || slug(identity).is_none() {
        return Err(refused(format!(
            "{adopt} is not a change request of {identity}: a change request is named as \
             https://{DEFAULT_HOST}/<owner>/<name>/pull/<number>. Nothing was pushed"
        )));
    }
    let recorded = state.publications.iter().rev().find_map(|earlier| {
        let carried = match &earlier.outcome {
            PublishOutcome::ChangeOpen(url)
            | PublishOutcome::ChangeDraft(url)
            | PublishOutcome::ChangeReviewDraft(url)
            | PublishOutcome::ChangeReviewDraftUnchecked(url)
            | PublishOutcome::Queued(url) => Some(url),
            _ => None,
        };
        (carried == Some(adopt)).then(|| earlier.branch.clone())
    });
    match recorded {
        Some(branch) if branch == session.branch => Ok(adopt.clone()),
        Some(branch) => Err(refused(format!(
            "{adopt} carries {branch:?} by this provider's newest record of it, and session {} \
             is on {:?}. Nothing was pushed",
            token.0, session.branch
        ))),
        None => Err(Error::UnrecordedChangeHead {
            change: adopt.to_string(),
            reason: format!(
                "this provider holds no record of which branch {adopt} carries, and a \
                 --defer-checks publication asks the host nothing. Nothing was pushed"
            ),
        }),
    }
}

/// Record that a `local-direct` publication landed — record, and nothing more.
///
/// Landing one is entirely repository-side work, a squash built detached and
/// pushed, which this provider does not perform and must not be named as if it
/// did. What it does is decide the outcome and emit the completion that says so.
fn record_local_landing(
    identity: &str,
    session: &Session,
    token: &SessionToken,
) -> (PublishOutcome, Vec<Emission>) {
    let sha = events::stable_sha(&["publish", &token.0, &session.branch]);
    let emission = Emission {
        stream: token.0.clone(),
        identity: Some(identity.to_owned()),
        kind: EventKind::MergeCompleted,
        // Every record of a landing says when the base received it and at which
        // commit, as `onevcs`'s own does: here, the moment this provider decided it.
        result: EmissionResult::Success,
        payload: object(json!({
            "identity": identity,
            "sha": sha,
            "base": session.base,
            "landed_at": events::timestamp(),
            "landing": sha,
        })),
    };
    (PublishOutcome::Merged(Sha(sha)), vec![emission])
}

/// Everything one provider publication knows about itself.
struct Publishing<'a> {
    slug: &'a str,
    identity: &'a str,
    session: &'a Session,
    policy: MergePolicy,
    approvals: Approvals,
    drafts: Drafts,
    request: &'a PublishRequest,
    token: &'a SessionToken,
}

impl Publishing<'_> {
    /// One event on the session's own stream, under this identity.
    fn emission(&self, kind: EventKind, payload: Value) -> Emission {
        Emission {
            stream: self.token.0.clone(),
            identity: Some(self.identity.to_owned()),
            kind,
            result: EmissionResult::Success,
            payload: object(payload),
        }
    }
}

/// Publish as a change request: open the session's change on the host, or adopt
/// the one it already holds, watch its required checks, and then do with it what
/// the policy asks.
///
/// **The draft lifecycle, as next door.** A publication carrying no reason opens its
/// change request as a draft while the checks run — or, adopting a draft, records it
/// as awaiting them rather than lifting it on the spot — and once they are green lifts
/// it before asking for any merge, or keeps it under `change-open` with approvals
/// required. `drafts: {disabled: true}` opens ready and lifts an adopted draft at once.
///
/// **What this provider cannot do is wait.** It has no clock, so each phase of the
/// watch is **one reading** of the host: a reading that has not settled is the bound
/// elapsing (`checks-unsettled`), and a draft on which no required check has run is
/// the grace window elapsing — it is lifted early, and the next reading is the host's
/// answer after the lift, which is where [`HostState::checks_after_lift`](crate::HostState::checks_after_lift)
/// comes in. A consumer drives each row of the lifecycle by seeding the reading it
/// wants rather than by timing one.
fn publish_as_change(
    hosting: &dyn Hosting,
    publishing: &Publishing<'_>,
    emissions: &mut Vec<Emission>,
) -> Result<PublishOutcome> {
    let Publishing {
        slug,
        session,
        policy,
        request,
        ..
    } = *publishing;
    let host = hosting.for_repo(slug)?;
    // Who the host believes is calling travels with the change, as it does in the
    // real publication and for the same reason.
    let author = host.authenticated_user()?;
    let lifecycle = !publishing.drafts.disabled.unwrap_or(false);
    // Checked before anything is opened, as the real publication checks it before
    // anything is pushed.
    if lifecycle {
        grace_seconds()?;
    }
    let existing = host.find_changes(&session.branch, &session.base)?;
    // Whether the host already held it, which is what decides whether there can be a
    // draft to lift — and, as next door, keeps a publication that opens its own change
    // request from asking this host anything extra.
    let adopted = !existing.is_empty();
    let change = match existing.into_iter().next() {
        Some(change) => change,
        None => host.open_change(ChangeSpec {
            head: session.branch.clone(),
            base: session.base.clone(),
            // A requested title has been checked by the conversion that built it, so
            // this provider cannot accept one the real publication would refuse. The
            // real implementation takes the subject from the branch's commits when no
            // title was requested, and a provider has no commits to read — so an
            // unrequested title names the branch instead.
            title: request
                .title
                .as_deref()
                .map_or_else(|| format!("Publish {}", session.branch), str::to_owned),
            // Verbatim, and nothing when there is none — the real publication
            // composes no body either, so a provider that composed one would be a
            // consumer's suite proving a change request nobody opens.
            body: request.body.clone(),
            // The reason travels to the host and no further, as it does there: what
            // the host does with it is open the change as a draft.
            draft: request.draft.clone(),
            draft_awaiting_checks: lifecycle && request.draft.is_none(),
        })?,
    };
    emissions.push(publishing.emission(
        EventKind::ChangeOpened,
        json!({
            "url": change.url.to_string(),
            "host": "github",
            "id": change.id.0,
            "base": change.base,
            "author": author,
        }),
    ));
    if let Some(reason) = &request.draft {
        // The same question the real publication asks, for the same reason: a host
        // that ignored the request, or a change request already open for review,
        // would otherwise be reported as held back while it can land.
        if !host.is_draft(&change)? {
            return Err(Error::Invalid {
                reason: format!(
                    "{url} is open for review on the host, and this publication asked for \
                     {asked}. A change that is open can land, so reporting it as a draft would \
                     say the work is held back when nothing is holding it",
                    url = change.url,
                    asked = asked_for(reason),
                ),
            });
        }
        // The publication record, and the only place the reason is written: the real
        // implementation writes nothing of it into the change request, and a provider
        // that did would be a consumer's suite proving a body nobody renders. The
        // payload is the reason's own serialized form — its `kind` and every field of
        // that kind — under the change request it holds, exactly as next door.
        let mut drafted = object(json!({
            "url": change.url.to_string(),
            "id": change.id.0,
            "base": change.base,
        }));
        if let serde_json::Value::Object(fields) =
            serde_json::to_value(reason).expect("a draft reason serializes")
        {
            drafted.extend(fields);
        }
        emissions.push(publishing.emission(EventKind::ChangeDrafted, Value::Object(drafted)));
        // Under every policy: a draft is unmergeable in that state, so nothing below
        // asks this host to merge it.
        return Ok(PublishOutcome::ChangeDraft(change.url.clone()));
    }
    // Three answers about whether the host holds it as a draft, told apart as next
    // door: a host that was never taught to draft one is holding nothing, and a host
    // that *could not say* is a refusal rather than a change nobody is holding.
    // Asked of a change this publication just opened only under the lifecycle, which
    // asked for a draft: without it, one opened moments ago without a reason is one
    // nobody drafted, and a host written against the earlier surface is asked nothing.
    let is_draft = match if lifecycle || adopted {
        host.is_draft(&change)
    } else {
        Ok(false)
    } {
        Ok(draft) => draft,
        Err(Error::NotImplemented { .. }) => false,
        Err(unreadable) => return Err(unreadable),
    };
    let drafted = if lifecycle {
        if is_draft {
            emissions.push(publishing.emission(
                EventKind::ChangeDrafted,
                json!({
                    "url": change.url.to_string(),
                    "id": change.id.0,
                    "base": change.base,
                    "kind": "awaiting-checks",
                }),
            ));
        }
        is_draft
    } else {
        // Without the lifecycle, publishing without a reason lifts an adopted draft
        // on the spot, as it always did; one opened moments ago is one nobody drafted.
        if adopted && is_draft {
            lift(host.as_ref(), publishing, &change, emissions)?;
        }
        false
    };

    // Every change policy watches — except that `change-auto` on a change nobody
    // drafted arms the host's own merge and leaves the checks to it, as next door.
    // Next door's merge watch still refuses a required check that already concluded
    // red rather than arm a merge over it, so this reading does too, and records the
    // checks settled only where every check the host declares required let it
    // through; one still running, or declared and not started, arms it, and the
    // host's hold is what the outcome reports.
    let still_draft = if drafted || policy != MergePolicy::ChangeAuto {
        match watch(host.as_ref(), publishing, &change, drafted, emissions)? {
            Watched::Draft => true,
            Watched::Ready => false,
            // A merge is armed in place of the elapsed wait's refusal where the policy
            // asks for one and the host allows it, as next door.
            Watched::Elapsed { error, skipped } => {
                return match policy {
                    MergePolicy::ChangeAuto | MergePolicy::ChangeDirect => arm_on_elapse(
                        host.as_ref(),
                        publishing,
                        &change,
                        emissions,
                        error,
                        &skipped,
                    ),
                    MergePolicy::ChangeOpen | MergePolicy::LocalDirect => Err(error),
                };
            }
        }
    } else {
        let answered = host.change_checks(&change)?;
        let checks: Vec<&Check> = answered.checks.iter().collect();
        let declared = given(
            declared_required(host.as_ref(), &change),
            answered.complete(),
            &checks,
        );
        let standing = standings(&checks, &declared);
        if let Some(failed) = red(&checks, &standing) {
            return Err(failed);
        }
        if through(&standing, &declared) {
            record_settled(
                publishing,
                &change,
                emissions,
                skipped(&standing),
                declared.unread(),
            );
        }
        false
    };
    if still_draft {
        if policy == MergePolicy::ChangeOpen && publishing.approvals == Approvals::Required {
            emissions.push(publishing.emission(
                EventKind::DraftKeptForReview,
                json!({
                    "url": change.url.to_string(),
                    "id": change.id.0,
                    "base": change.base,
                }),
            ));
            return Ok(PublishOutcome::ChangeReviewDraft(change.url.clone()));
        }
        // Lifted before any merge is asked for: this host, like GitHub, will neither
        // merge a draft nor arm its own merge on one.
        lift(host.as_ref(), publishing, &change, emissions)?;
    }

    if policy == MergePolicy::ChangeOpen {
        return Ok(PublishOutcome::ChangeOpen(change.url.clone()));
    }
    Ok(match host.merge(&change, policy)? {
        MergeOutcome::Merged(sha) => merged(host.as_ref(), publishing, &change, emissions, &sha),
        MergeOutcome::Queued => PublishOutcome::Queued(change.url.clone()),
        MergeOutcome::Open => PublishOutcome::ChangeOpen(change.url.clone()),
    })
}

/// Record a merge the host performed, and answer it as the publication's outcome.
fn merged(
    host: &dyn RemoteHost,
    publishing: &Publishing<'_>,
    change: &ChangeRequest,
    emissions: &mut Vec<Emission>,
    sha: &Sha,
) -> PublishOutcome {
    // When the host says the base received it, as `onevcs`'s own record of a
    // landing carries it. Where the host cannot say there is no landing commit
    // in this world to read a time from either, so the record says nobody can
    // time it rather than claim the moment this provider saw the merge.
    let landed_at = host
        .merge_time(change)
        .ok()
        .flatten()
        .and_then(|spelled| events::moment(&spelled));
    emissions.push(publishing.emission(
        EventKind::ChangeMerged,
        json!({
            "url": change.url.to_string(),
            "sha": sha.0,
            "landed_at": landed_at,
            "landing": sha.0,
        }),
    ));
    emissions.push(publishing.emission(
        EventKind::MergeCompleted,
        json!({
            "identity": publishing.identity,
            "sha": sha.0,
            "landed_at": landed_at,
            "landing": sha.0,
        }),
    ));
    PublishOutcome::Merged(sha.clone())
}

/// What a `change-auto` or `change-direct` publication does when its watch elapses
/// with no required check red, as next door: ask the host whether it allows
/// auto-merge before changing anything, and where it does, lift the draft awaiting its
/// checks and arm the host's merge, record `merge-armed`, and end `checks-unsettled`
/// carrying the [`ArmedMerge`]. A host that does not allow it — or will not say — is
/// left as the elapsed watch left it, and the refusal says why.
fn arm_on_elapse(
    host: &dyn RemoteHost,
    publishing: &Publishing<'_>,
    change: &ChangeRequest,
    emissions: &mut Vec<Emission>,
    elapsed: Error,
    skipped: &[String],
) -> Result<PublishOutcome> {
    let Error::ChecksUnsettled { reason } = elapsed else {
        return Err(elapsed);
    };
    let unarmed = |why: String| Error::ChecksUnsettled {
        reason: format!(
            "{reason}. {why}, so {url} is left as it was — nothing lifted it or armed its merge",
            url = change.url
        ),
    };
    // A skipped required check is one the host's auto-merge reads as satisfied, so a
    // merge armed over one could land with it never run, as next door refuses to.
    if !skipped.is_empty() {
        return Err(unarmed(format!(
            "Required check {} concluded skipped, which the host's auto-merge would read as \
             passed",
            skipped.join(", ")
        )));
    }
    match host.allows_auto_merge() {
        Ok(true) => {}
        Ok(false) => {
            return Err(unarmed(
                "The repository does not allow auto-merge".to_owned(),
            ))
        }
        Err(unread) => {
            return Err(unarmed(format!(
                "Whether the repository allows auto-merge could not be read ({unread})"
            )))
        }
    }
    let is_draft = match host.is_draft(change) {
        Ok(draft) => draft,
        Err(Error::NotImplemented { .. }) => false,
        Err(unreadable) => return Err(unreadable),
    };
    if is_draft {
        lift(host, publishing, change, emissions)?;
    }
    if let MergeOutcome::Merged(sha) = host.merge(change, MergePolicy::ChangeAuto)? {
        return Ok(merged(host, publishing, change, emissions, &sha));
    }
    emissions.push(publishing.emission(
        EventKind::MergeArmed,
        json!({"url": change.url.to_string(), "head": change.head_sha.0}),
    ));
    Ok(PublishOutcome::Failed {
        kind: FailureKind::ChecksUnsettled,
        reason: format!(
            "{}. Its merge is armed: the host lands {url} once its required checks pass, and \
             publishing the session again watches it",
            Error::ChecksUnsettled { reason },
            url = change.url,
        ),
        retained: None,
        armed: Some(ArmedMerge {
            change: change.url.clone(),
            head: change.head_sha.0.clone(),
        }),
    })
}

/// Take a change out of its draft on the host, and record the lift.
fn lift(
    host: &dyn RemoteHost,
    publishing: &Publishing<'_>,
    change: &ChangeRequest,
    emissions: &mut Vec<Emission>,
) -> Result<()> {
    host.ready_for_review(change)?;
    emissions.push(publishing.emission(
        EventKind::DraftLifted,
        json!({"url": change.url.to_string(), "id": change.id.0}),
    ));
    Ok(())
}

/// Which checks a merge requires, as the host said: nothing, these names, or unknown —
/// with why, which a settlement read off the host's marking says, as next door.
#[derive(Clone, PartialEq, Eq)]
enum Declared {
    Nothing,
    Names(BTreeSet<String>),
    Unknown(String),
}

impl Declared {
    /// Why what is required is read off the host's own per-check marking, where it is.
    fn unread(&self) -> Option<&str> {
        match self {
            Declared::Unknown(because) => Some(because),
            Declared::Nothing | Declared::Names(_) => None,
        }
    }
}

/// What the host declares a merge into the change's base requires, and why it could
/// not be read where it could not — as next door, which reads every phase of a watch
/// against this one answer.
fn declared_required(host: &dyn RemoteHost, change: &ChangeRequest) -> Declared {
    match host.required_checks_on(&change.base) {
        Ok(answer) if answer.checks.is_empty() && answer.complete() => Declared::Nothing,
        Ok(answer) if !answer.checks.is_empty() => Declared::Names(answer.checks),
        Ok(_) => Declared::Unknown(format!(
            "the host answered only in part about which checks a merge into {} requires",
            change.base
        )),
        Err(refused) => Declared::Unknown(format!(
            "the host would not say which checks a merge into {} requires: {refused}",
            change.base
        )),
    }
}

/// The declaration, sharpened by one reading as next door sharpens it: where the host
/// would not say what it requires, a complete rollup reporting checks none of which is
/// required is its answer that nothing is.
fn given(declared: Declared, complete: bool, checks: &[&Check]) -> Declared {
    if matches!(declared, Declared::Unknown(_))
        && complete
        && !checks.is_empty()
        && checks.iter().all(|check| !check.required)
    {
        return Declared::Nothing;
    }
    declared
}

/// Each required check's name and the state its entries add up to — `None` where the
/// host reported none — ranked as next door: red, then running, then passed, then no
/// verdict, then skipped.
fn standings(checks: &[&Check], declared: &Declared) -> Vec<(String, Option<CheckState>)> {
    let names: BTreeSet<String> = match declared {
        Declared::Names(names) => names.clone(),
        Declared::Nothing => BTreeSet::new(),
        Declared::Unknown(_) => checks
            .iter()
            .filter(|check| check.required)
            .map(|check| check.name.clone())
            .collect(),
    };
    let rank = |state: CheckState| match state {
        CheckState::Failed => 0,
        CheckState::Pending => 1,
        CheckState::Passed => 2,
        CheckState::NoVerdict => 3,
        CheckState::Skipped => 4,
    };
    names
        .into_iter()
        .map(|name| {
            let state = checks
                .iter()
                .filter(|check| check.name == name)
                .map(|check| check.state())
                .min_by_key(|state| rank(*state));
            (name, state)
        })
        .collect()
}

/// The refusal for the first required check that concluded red.
fn red(checks: &[&Check], standing: &[(String, Option<CheckState>)]) -> Option<Error> {
    let (name, _) = standing
        .iter()
        .find(|(_, state)| *state == Some(CheckState::Failed))?;
    let check = checks
        .iter()
        .find(|check| &check.name == name && check.state() == CheckState::Failed)?;
    Some(Error::ChecksFailed {
        reason: format!(
            "required check {:?} concluded {}.",
            check.name,
            check
                .conclusion
                .as_deref()
                .unwrap_or("without a conclusion")
        ),
    })
}

/// Whether every required check lets the change through — passed, or skipped — over
/// a set that is empty only where the host answered, completely, that nothing is
/// required. A declared check with no run holds it, as next door.
fn through(standing: &[(String, Option<CheckState>)], declared: &Declared) -> bool {
    (*declared == Declared::Nothing || !standing.is_empty())
        && standing
            .iter()
            .all(|(_, state)| matches!(state, Some(CheckState::Passed | CheckState::Skipped)))
}

/// What a reading that has not settled names, in the words next door's bound names it
/// in: each required check still running or with no run yet, then the ones that ended
/// with no verdict or were skipped, and only then that every one settled or that the
/// host declared none — and, where the declaration could not be read, that too.
fn unsettled_named(
    checks: &[&Check],
    standing: &[(String, Option<CheckState>)],
    declared: &Declared,
) -> String {
    let pending: Vec<String> = standing
        .iter()
        .filter_map(|(name, state)| match state {
            Some(CheckState::Pending) => Some(format!("{name:?}")),
            None => Some(format!("{name:?} (no run yet)")),
            _ => None,
        })
        .collect();
    let no_verdict: Vec<String> = standing
        .iter()
        .filter(|(_, state)| *state == Some(CheckState::NoVerdict))
        .map(|(name, _)| {
            let conclusion = checks
                .iter()
                .find(|check| &check.name == name && check.state() == CheckState::NoVerdict)
                .and_then(|check| check.conclusion.as_deref())
                .unwrap_or("unknown");
            format!("{name:?}: {conclusion}")
        })
        .collect();
    let skipped: Vec<String> = skipped(standing)
        .iter()
        .map(|name| format!("{name:?}"))
        .collect();
    let named = if !pending.is_empty() {
        let verdicts = if no_verdict.is_empty() {
            String::new()
        } else {
            format!("; completed with no verdict: {}", no_verdict.join(", "))
        };
        format!("still unsettled: {}{verdicts}", pending.join(", "))
    } else if !no_verdict.is_empty() {
        format!("completed with no verdict: {}", no_verdict.join(", "))
    } else if !skipped.is_empty() {
        format!(
            "skipped on the draft, so not run on it: {}",
            skipped.join(", ")
        )
    } else if standing.is_empty() {
        match declared {
            Declared::Nothing => "the host declared no required check on it at all".to_owned(),
            _ => "it has marked no check required on it".to_owned(),
        }
    } else {
        "every required check it declared had settled".to_owned()
    };
    let read_from = declared
        .unread()
        .map(|because| {
            format!(
                ". Which checks it requires could not be read, so they were read from the \
                 checks it marked required: {because}"
            )
        })
        .unwrap_or_default();
    format!("{named}{read_from}")
}

/// The skipped required checks, by name.
fn skipped(standing: &[(String, Option<CheckState>)]) -> Vec<String> {
    standing
        .iter()
        .filter(|(_, state)| *state == Some(CheckState::Skipped))
        .map(|(name, _)| name.clone())
        .collect()
}

/// Record that the required checks stopped blocking — `passed`, or
/// `passed-with-skipped` naming the skipped ones.
///
/// `unread`: the requirement was read from the host's own per-check marking because
/// its declaration could not be read, which the record says, as next door.
fn record_settled(
    publishing: &Publishing<'_>,
    change: &ChangeRequest,
    emissions: &mut Vec<Emission>,
    skipped: Vec<String>,
    unread: Option<&str>,
) {
    let verdict = if skipped.is_empty() {
        "passed"
    } else {
        "passed-with-skipped"
    };
    let mut payload = json!({
        "url": change.url.to_string(),
        "id": change.id.0,
        "head": change.head_sha.0,
        "verdict": verdict,
        "skipped": skipped,
    });
    if let Some(because) = unread {
        eprintln!(
            "onevcs: warning: the required checks on {} were read from the host's own \
             per-check marking, because the declaration could not be read: {because}",
            change.url
        );
        payload["requirement"] = json!({"read_from": "host-marking", "because": because});
    }
    let mut settled = publishing.emission(EventKind::ChecksSettled, payload);
    settled.result = if verdict == "passed" {
        EmissionResult::Passed
    } else {
        EmissionResult::PassedWithSkipped
    };
    emissions.push(settled);
}

/// The watch, one reading per phase. See [`publish_as_change`] for what a reading
/// stands for.
fn watch(
    host: &dyn RemoteHost,
    publishing: &Publishing<'_>,
    change: &ChangeRequest,
    drafted: bool,
    emissions: &mut Vec<Emission>,
) -> Result<Watched> {
    let settled = |emissions: &mut Vec<Emission>, skipped: Vec<String>, unread: Option<&str>| {
        record_settled(publishing, change, emissions, skipped, unread);
    };
    let elapsed_naming = |checks: &[&Check],
                          standing: &[(String, Option<CheckState>)],
                          declared: &Declared,
                          skipped: Vec<String>| Watched::Elapsed {
        error: Error::ChecksUnsettled {
            reason: format!(
                "the host had not settled its required checks on {}; {}",
                change.url,
                unsettled_named(checks, standing, declared)
            ),
        },
        skipped,
    };
    let unsettled =
        |checks: &[&Check], standing: &[(String, Option<CheckState>)], declared: &Declared| {
            elapsed_naming(checks, standing, declared, skipped(standing))
        };
    let answered = host.change_checks(change)?;
    let complete = answered.complete();
    let checks: Vec<&Check> = answered.checks.iter().collect();
    // What the host declares it requires, read once and sharpened by this reading.
    let declared = given(declared_required(host, change), complete, &checks);
    let unread = declared.unread();

    if !drafted {
        let standing = standings(&checks, &declared);
        if let Some(failed) = red(&checks, &standing) {
            return Err(failed);
        }
        if !through(&standing, &declared) {
            return Ok(unsettled(&checks, &standing, &declared));
        }
        settled(emissions, skipped(&standing), unread);
        return Ok(Watched::Ready);
    }

    // The draft: a skipped required check has not run.
    if matches!(declared, Declared::Nothing) {
        settled(emissions, Vec::new(), None);
        return Ok(Watched::Draft);
    }
    let standing = standings(&checks, &declared);
    if let Some(failed) = red(&checks, &standing) {
        return Err(failed);
    }
    if !standing.is_empty()
        && standing
            .iter()
            .all(|(_, state)| *state == Some(CheckState::Passed))
    {
        settled(emissions, Vec::new(), unread);
        return Ok(Watched::Draft);
    }
    let not_run: Vec<String> = standing
        .iter()
        .filter(|(_, state)| matches!(state, None | Some(CheckState::Skipped)))
        .map(|(name, _)| name.clone())
        .collect();
    let running = standing
        .iter()
        .any(|(_, state)| matches!(state, Some(CheckState::Pending | CheckState::NoVerdict)));
    let unseen = matches!(declared, Declared::Unknown(_)) && standing.is_empty();
    // The grace window, elapsed: where the host would not say what it requires and
    // checks ran on the draft with none skipped, its own marking is the answer.
    if unseen
        && !checks.is_empty()
        && checks
            .iter()
            .all(|check| check.state() != CheckState::Skipped)
    {
        settled(emissions, Vec::new(), unread);
        return Ok(Watched::Draft);
    }
    if running || (not_run.is_empty() && !unseen) || still_running(host, change, &checks) {
        return Ok(unsettled(&checks, &standing, &declared));
    }

    // The grace window elapsed with nothing required run: lift early, say so, and read
    // the host again as a ready change whose checks must run after the lift.
    let snapshot: Vec<Check> = answered.checks.clone();
    lift(host, publishing, change, emissions)?;
    let warned = publishing.drafts.warn_on_early_lift.unwrap_or(true);
    let grace = grace_seconds()?;
    if warned {
        eprintln!(
            "onevcs: warning: {} was lifted out of its draft before its required checks ran on \
             it ({}): none had run within {grace}s and nothing on its head was still running, \
             which is what a workflow that skips drafts looks like. {DRAFT_CI}",
            change.url,
            not_run.join(", ")
        );
    }
    emissions.push(publishing.emission(
        EventKind::DraftLiftedEarly,
        json!({
            "url": change.url.to_string(),
            "id": change.id.0,
            "base": change.base,
            "awaited": not_run,
            "grace_seconds": grace,
            "warned": warned,
        }),
    ));
    let after = host.change_checks(change)?.checks;
    let from_the_draft = |check: &Check| !ran_after_the_lift(check, &snapshot);
    let counted: Vec<&Check> = after
        .iter()
        .filter(|check| !(from_the_draft(check) && check.state() == CheckState::Skipped))
        .collect();
    let standing = standings(&counted, &declared);
    if let Some(failed) = red(&counted, &standing) {
        return Err(failed);
    }
    let rerun = after.iter().any(|check| {
        !from_the_draft(check)
            && (standing.is_empty() || standing.iter().any(|(name, _)| *name == check.name))
    });
    // A watch that elapses after the lift names a required check standing on nothing
    // but a draft-era skip as skipped, as next door's does: the host's auto-merge would
    // read it as satisfied, so the change is left unarmed rather than merging on it.
    let reported: Vec<&Check> = after.iter().collect();
    let elapsed = || {
        let mut named = skipped(&standing);
        for name in skipped(&standings(&reported, &declared)) {
            if !named.contains(&name) {
                named.push(name);
            }
        }
        elapsed_naming(&counted, &standing, &declared, named)
    };
    if !rerun {
        // The draft's own workflow still going will attach the check it has not created
        // yet, so that is a watch still waiting rather than one that ended.
        if still_running(host, change, &reported) {
            return Ok(elapsed());
        }
        return Err(Error::ChecksUnsettled {
            reason: format!(
                "the required checks on {} did not re-run after its draft was lifted: no run \
                 the host attached after the lift appeared and nothing on its head is still \
                 running, while the runs from while it was a draft were skipped or never \
                 started, which is not a verdict. {DRAFT_CI}",
                change.url
            ),
        });
    }
    // The after-lift rule is next door's: a run attached since the lift, and every
    // required check it stands for passed or skipped.
    if !standing
        .iter()
        .all(|(_, state)| matches!(state, Some(CheckState::Passed | CheckState::Skipped)))
    {
        return Ok(elapsed());
    }
    settled(emissions, skipped(&standing), unread);
    Ok(Watched::Ready)
}

/// What to do about CI that does not run a draft's required checks, in the words the
/// crate next door says it in.
const DRAFT_CI: &str = "Run the required checks on drafts: their results attach to the head \
     commit, so the change is then kept a draft until they are green, and a workflow that runs \
     on drafts needs no `ready_for_review` trigger. Only a workflow that skips its required \
     jobs on drafts needs `ready_for_review` to run them after a lift, at the cost of one more \
     run per lift";

/// Whether anything on the change's head is still running, by the two readings next
/// door's watch holds both of a draft's "nothing is coming" decisions to: a check the
/// host reports that has not completed, and then — only where none has — the host's
/// own answer about its head. A refusal, or an answer about another commit, is no
/// answer.
fn still_running(host: &dyn RemoteHost, change: &ChangeRequest, checks: &[&Check]) -> bool {
    checks.iter().any(|check| !check.settled())
        || host
            .head_activity(change)
            .is_ok_and(|answer| answer.head == change.head_sha && !answer.in_progress.is_empty())
}

/// Where one watch ended.
enum Watched {
    /// Green on a draft still standing, for the caller to lift or keep.
    Draft,
    /// Green on a ready change.
    Ready,
    /// The reading had not settled, which is the bound elapsing here; the error is the
    /// `checks-unsettled` it ends as unless the merge is armed instead.
    Elapsed {
        /// The `checks-unsettled` the bound ends as.
        error: Error,
        /// The required checks that had concluded skipped when the bound elapsed,
        /// which keep its merge from being armed.
        skipped: Vec<String>,
    },
}

/// Whether `check` is a run the host attached after the lift rather than the draft's
/// run of it in `snapshot`, decided as the real publication decides it: by the run's
/// own identity, never by its conclusion or its status. A check the draft never
/// reported is new, and one it did report is new only where it reports a `started_at`
/// no draft-era run of that check reported, running or settled — so a consumer seeds a
/// re-run by giving it a start of its own.
fn ran_after_the_lift(check: &Check, snapshot: &[Check]) -> bool {
    let earlier: Vec<&Check> = snapshot
        .iter()
        .filter(|seen| seen.name == check.name)
        .collect();
    if earlier.is_empty() {
        return true;
    }
    check.started_at.as_ref().is_some_and(|started| {
        earlier
            .iter()
            .all(|seen| seen.started_at.as_ref() != Some(started))
    })
}

/// The default grace window of the real publication, which is `onevcs`'s own and
/// private to it. A copy, so it is gated: `lifecycle.rs`'s
/// `the_grace_window_an_early_lift_records_is_the_one_onevcs_defaults_to` reads the
/// constant out of `onevcs`'s source and holds this to it.
const DEFAULT_DRAFT_GRACE_SECONDS: f64 = 120.0;

/// The knob a real publication waits its grace window by.
const DRAFT_GRACE_ENV: &str = "ONEVCS_DRAFT_CHECKS_GRACE_SECONDS";

/// The grace window a real publication would have waited out, as the operator set it
/// or the default — recorded on `draft-lifted-early` so the payload reads as the real
/// one does, though nothing here waits.
///
/// Validated as the real publication validates it, and refused by name where it is
/// not a finite number of seconds above zero: a provider that quietly took the default
/// would let a consumer's suite pass on a setting the real one refuses.
fn grace_seconds() -> Result<f64> {
    let Some(raw) = std::env::var_os(DRAFT_GRACE_ENV) else {
        return Ok(DEFAULT_DRAFT_GRACE_SECONDS);
    };
    let raw = raw.to_string_lossy().into_owned();
    let seconds: f64 = raw.trim().parse().map_err(|_| Error::Invalid {
        reason: format!("{DRAFT_GRACE_ENV} must be a number of seconds, not {raw:?}"),
    })?;
    if !seconds.is_finite() || seconds <= 0.0 {
        return Err(Error::Invalid {
            reason: format!(
                "{DRAFT_GRACE_ENV} must be a finite number of seconds above zero, not {raw:?}"
            ),
        });
    }
    Ok(seconds)
}

/// The draft a publication asked for, as the two refusals next door spell it: "a
/// draft awaiting <repository> <target>", or "a draft held by the session that opened
/// it (<why>)". A restatement, so the refusals here read as the real ones do.
fn asked_for(reason: &DraftReason) -> String {
    match reason {
        DraftReason::AwaitingRelease {
            awaiting, target, ..
        } => format!("a draft awaiting {awaiting} {target}"),
        DraftReason::Held { because } => {
            format!("a draft held by the session that opened it ({because})")
        }
    }
}

/// What a publication answers for an identity no change request can be opened
/// against.
///
/// Two failures rather than one, as the real implementation keeps them: an
/// identity that is not hosted at all is asking for the wrong policy, while a
/// hosted one on a host this build does not speak for is asking for an
/// implementation that has not arrived.
fn refusal(identity: &str) -> PublishOutcome {
    failed(&if identity.split('/').count() == 3 {
        Error::NotImplemented {
            operation: "RemoteHost for a host other than github.com",
        }
    } else {
        Error::Invalid {
            reason: format!(
                "identity {identity:?} is not a hosted repository, so it cannot publish a \
                 change request; a local identity publishes with local-direct"
            ),
        }
    })
}

/// One failure, as the outcome a publication that started and did not land is.
fn failed(error: &Error) -> PublishOutcome {
    PublishOutcome::Failed {
        // Through the crate's own mapping, so the kind a caller branches on is the
        // one the real implementation would report for the same failure.
        kind: FailureKind::of(error),
        reason: error.to_string(),
        // A provider has no execution checkout, so there is nowhere a branch could
        // have been handed back to and nothing to report about one.
        retained: None,
        armed: None,
    }
}

/// The argv that lands a preserved branch, as `recoverable` reports it.
///
/// Both verbs take the branch by name and the repository by path, the way the real
/// implementation reports them: the provenance decides which one, and neither
/// depends on the directory a reader happens to be standing in.
// llmlint: ignore[names_match_behavior] named for the public
// `Recoverable::recover_command` field it fills, which `onevcs` publishes and this
// crate must answer identically; a provider whose helper were named otherwise would
// read as filling something else.
fn recover_command(branch: &str, checkout: &Path, provenance: Provenance) -> Vec<String> {
    let verb = match provenance {
        Provenance::IncompleteStep => "recover",
        Provenance::Complete => "publish-branch",
    };
    vec![
        "onevcs".to_owned(),
        verb.to_owned(),
        branch.to_owned(),
        "--repo".to_owned(),
        checkout.display().to_string(),
    ]
}

/// How a provenance kind is spelled in an event payload.
fn spell(provenance: Provenance) -> &'static str {
    match provenance {
        Provenance::Complete => "complete",
        Provenance::IncompleteStep => "incomplete-step",
    }
}

fn object(value: Value) -> Map<String, Value> {
    value.as_object().cloned().unwrap_or_default()
}