onepipeline 0.22.2

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

use std::collections::{BTreeMap, BTreeSet};
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};

use onevcs::SessionRequest;

use crate::controls::NodeControls;
use crate::engine::{self, Message, Settlement};
use crate::event::{Envelope, Labels};
use crate::executor::{DispatchRequest, Executor, WorkspaceSpec};
use crate::filter::EventFilter;
use crate::graph::NodeStatus;
use crate::ledger::RunPaths;
use crate::plan::{Node, NodeKind, Step};

/// The persona that drafts a change request's body.
pub const PR_AUTHOR_PERSONA: &str = "pr-author";

// llmlint: ignore-block[invalid_states_unrepresentable] the graph references below are the
// same validated, launch-recorded strings the engine carries — the launch record's own
// fields, read off it strictly and passed straight back into oneagentgraph's transparent
// ConfigRef. Another newtype would duplicate that sibling type and widen this
// path-resolution change across unrelated composition.
/// What this run's launch decides about a lifecycle node's dispatches.
///
/// One value rather than three parameters, and it is the launch record's own
/// three: every one of them is read off the record the loop read **strictly** at
/// the start of the pass, so a dispatch cannot pick up a config this build could
/// not honour by re-reading `launch.json` leniently where nothing can refuse it.
#[derive(Debug, Clone, Default)]
pub struct Launch {
    /// The default node-scope agent-graph config every dispatch launches, unless
    /// the node or the step names one of its own.
    pub node_graph: String,
    /// The agent graph a change request's body is drafted by, when the launch
    /// named one. `None` is the shipped default: this crate ships the flag, not
    /// the document, and a launch that names no graph drafts nothing.
    pub pr_author_graph: Option<String>,
    /// What every followed `onevcs` session's stream is read through.
    pub vcs_filter: Option<EventFilter>,
}

/// Run one lifecycle node to settlement, re-dispatching it while its
/// publication fails in a way that leaves the work behind.
///
/// A publication that ends `checks-failed`, `checks-unsettled`, `push-rejected`,
/// `pushed-unverified`, or `sync-conflict` did not reject the node — it rejected
/// the **tree** the node produced, and that tree is still on the branch the
/// session handed back (`pushed-unverified` more than the rest: that one is
/// already on the origin, and what a further attempt re-reads is the merge path
/// rather than the push). There
/// is nothing left in the run that would ever look at it again: the node settles
/// `failed`, its dependents never start, and an operator hand-builds a
/// replacement node out of the settlement's detail. So the node is asked again
/// instead, on that same branch, with the diagnosis in its hands.
///
/// Bounded, because a check that will never pass would otherwise be answered by
/// an unbounded series of dispatches, each of them producing the same tree and
/// paying for the same refusal. The node that spends the budget settles `failed`
/// saying how many attempts were made and what each one ended with, which is what
/// tells a reader the difference between a failure and a loop.
#[allow(
    clippy::too_many_arguments,
    reason = "one node's whole execution: the executor, the run, the launch, the node, \
              its cross-repository references, its cancellation, and where to report"
)]
pub fn execute(
    executor: &dyn Executor,
    paths: &RunPaths,
    launch: &Launch,
    node: &Node,
    references: &[crate::plan::CrossRepoReference],
    cancel: &crate::executor::CancellationToken,
    tx: &Sender<Message>,
) -> Settlement {
    let attempts = engine::publication_attempts();
    // What each attempt's publication ended with, in order, for the settlement
    // that stops the loop. One word per attempt: the last attempt's own reason
    // leads the detail as it always has, and a detail carrying three sibling
    // diagnostics in full would carry none of them — every payload text this
    // crate writes is bounded.
    let mut endings: Vec<crate::vcs::Preserving> = Vec::new();
    let mut node = std::borrow::Cow::Borrowed(node);
    let mut attempt = std::num::NonZeroU32::MIN;
    loop {
        let preserved = match attempt_once(executor, paths, launch, &node, references, cancel, tx) {
            Attempt::Settled(settlement) => return *settlement,
            Attempt::Preserving(preserved) => preserved,
        };
        endings.push(preserved.outcome);
        // Two reasons to stop, and one settlement for both: the budget is spent,
        // or the run is being stopped. A cancelled run must not be given another
        // dispatch — the teardown is on its way to reap it, and the node would
        // then settle as the cancellation rather than as the publication failure
        // that is the useful half of what happened.
        if attempt >= attempts || cancel.is_cancelled() {
            return stopped_retrying(&node.id, &preserved, &endings);
        }
        attempt = attempt.saturating_add(1);
        // Another `node-dispatched` rather than a kind of its own, so a reader
        // counting dispatches sees the retry without a second word to learn.
        let _ = tx.send(Message::Redispatched(Box::new(engine::Redispatch {
            node: node.id.clone(),
            attempt,
            attempts,
            reason: format!("{}: {}", preserved.outcome.outcome(), preserved.reason),
        })));
        node = std::borrow::Cow::Owned(continued(&node, &preserved, attempt, attempts, &endings));
    }
}

#[allow(
    clippy::too_many_arguments,
    reason = "one attempt's whole context, which is `execute`'s own — see the reason there"
)]
fn attempt_once(
    executor: &dyn Executor,
    paths: &RunPaths,
    launch: &Launch,
    node: &Node,
    references: &[crate::plan::CrossRepoReference],
    cancel: &crate::executor::CancellationToken,
    tx: &Sender<Message>,
) -> Attempt {
    let run = paths.run.as_str();
    let vcs_filter = launch.vcs_filter.as_ref();
    let Some(request) = crate::vcs::request_for(node) else {
        return Attempt::settled(Settlement {
            detail: Some("a lifecycle node needs a repo".into()),
            ..Settlement::plain(&node.id, NodeStatus::Failed, Some(engine::INVALID_NODE))
        });
    };

    // A node that declared no steps has one dispatch and no step, so nothing
    // stamps a `step` label the plan never wrote.
    let declared_steps = node.steps.is_some();
    // Every step's controls are narrowed here, before a session exists: a
    // workstream that cannot dispatch one of its steps must not first cut a
    // branch and run the steps before it, because that leaves work on a branch
    // for a node that was never going to finish.
    // llmlint: ignore-block[changed_behavior_has_e2e] what this arm newly carries — a
    // step whose declaration no dispatch can run under — is refused by `graph::validate`
    // at `start` and at every live edit, so only a graph
    // folded from a journal an *earlier build* wrote reaches it. Reaching that end to
    // end means writing that journal by hand, which proves the fixture rather than the
    // code, and deleting the arm would reinstate the silent default this control exists
    // to remove. Held instead by the unit test below, which drives the real
    // `LocalExecutor`; the step cycle this arm already reported keeps its own journey.
    let steps = match dispatchable_steps(node) {
        Ok(steps) => steps,
        Err(reason) => {
            return Attempt::settled(Settlement {
                detail: Some(reason),
                ..Settlement::plain(&node.id, NodeStatus::Failed, Some(engine::INVALID_NODE))
            })
        }
    }; // llmlint: ignore-end[changed_behavior_has_e2e]

    let mut session: Option<onevcs::SessionToken> = None;
    // The session's own stream, followed from the moment there is a token to
    // follow, so the publication that comes after the steps is visible while it
    // runs rather than only once it is over.
    let mut stream: Option<crate::vcs::Follower> = None;
    // The one worktree this node's dispatches work in, once its session has
    // opened one. See where it is read: every dispatch after the first runs
    // *there* rather than opening a session beside it.
    let mut worktree: Option<std::path::PathBuf> = None;
    // And what a publication of that session measures its branch against, taken
    // from the same read: asking again at publication would ask the sibling a
    // question it has already answered, on a path where the answer cannot have
    // changed and a failure could not happen — a publication that succeeded is a
    // record that was readable.
    let mut base: Option<String> = None;
    // Where in the run the session's own envelopes belong. The node, not a
    // step: a session outlives every step that wrote in it, and the publication
    // that follows them belongs to none.
    let whose = engine::dispatch_labels(run, &node.id, None, node.persona.as_deref());
    let mut branch: Option<String> = node.branch.clone();
    // The steps the preserved branch already carries, plus the ones this attempt
    // adds. Carried forward whole, because the branch a later attempt preserves
    // is the same branch: a step skipped on one attempt is still on it.
    let mut completed: Vec<String> = node
        .resume
        .as_ref()
        .map(|resume| resume.completed_steps.clone())
        .unwrap_or_default();

    for (step, controls) in &steps {
        if declared_steps && completed.iter().any(|id| id == &step.id) {
            // Already on the preserved branch. Re-running it would redo work the
            // branch carries, which for a step that opened a change is not
            // idempotent.
            continue;
        }
        if step.kind == NodeKind::Human {
            // A ready human step needs a person, and the workstream holds its
            // branch until one acts. The harness never infers that it happened.
            // The session stays open for them and the follow does not: dropping
            // it here ends a process that would otherwise read a stream nobody
            // is waiting for, for as long as the driver lives.
            //
            // Read against its criteria here, because this is where the node
            // settles and the person about to act is the reader a finding is
            // for: a branch that contradicts the bar is worth knowing *before*
            // an approval, not after. And it is the only place: the attempt that
            // follows an attestation dispatches nothing where the human step was
            // last, so it opens no session and has no branch in hand to read.
            check_criteria(node, worktree.as_deref(), tx);
            return Attempt::settled(Settlement {
                branch,
                completed_steps: completed,
                ..Settlement::plain(&node.id, NodeStatus::Waiting, None)
            });
        }
        if step.expects_no_diff {
            continue;
        }
        // Every step after the first names the branch the first opened, which
        // is what makes them one workstream rather than several beside it.
        let request = SessionRequest {
            branch: branch.clone().or_else(|| request.branch.clone()),
            ..request.clone()
        };
        // And works in the worktree the first step's session opened, rather than
        // asking for a session of its own. `onevcs` cuts every session its own
        // clone from the execution checkout, so a second session on the same
        // branch starts from the base with none of the earlier steps' work — and
        // opening it reclaims the first session's workspace, uncommitted work
        // and all. Steps are serial by construction, so one worktree is what
        // "several steps share one branch" has always meant.
        let workspace = match &worktree {
            Some(dir) => WorkspaceSpec::Path(dir.clone()),
            None => WorkspaceSpec::VcsSession(request.clone()),
        };
        let graph = engine::node_graph(
            step.agent_graph.as_ref().or(node.agent_graph.as_ref()),
            &launch.node_graph,
        );
        let build = || DispatchRequest {
            graph: graph.clone(),
            task: step.rendered_task_for(node, references),
            labels: engine::dispatch_labels(
                run,
                &node.id,
                declared_steps.then_some(step.id.as_str()),
                step.persona.as_deref(),
            ),
            controls: *controls,
            workspace: workspace.clone(),
            cancel: cancel.clone(),
        };
        let drained = engine::attempt(executor, &node.id, cancel, tx, &build);
        // The session the dispatch opened is what publication needs, whether or
        // not the step succeeded: a cancelled step's commits are preserved on
        // the branch it left behind.
        session = drained.session.or(session);
        branch = drained.branch.or(branch);
        if stream.is_none() {
            if let Some(token) = &session {
                let opened = crate::vcs::working_session(token);
                worktree = opened.as_ref().map(|open| open.worktree.clone());
                base = opened.map(|open| open.base);
                stream = crate::vcs::follow(token, vcs_filter, relay_into(tx, whose.clone()));
            }
        }
        if drained.settlement.status != NodeStatus::Done {
            // The node is settling on this, so the branch it settles on is read
            // against its own criteria before the session that holds it goes.
            check_criteria(node, worktree.as_deref(), tx);
            end_session(stream, tx, session.as_ref(), &whose, vcs_filter);
            return Attempt::settled(Settlement {
                branch,
                completed_steps: completed,
                ..drained.settlement
            });
        }
        if declared_steps {
            completed.push(step.id.clone());
        }
    }

    let Some(token) = session else {
        // Every step declared no diff, so there is nothing to publish and the
        // node settles on the existing no-changes outcome.
        return Attempt::settled(Settlement {
            branch,
            ..Settlement::plain(&node.id, NodeStatus::Done, Some(engine::NO_CHANGES))
        });
    };

    let attempted = publish(
        executor,
        paths,
        launch,
        node,
        references,
        worktree.as_deref(),
        base.as_deref(),
        cancel,
        tx,
        &token,
        branch,
    );
    // Only where this attempt is the node's answer. A publication that failed
    // leaving the work on its branch is asked again, and reporting a criterion
    // against every attempt of a node that is still being re-dispatched would
    // put three findings on the queue for one branch nobody has settled on yet.
    if matches!(attempted, Attempt::Settled(_)) {
        check_criteria(node, worktree.as_deref(), tx);
    }
    end_session(stream, tx, Some(&token), &whose, vcs_filter);
    attempted
}

/// Hand [`crate::criteria`]'s reading of this node's branch to the loop.
///
/// **When**, which is all this call site decides. Every caller is a settlement
/// `attempt_once` has already made, so nothing here can change one; and it is
/// once per settlement rather than once per node, which differ only for a
/// workstream held at a human step and dispatched again afterwards — two
/// settlements, and not the same branch between them.
///
/// No worktree is no branch to read: every step declared no diff, the session
/// never opened, or the remaining steps were all done on a previous attempt.
/// Silence rather than an unread answer — nothing was named that could not be
/// read.
fn check_criteria(node: &Node, worktree: Option<&std::path::Path>, tx: &Sender<Message>) {
    // Both halves of "there is something to read, on behalf of somebody": a
    // branch in hand, and a node the graph carries to report it against.
    let (Some(worktree), Some(whose)) = (worktree, crate::graph::NodeRef::of(node)) else {
        return;
    };
    for check in crate::criteria::checkable_of(node) {
        let answer = crate::criteria::answer(worktree, &check);
        let _ = tx.send(Message::CriterionChecked(Box::new(
            engine::CriterionChecked {
                node: whose.clone(),
                check,
                answer,
            },
        )));
    }
}

/// Draft the change request's body, then publish through `onevcs`.
#[allow(
    clippy::too_many_arguments,
    reason = "publication needs the dispatch context (executor, the run's paths, what its \
              launch decided, the node, cancellation, and the event stream) as well as what \
              the steps left behind (the session token, its branch, and the worktree and base \
              its record named); the first six are the node's own dispatch identity and \
              bundling them would only move the same list one indirection away"
)]
fn publish(
    executor: &dyn Executor,
    paths: &RunPaths,
    launch: &Launch,
    node: &Node,
    references: &[crate::plan::CrossRepoReference],
    worktree: Option<&std::path::Path>,
    base: Option<&str>,
    cancel: &crate::executor::CancellationToken,
    tx: &Sender<Message>,
    token: &onevcs::SessionToken,
    branch: Option<String>,
) -> Attempt {
    // The plan's own body wins outright and spends no dispatch: a planner who
    // wrote the change request has already done the drafting.
    let (body, undrafted) = match node.body.clone() {
        Some(body) => (Some(body), None),
        // `None` is a launch that named no drafting graph, which drafts nothing
        // and is not a failure: this crate ships the flag, not the document.
        None => match drafted(executor, paths, launch, node, worktree, cancel, tx) {
            None => (None, None),
            Some(Drafted::Body(body)) => (Some(body), None),
            Some(Drafted::Undrafted(ending)) => (None, Some(ending)),
        },
    };
    // Said twice, and only where a drafting dispatch was configured and
    // attempted: in the run's own record at the moment it happened, and on the
    // node's settlement, where a planner reading `results` is shown it without
    // opening the store. Without either, a bodyless change request cannot say
    // whether the drafter ran and failed or was never wired at all — and those
    // need different fixes.
    //
    // On the settlement whatever the publication went on to do, not only where
    // it succeeded: what the drafter did is true either way, and a reader
    // looking for it must not have to know which failure came first. The
    // publication's own reason leads there, because that is what settled the
    // node.
    let undrafted = undrafted.map(|ending| {
        let why = ending.why();
        let _ = tx.send(Message::BodyNotDrafted(Box::new(engine::UndraftedBody {
            node: node.id.clone(),
            ending,
        })));
        why
    });
    // Through the one composition, so every place a publication's own words and
    // a drafting failure are put together agrees about the order and the
    // punctuation — including the failure paths below, which compose the same
    // two values from a different function.
    let with_undrafted = |detail: String| compose(&detail, undrafted.as_deref());
    // The residual: a publication this crate can say nothing more about than
    // that it failed. Every failure `onevcs` names a kind for goes through
    // `failed_publication` below instead, which is where the word and the routing
    // are decided together.
    let publication_failed = |detail: String| {
        Attempt::settled(Settlement {
            branch: branch.clone(),
            detail: Some(with_undrafted(detail)),
            ..Settlement::plain(
                &node.id,
                NodeStatus::Failed,
                Some(crate::vcs::Failure::RESIDUAL),
            )
        })
    };

    // Whether this node's temporary git pin is still temporary, asked at the one
    // moment it decides anything. A node with no reference block — every node that
    // is not fast-adoption, and every fast one whose dependencies land where it
    // does — has nothing to ask about and gets `None`, which is the publication
    // this crate has always made.
    let draft = crate::release::draft_reason(references);
    let publication =
        publish_rereading_the_merge_path(node, token, body.as_deref(), draft.as_ref(), cancel);
    match publication.answered {
        Ok(published) => {
            // A publication that did not land is an ending of the publication,
            // not a refused request: `onevcs` draws that line itself, in
            // `PublishOutcome::Failed`, and this crate reads its line rather
            // than a second one. The reason is the sibling's own — what turned
            // the publication down, and what it said — and it is what the node
            // settles with, or what a re-dispatch carries back to the worker.
            if let onevcs::PublishOutcome::Failed {
                kind,
                reason,
                retained,
            } = &published.outcome
            {
                // The push reached the remote and the reads behind it are spent.
                // Settled here rather than routed with the four the tree was
                // rejected by: there is nothing about the tree to fix, and the
                // node says what it is — where the work is, what commit it is at,
                // and what stopped the read — instead of being asked for again.
                if crate::vcs::failure_of(*kind) == crate::vcs::Failure::Unread {
                    return unread_merge_path(
                        &node.id,
                        token,
                        branch.or_else(|| Some(published.branch.clone())),
                        reason,
                        publication.reads,
                        undrafted.clone(),
                    );
                }
                return failed_publication(
                    &node.id,
                    token,
                    branch.or_else(|| Some(published.branch.clone())),
                    *kind,
                    reason,
                    retained.as_ref(),
                    undrafted.clone(),
                );
            }
            let labels =
                engine::dispatch_labels(&paths.run, &node.id, None, node.persona.as_deref());
            let _ = tx.send(Message::Event(Box::new(crate::vcs::published_event(
                &published, &labels,
            ))));
            // What a `no-changes` compared against. It is the one outcome whose
            // word says nothing a reader can act on — a worker that wrote
            // nothing, a worker whose change was already on the base, and a base
            // that has since taken the work another way all settle identically,
            // and only the ref separates them. The base is the session's own,
            // because a node naming none took the identity's default and this
            // crate never saw it; a session whose record could not be read has
            // none, and the settlement then says what it always did rather than
            // naming a ref nothing established.
            let compared = match published.outcome {
                // Composed out of two of the sibling's own strings and stripped
                // of controls on the way, by the same rule every view applies to
                // a relayed value it renders — see `views::one_line`. A
                // settlement's detail is read back on one line, and this is where
                // this crate makes one out of somebody else's.
                onevcs::PublishOutcome::NothingToPublish => base.map(|base| {
                    crate::views::one_line(&format!(
                        "compared against {base}: {} carries nothing it does not",
                        published.branch
                    ))
                }),
                _ => None,
            };
            // A change the host is holding as a draft says why, on the line a
            // settlement is read back on. It leads whatever else the settlement
            // had to say for the reason a publication's own reason leads a
            // drafting failure: this is what the node settled as.
            let drafted = matches!(published.outcome, onevcs::PublishOutcome::ChangeDraft(_))
                .then(|| draft.as_ref().map(crate::release::drafted_detail))
                .flatten();
            Attempt::settled(Settlement {
                // What the node settles on is its publication, exactly as
                // before; a drafting failure only ever adds words to it.
                detail: drafted
                    .or(compared)
                    .map(&with_undrafted)
                    .or_else(|| undrafted.clone()),
                // The branch the publication says carried the change, where a
                // dispatch reported none: they are the same branch, and the
                // sibling is the one that knows it.
                branch: branch.or_else(|| Some(published.branch.clone())),
                change_url: crate::vcs::change_url(&published.outcome),
                // Every ending has its own name. A branch whose base already
                // carries it settles `no-changes` rather than a bare
                // "published", which is what let a node whose worker wrote
                // nothing report as one that landed work.
                outcome: Some(crate::vcs::outcome_of(&published.outcome).to_owned()),
                // The node is done either way — publishing is the whole of what
                // the plan asked of it — so whether the change *landed* is
                // carried beside the status rather than folded into it. Taken
                // from what the publication answered and never from the policy
                // it ran under: an identity that asks the host to merge
                // immediately still has to be observed doing it.
                landing: crate::vcs::landing_of(&published.outcome),
                // **Complete, and not `done`.** Every step ran and the branch is
                // published, so nothing here failed and nothing is left for this
                // run to ask a worker for; what is left is a release outside it.
                // Settled `done`, the node's dependents would start on work that
                // cannot land and the run would report finished with the git pin
                // it launched against sitting in an open change — which is the
                // one ending fast adoption must not have.
                ..Settlement::plain(&node.id, drafted_status(&published.outcome), None)
            })
        }
        // llmlint: ignore[changed_behavior_has_e2e] this arm is `onevcs` refusing the
        // call outright, which no double can produce: the fake host answers a publish
        // request, and the one refusal this crate can provoke — a title the sibling
        // will not commit under — is caught before any dispatch runs, by
        // `a_title_the_sibling_will_not_commit_under_is_refused_before_any_dispatch`.
        // What the arm does with a drafting failure is not its own composition either:
        // it is the same `publication_failed` the outcome arm above takes, which
        // `a_publication_its_merge_path_refuses_settles_the_node_failed_by_name` drives
        // end to end beside an undrafted body.
        Err(error) => publication_failed(error.to_string()),
    }
}

/// The status a publication settles its node at.
///
/// Read off what the publication **answered** rather than off the reason that was
/// asked for, because the two can differ: a host that would not draft the change
/// is a change that can land, and reporting it as held back would leave a landable
/// pin reported as safe.
fn drafted_status(outcome: &onevcs::PublishOutcome) -> NodeStatus {
    match outcome {
        onevcs::PublishOutcome::ChangeDraft(_) => NodeStatus::CompleteDraft,
        _ => NodeStatus::Done,
    }
}

/// One publication, and how many reads of the merge path it took to answer.
struct Published {
    /// What the last read answered, which is the publication the node settles on.
    answered: crate::error::Result<onevcs::Publication>,
    /// How many reads were made, for the settlement a spent budget writes. One
    /// on every path but the re-read, which is every publication that answered
    /// the first time it was asked.
    reads: std::num::NonZeroU32,
}

/// Publish, and where the push reached the remote with the merge path unread,
/// **re-read that path** rather than sending the agent back to the tree.
///
/// The one publication failure whose fix is not more work: the push landed, and
/// re-dispatching the agent buys a fresh clone and a fresh gate to re-push what
/// the remote already carries.
///
/// The re-read is [`crate::vcs::publish`] on the **same session**, which for a
/// branch already on the remote is `onevcs`'s own guidance for this state and is a
/// read of the host rather than a second push. Nothing here asks a host anything
/// itself: a second route to a change request's state would be host knowledge
/// regrown in the composition layer.
///
/// Bounded by [`engine::merge_path_reads`]. Whatever a read answers is what the
/// node settles on, and the routing that follows is the one that word has always
/// had.
fn publish_rereading_the_merge_path(
    node: &Node,
    token: &onevcs::SessionToken,
    body: Option<&str>,
    draft: Option<&onevcs::DraftReason>,
    cancel: &crate::executor::CancellationToken,
) -> Published {
    let publish =
        || crate::vcs::publish(token, node.merge_policy, node.title.as_deref(), body, draft);
    let budget = engine::merge_path_reads();
    let mut backoff = engine::merge_path_backoff();
    let mut reads = std::num::NonZeroU32::MIN;
    let mut answered = publish();
    while reads < budget && still_unread(&answered) && waited(backoff, cancel) {
        backoff = engine::doubled(backoff);
        reads = reads.saturating_add(1);
        answered = publish();
    }
    Published { answered, reads }
}

/// Wait out one backoff, answering `false` if the run was stopped instead.
///
/// In steps rather than one sleep because the backoff doubles to two minutes, and
/// a teardown held open that long by a poll of somebody else's API is the thing
/// the cancellation is for.
fn waited(backoff: std::time::Duration, cancel: &crate::executor::CancellationToken) -> bool {
    /// How often the wait looks up. Short enough that a stop is not felt as a
    /// pause, long enough that waiting out a two-minute backoff is not a spin.
    const STEP: std::time::Duration = std::time::Duration::from_millis(50);

    let until = std::time::Instant::now() + backoff;
    loop {
        if cancel.is_cancelled() {
            return false;
        }
        let left = until.saturating_duration_since(std::time::Instant::now());
        if left.is_zero() {
            return true;
        }
        std::thread::sleep(left.min(STEP));
    }
}

/// Whether a publication ended with its push on the remote and the path behind it
/// unread — the one ending another read of the host could answer.
///
/// A publication `onevcs` **refused** is not one: the sibling draws the line
/// between a request it would not take and a publication that ran and did not
/// land, and a refusal is the first of those. Nothing about it says a push reached
/// anything, so re-reading it would ask the host about work that may never have
/// left this machine. It settles as the residual, exactly as it always did.
fn still_unread(answered: &crate::error::Result<onevcs::Publication>) -> bool {
    let Ok(published) = answered else {
        return false;
    };
    matches!(
        &published.outcome,
        onevcs::PublishOutcome::Failed { kind, .. }
            if crate::vcs::failure_of(*kind) == crate::vcs::Failure::Unread
    )
}

/// The settlement of a node whose work reached the remote and whose merge path
/// the reads never answered.
///
/// **Not re-dispatched**: nothing rejected the tree, so asking a worker again
/// would republish what the origin already carries. `reason` is `onevcs`'s own
/// sentence, which names the branch, the commit, what stopped the read, and the
/// `publish-branch` that lands it once the host is back.
fn unread_merge_path(
    node: &str,
    token: &onevcs::SessionToken,
    branch: Option<String>,
    reason: &str,
    reads: std::num::NonZeroU32,
    undrafted: Option<String>,
) -> Attempt {
    let how_many = format!(
        "the merge path was read {reads} time{} and never answered",
        if reads.get() == 1 { "" } else { "s" }
    );
    Attempt::settled(Settlement {
        branch,
        head: crate::vcs::branch_head_in(token),
        detail: Some(compose(
            &format!("onevcs: {reason}. {how_many}"),
            undrafted.as_deref(),
        )),
        ..Settlement::plain(node, NodeStatus::Failed, Some(crate::vcs::Failure::UNREAD))
    })
}

/// How one attempt at a lifecycle node ended.
///
/// Two cases, and the split is the whole of the routing: a settlement is the
/// node's answer and the loop stops on it, and a publication that failed leaving
/// the work on its branch is an attempt rather than an answer. Cases rather than
/// a settlement a caller inspects afterwards, because everything a continuation
/// needs exists only on the second and would otherwise be `Option`s on every
/// settlement this crate makes.
enum Attempt {
    Settled(Box<Settlement>),
    Preserving(Box<Preserved>),
}

impl Attempt {
    /// One settled attempt, boxed as the other case is: a settlement is much the
    /// larger of the two, and an enum carrying it inline would move that whole
    /// value through every return between here and the loop.
    fn settled(settlement: Settlement) -> Self {
        Self::Settled(Box::new(settlement))
    }
}

/// A publication that failed and handed its branch back.
///
/// What the *next* attempt is dispatched with, and what the settlement says if
/// there is no next attempt — the same four values serve both, because a budget
/// that runs out has to report exactly the failure it stopped re-dispatching.
struct Preserved {
    branch: String,
    outcome: crate::vcs::Preserving,
    /// Already bounded and folded onto one line, because it reaches a reader
    /// through an envelope payload and a settlement detail, both of which are
    /// read back a line at a time.
    reason: String,
    evidence: Vec<crate::vcs::Evidence>,
    /// A drafting ending this attempt also had, carried so that the settlement
    /// a spent budget writes says it exactly as one that settled straight away
    /// does.
    undrafted: Option<String>,
}

/// Settle or continue one failed publication.
///
/// Preserving is **two** conditions and not one. The failure has to be a kind a
/// further attempt could answer — [`crate::vcs::failure_of`] decides that — and
/// the branch has to still exist outside the session, which is `onevcs`'s
/// [`Retention`](onevcs::Retention) answer: a session's clone is disposable, so a
/// branch the execution checkout refused went with it and there is nothing left
/// to continue. Sending a node back to work on a branch nobody kept would cut a
/// fresh one from the base and republish an empty tree, reporting a recovery that
/// recovered nothing.
#[allow(
    clippy::too_many_arguments,
    reason = "the failure's own five values — which kind, what it said, what became of the \
              branch, which branch, and which node — plus the session the evidence is read \
              off and the drafting ending the settlement carries either way. Bundling them \
              would name a struct whose only constructor is this call site"
)]
fn failed_publication(
    node: &str,
    token: &onevcs::SessionToken,
    branch: Option<String>,
    kind: onevcs::FailureKind,
    reason: &str,
    retained: Option<&onevcs::Retention>,
    undrafted: Option<String>,
) -> Attempt {
    let failure = crate::vcs::failure_of(kind);
    let handed_back = matches!(retained, Some(onevcs::Retention::HandedBack(_)));
    let settled = || {
        Attempt::settled(Settlement {
            branch: branch.clone(),
            detail: Some(compose(&format!("onevcs: {reason}"), undrafted.as_deref())),
            ..Settlement::plain(node, NodeStatus::Failed, Some(failure.outcome()))
        })
    };
    // llmlint: ignore-block[changed_behavior_has_e2e] the second arm covers two cases and
    // only one of them is new. The **terminal** one — a failure no further attempt can
    // answer — is driven end to end by
    // `a_publication_onevcs_refuses_outright_settles_the_residual_and_is_not_retried`,
    // which asserts the residual word and that the node was dispatched exactly once. It
    // reaches the arm through a hosted identity this build has no `RemoteHost` for,
    // because a repository's own verification no longer produces a terminal kind at all:
    // `onevcs` 0.11.0 runs no gate, and the merge path refusing a push is `push-rejected`,
    // which is preserving. The other case is a preserving failure whose branch the
    // execution checkout refused: `onevcs` hands a branch back on every failure it can and
    // reports `Refused` only when that copy itself failed — a checkout that could not be
    // written to — which no double here injects and which the hook script deliberately
    // keeps out of the repository. Reaching it would mean breaking the checkout
    // mid-publication, which proves the fixture rather than this arm, and what it does is
    // exactly what the terminal case does.
    match (failure, handed_back, branch.clone()) {
        (crate::vcs::Failure::Preserving(outcome), true, Some(branch)) => {
            Attempt::Preserving(Box::new(Preserved {
                branch,
                outcome,
                reason: engine::bounded(&crate::views::one_line(reason)),
                evidence: crate::vcs::evidence_in(token),
                undrafted,
            }))
        }
        _ => settled(),
    } // llmlint: ignore-end[changed_behavior_has_e2e]
}

/// A publication's own words and a drafting ending, in that order.
///
/// Written once because three settlements compose the pair, and three spellings
/// of it would come to disagree about the order or the punctuation.
fn compose(detail: &str, undrafted: Option<&str>) -> String {
    match undrafted {
        Some(why) => format!("{detail}. {why}"),
        None => detail.to_owned(),
    }
}

/// The settlement of a node that will not be dispatched again — because its
/// publication budget is spent, or because the run is being cancelled before it
/// could be. Both endings settle as the publication failure, so both are written
/// here.
///
/// The **last** failure's word, because that is the one standing in the way, over
/// a roll-up of every attempt: without it a reader sees one failure and cannot
/// tell it from a node that failed once — which is the difference between "fix
/// this check" and "this check is never going to pass".
fn stopped_retrying(
    node: &str,
    preserved: &Preserved,
    endings: &[crate::vcs::Preserving],
) -> Settlement {
    let each: Vec<String> = endings
        .iter()
        .enumerate()
        .map(|(index, ending)| format!("{} {}", index + 1, ending.outcome()))
        .collect();
    let roll_up = format!(
        "{} publication attempt{} on {}: {}",
        endings.len(),
        if endings.len() == 1 { "" } else { "s" },
        preserved.branch,
        each.join(", ")
    );
    Settlement {
        branch: Some(preserved.branch.clone()),
        detail: Some(compose(
            &format!("onevcs: {}. {roll_up}", preserved.reason),
            preserved.undrafted.as_deref(),
        )),
        // **No step** is recorded as completed, and that is the same rule the
        // re-dispatch was made under seen from the other end. The branch carries
        // a tree the merge path rejected, so a `retry` that skipped the steps it
        // already holds would publish that tree again unaltered and meet the same
        // refusal — the ending this whole loop exists to avoid, reached by hand
        // instead of automatically.
        ..Settlement::plain(node, NodeStatus::Failed, Some(preserved.outcome.outcome()))
    }
}

/// The node the next attempt is dispatched as.
///
/// Three changes and no others. It is **pinned to the preserved branch**, so the
/// session `onevcs` opens continues that branch from its own tip rather than
/// cutting a second one beside committed work. It records **no step as
/// completed**, so every step runs again — against the tree that was rejected,
/// which is the tree that has to change; a continuation that skipped the steps
/// the branch already carries would republish it unaltered and meet the same
/// refusal, which is the one failure this must not have. And it carries the
/// **diagnosis** as its node context, so the worker meets the failure rather than
/// having to go and find it.
///
/// The planner's own note does not survive: a note carries exactly one dispatch
/// and the attempt that just ran was it.
fn continued(
    node: &Node,
    preserved: &Preserved,
    attempt: std::num::NonZeroU32,
    attempts: std::num::NonZeroU32,
    endings: &[crate::vcs::Preserving],
) -> Node {
    Node {
        branch: Some(preserved.branch.clone()),
        resume: None,
        context: Some(diagnosis(preserved, attempt, attempts, endings)),
        ..node.clone()
    }
}

/// What the next attempt is told about the one before it.
///
/// The failure's own reason and a pointer to every artifact its publication
/// recorded — the check's log, the push's output, the conflict's hunks — by id,
/// because the artifact is somebody else's megabytes and what a worker needs is
/// the fetch that gets it. Named as *observed state* by the section it is
/// rendered into, so a worker cannot read a failure report as a new bar to clear.
fn diagnosis(
    preserved: &Preserved,
    attempt: std::num::NonZeroU32,
    attempts: std::num::NonZeroU32,
    endings: &[crate::vcs::Preserving],
) -> String {
    let mut note = format!(
        "The previous attempt's publication failed and its branch was preserved. This is \
         attempt {attempt} of {attempts}, and it continues that same branch — {branch} — so \
         the tree that was rejected is the tree this dispatch starts from. Change what the \
         failure below is about; republishing it unaltered meets the same refusal.\n\n\
         The publication ended `{ending}`, and `onevcs` said:\n\n{reason}\n",
        branch = preserved.branch,
        ending = preserved.outcome.outcome(),
        reason = preserved.reason,
    );
    if endings.len() > 1 {
        let each: Vec<&str> = endings.iter().map(|ending| ending.outcome()).collect();
        note.push_str(&format!(
            "\nEvery attempt so far ended: {}.\n",
            each.join(", ")
        ));
    }
    if !preserved.evidence.is_empty() {
        note.push_str(
            "\nThe publication recorded this evidence, each fetched with \
             `onevcs artifact cat ID`:\n",
        );
        for evidence in &preserved.evidence {
            note.push_str(&format!("- {}{}\n", evidence.kind.0, evidence.id.0));
        }
    }
    note
}

/// The task a drafting dispatch is given, ahead of the node's own.
const DRAFTING_TASK: &str = "Read this branch's diff and write the change request's body, \
     following the repository's own template. The task this branch delivered:";

/// What one drafting dispatch ended as.
///
/// A body or an ending that is not one, because **every** ending here leaves the
/// publication to proceed with no body: the two are what a change request opens
/// with, not whether it opens.
enum Drafted {
    /// It drafted the change request's body.
    Body(String),
    /// It ended with none, and which of the three endings it was.
    Undrafted(Undrafted),
}

/// A drafting dispatch that produced no body, and how.
///
/// Three endings kept apart rather than one "it did not work", because they need
/// three different fixes: a graph that will not start or will not finish, one
/// whose answers the schema refuses, and one that answers inside the schema with
/// nothing in it. A run that had just wired a drafter could tell none of them
/// from a launch that had wired no drafter at all.
pub(crate) enum Undrafted {
    /// It could not be run, or it ran and did not succeed — in its own words.
    ///
    /// One ending rather than three: a dispatch that never started, one that
    /// failed, and one that was cancelled differ in the reason they carry and in
    /// nothing else a publication carrying no body either way can act on.
    Dispatch(String),
    /// It succeeded, and the schema it was validated against refused every
    /// answer it made.
    SchemaRefused,
    /// It succeeded and there was no body in what it answered with.
    ///
    /// The widest of the three on purpose. It is where a dispatch lands that
    /// succeeded and had nothing refused: one that answered inside its schema
    /// and put nothing in it, one no schema was asked of, and one whose reports
    /// this run holds no readable copy of. They differ in nothing a reader acts
    /// on differently — a drafter that succeeded and produced no prose is the
    /// same fix in each — and none of them is a schema to correct, which is
    /// what keeps them out of [`SchemaRefused`](Self::SchemaRefused).
    Bodyless,
}

impl Undrafted {
    /// The ending, as the event names it.
    pub(crate) fn ending(&self) -> &'static str {
        match self {
            Self::Dispatch(_) => "dispatch-failed",
            Self::SchemaRefused => "schema-refused",
            Self::Bodyless => "no-body",
        }
    }

    /// Why the change request opened with no body, in the words a planner reads
    /// off `results`.
    pub(crate) fn why(&self) -> String {
        match self {
            Self::Dispatch(reason) => {
                format!("the change request's body was not drafted: {reason}")
            }
            Self::SchemaRefused => "the change request's body was not drafted: the drafting \
                 dispatch answered nothing the schema it was validated against accepted"
                .to_owned(),
            Self::Bodyless => "the change request's body was not drafted: the drafting \
                 dispatch succeeded and there was no body in what it answered with"
                .to_owned(),
        }
    }
}

/// One post-verification dispatch drafting the change request's body, when the
/// launch named a graph to draft it with and the node carries none of its own.
///
/// It runs **after** the branch has been verified and is not on the publication
/// path: every way it can end badly leaves the change request to open with no
/// body, and the node settles on its publication as before. That is the whole
/// point of running it here rather than making it a step. What each of those
/// ways *was* is [`Undrafted`], reported beside the publication rather than
/// folded into it.
///
/// It runs in the node's **own** worktree, which is the only place the diff it is
/// asked to read exists: a session of its own would be a fresh clone cut from the
/// base, carrying nothing this node wrote — and opening one reclaims the session
/// still holding the work. So a node with no worktree to run it in drafts
/// nothing, out loud, rather than dispatching an agent to read an empty diff.
///
/// `None` is the one ending that is not a failure and is not reported: a launch
/// that named no drafting graph. This crate ships the flag, not the document, so
/// naming none is the shipped default and there is nothing to say about it. A
/// node carrying its own `body` never reaches here at all.
#[allow(
    clippy::too_many_arguments,
    reason = "the draft is a dispatch inside one lifecycle execution and needs that \
              execution's executor, the run's own paths, what its launch decided, the node, \
              the workspace, cancellation, and the event stream"
)]
fn drafted(
    executor: &dyn Executor,
    paths: &RunPaths,
    launch: &Launch,
    node: &Node,
    worktree: Option<&std::path::Path>,
    cancel: &crate::executor::CancellationToken,
    tx: &Sender<Message>,
) -> Option<Drafted> {
    let graph = launch.pr_author_graph.as_deref()?;
    let Some(worktree) = worktree else {
        // A dispatch that was configured and could not be run at all, which is
        // the same ending as one the executor refused: it is said out loud, as
        // it always was, and now recorded as well.
        let why = "there was no worktree to read this branch's diff in";
        eprintln!(
            "onepipeline: node '{}': no worktree to draft its change request in, \
             so it publishes with no body",
            node.id
        );
        return Some(Drafted::Undrafted(Undrafted::Dispatch(why.to_owned())));
    };
    let dispatch = executor.dispatch(DispatchRequest {
        graph: oneagentgraph::config::ConfigRef(graph.to_owned()),
        task: format!("{DRAFTING_TASK}\n\n{}", node.rendered_task()),
        labels: engine::dispatch_labels(&paths.run, &node.id, None, Some(PR_AUTHOR_PERSONA)),
        // None of the node's own: the drafting dispatch is not the node's work,
        // and a turn budget written for that work would be spent twice — once on
        // it and once here — if this dispatch inherited it.
        controls: NodeControls::default(),
        workspace: WorkspaceSpec::Path(worktree.to_path_buf()),
        cancel: cancel.clone(),
    });
    let mut handle = match dispatch {
        Ok(handle) => handle,
        Err(error) => {
            return Some(undrafted(
                &node.id,
                format!("the drafting dispatch could not start: {error}"),
            ))
        }
    };
    let mut retained = Vec::new();
    for envelope in handle.events() {
        // A line off this stream that will not parse costs that line and nothing
        // more: what the loop is looking for is a `member-settled` naming a
        // retained report, and a drafting run that never produces one already
        // publishes with no body two lines below. Skipping is therefore the same
        // ending an unreadable stream would reach by any other route, reported
        // the same way.
        // llmlint: ignore[changed_behavior_has_e2e] no double can produce this: the
        // envelopes come off the real `oneagentgraph`'s own stdout, which is well-formed
        // by construction, and there is no fault-injection seam here to drive one through.
        // The ending it falls back to — a dispatch that yields no body, and a publication
        // that proceeds without one — is driven end to end by
        // `a_drafting_graph_the_runner_refuses_still_publishes_the_change_request`.
        let Ok(envelope) = envelope else { continue };
        // **Ingest**, and the same ingest the engine performs on the envelopes
        // this relays to it: the line is arriving on the stdout of a process
        // this crate started, which is the one moment the path it names carries
        // the producer's authority rather than the journal's. What is read
        // below is that copy, at a path derived from the settlement — this
        // crate never opens the path a producer named.
        crate::report::retain(paths, &envelope);
        if envelope.source == crate::event::Source::Agentgraph
            && envelope.kind.0 == crate::report::MEMBER_SETTLED
        {
            retained.push(paths.report_for(&envelope.stream, envelope.seq));
        }
        let _ = tx.send(Message::Event(Box::new(envelope)));
    }
    // llmlint: ignore-block[changed_behavior_has_e2e] the last arm below is reached by a
    // dispatch that failed and by one that was cancelled; the first has a journey of its
    // own in `tests/e2e/lifecycle.rs` and the second has none because it is not separately
    // reachable. Nothing cancels a drafting dispatch except the node's own token being
    // flipped, which happens when the run is being stopped — and a run whose driver is
    // being torn down has no publication left to protect, so a journey claiming "it
    // published anyway" would be asserting the opposite of what a stop means. Deleting the
    // arm is not the alternative either: it is the same `_` a failed settlement takes.
    match handle.wait() {
        Ok(outcome) if outcome.succeeded => {
            // Every report the dispatch retained, read as **one** answer: a
            // fallback chain records a candidate per identity it tried, and
            // which report an entry landed in is not the reader's business.
            let kept: Vec<serde_json::Value> = retained
                .iter()
                .filter_map(|kept| crate::report::read(kept))
                .collect();
            Some(match crate::report::drafted(&kept) {
                crate::report::Drafted::Body(body) => Drafted::Body(body),
                crate::report::Drafted::SchemaRefused => {
                    Drafted::Undrafted(Undrafted::SchemaRefused)
                }
                crate::report::Drafted::Bodyless => Drafted::Undrafted(Undrafted::Bodyless),
            })
        }
        Ok(outcome) => Some(undrafted(
            &node.id,
            format!(
                "the drafting dispatch settled without succeeding: {}",
                first_line(&outcome.detail)
            ),
        )),
        Err(error) => Some(undrafted(
            &node.id,
            format!("the drafting dispatch could not be waited on: {error}"),
        )),
    } // llmlint: ignore-end[changed_behavior_has_e2e]
}

/// A drafting dispatch that produced no body because the **dispatch** failed,
/// said out loud and then recorded.
///
/// Out loud for every one of those endings rather than one of them, because the
/// reason does not distinguish between them: a launch that named a drafting graph
/// and silently drafted nothing is indistinguishable from one that named none,
/// and the change request it opens carries no sign of it either way. Which
/// ending a given failure takes depends on where the dispatch runs — a graph the
/// runner refuses is a refusal to the caller that launched it in its own process
/// and a settlement to the one that gave it a process of its own — and an
/// operator reading stderr must not be told only on the arms one deployment
/// happens to reach.
fn undrafted(node: &str, why: String) -> Drafted {
    eprintln!("onepipeline: node '{node}': {why}, so it publishes with no body");
    Drafted::Undrafted(Undrafted::Dispatch(why))
}

/// A dispatch's own words, as one bounded line of a settlement detail.
///
/// The reason a dispatch gives is its stderr, which is many lines of a sibling's
/// diagnostics; what belongs beside a publication is the first of them, held to
/// the same bound every other payload text this crate writes is held to.
fn first_line(detail: &str) -> String {
    match detail.lines().find(|line| !line.trim().is_empty()) {
        Some(line) => engine::bounded(line.trim()),
        None => "it reported nothing".to_owned(),
    }
}
// llmlint: ignore-end[invalid_states_unrepresentable]

/// Put every envelope a followed session writes into the merged stream.
fn relay_into(tx: &Sender<Message>, node: Labels) -> Box<dyn Fn(Envelope) + Send> {
    let tx = tx.clone();
    Box::new(move |mut envelope| {
        stamp(&mut envelope.labels, &node);
        let _ = tx.send(Message::Event(Box::new(envelope)));
    })
}

/// Say which node a session's envelope belongs to, where its producer could not.
///
/// `onevcs` stamps what it knows, and a session does not know it is a graph
/// node: the crate that opened it does. Without this a whole publication —
/// push, change request, merge — lands in the merged store belonging to no node,
/// so every per-node view reads it as work that happened to nobody.
///
/// An enricher, so it never rewrites: a key the producer stamped stands.
pub(crate) fn stamp(labels: &mut Labels, known: &Labels) {
    labels.run_id = labels.run_id.take().or_else(|| known.run_id.clone());
    labels.node = labels.node.take().or_else(|| known.node.clone());
    labels.persona = labels.persona.take().or_else(|| known.persona.clone());
}

/// How long ending a session waits for the terminator its stream ends with.
///
/// Nothing in the ordinary case: a session whose terminator is written answers on
/// the first read. The grace bounds the case where none is.
const TERMINATOR_GRACE: Duration = Duration::from_secs(5);

/// How often that wait re-reads the stream, and re-asks a close that refused.
const TERMINATOR_POLL: Duration = Duration::from_millis(250);

/// Close the session, and collect what its stream said.
///
/// **The follow ends first, and the close comes after it.** `onevcs` refuses to
/// release a session while any live process is working inside its run root, and
/// the follow's own poll asks the library whether the session closed — a call
/// that shells out to `git` in that session's clone. Closed first, as this once
/// was, the close raced the follow's own children and lost intermittently: the
/// session stayed open and the refusal was the only account of why.
///
/// Closing is still what writes the session's last record, so a follow can end
/// having relayed everything but the tail, and the stream is read again
/// afterwards from the point it reached. **Again, rather than once more**: every
/// way a read can go badly hands back an empty batch, so one read made the last
/// record conditional on that read having gone well, and a node settled in
/// silence with a hole in its record.
fn end_session(
    stream: Option<crate::vcs::Follower>,
    tx: &Sender<Message>,
    token: Option<&onevcs::SessionToken>,
    node: &Labels,
    filter: Option<&EventFilter>,
) {
    // Empty from either side is the whole stream still to read: no follow was
    // started, or one was and relayed nothing.
    let followed_through = stream.map(crate::vcs::Follower::finish).unwrap_or_default();
    let refused = close(token);
    relay_session_events(tx, token, node, followed_through, filter, refused);
}

/// Fold the part of the session's stream nothing has relayed into the merged one.
///
/// `onevcs` records the commits and the publication against the session, the
/// merge path's own verdict on the `push` among them; without this the merged
/// store would carry a lifecycle node's settlement with none of the evidence
/// behind it. `followed_through` is the highest `seq` the follow already relayed
/// **per stream**, so a record arrives **once**: each stream is numbered
/// monotonically and resumes its series across the processes that write to it,
/// which makes those marks the whole of the bookkeeping. Per stream and not one
/// mark over all of them, because reading one session hands back the identity's
/// release records as well as the session's own, in a series of their own.
fn relay_session_events(
    tx: &Sender<Message>,
    token: Option<&onevcs::SessionToken>,
    node: &Labels,
    followed_through: crate::vcs::Watermarks,
    filter: Option<&EventFilter>,
    refused: Option<String>,
) {
    let Some(token) = token else { return };
    let relay = relay_into(tx, node.clone());
    // Carried across the reads rather than re-derived from each: what stops a
    // record arriving twice is the mark the relay left on it, and a second read of
    // a stream hands back everything the first one did.
    let mut relayed = followed_through;
    let mut refused = refused;
    let deadline = Instant::now() + TERMINATOR_GRACE;
    // llmlint: ignore-block[changed_behavior_has_e2e] every lifecycle journey drives the
    // first pass. A second one needs a stream that gains its last record late or never,
    // which no plan can ask for — `a_session_whose_terminator_arrives_late_still_relays_it_and_one_with_none_says_so`
    // holds both, against a real stream through the real reader.
    loop {
        // The same filter the follow was opened with: this read covers the tail of
        // the *same* stream, so a run that filtered what it followed and not what
        // it caught up on would relay events it said it did not want, for no
        // reason but which side of a settlement they landed on.
        let read = crate::vcs::events(token, filter);
        // Asked of the whole read rather than of what this pass relays: the follow
        // may have relayed the terminator already, and what the wait is for is a
        // session that has *ended*, however its last record reached the store.
        let ended = read.iter().any(crate::vcs::is_terminator);
        for envelope in beyond(read, &relayed) {
            relayed.reached(&envelope);
            relay(envelope);
        }
        if ended {
            return;
        }
        if Instant::now() >= deadline {
            // The one thing a reader of the merged store cannot work out for
            // itself: the records are all there and the last one is missing, which
            // is indistinguishable from a publication still running.
            eprintln!(
                "onepipeline: session {} ended with no `session-closed` record{}",
                token.0,
                refused
                    .map(|why| format!("; its close refused: {why}"))
                    .unwrap_or_default()
            );
            return;
        }
        // Asked again only where the ask before it refused, and only after the read
        // above found no terminator — so a close that emitted one and then failed is
        // never asked to emit a second. `onevcs` refuses a close over a live process
        // working inside the run root, which is exactly what the dispatch that has
        // just finished is until the host reaps it: a refusal that answers
        // differently a moment later, and the only one that leaves a session with no
        // last record at all.
        if refused.is_some() {
            refused = close(Some(token));
        }
        std::thread::sleep(TERMINATOR_POLL);
    }
    // llmlint: ignore-end[changed_behavior_has_e2e]
}

/// The part of what a read handed back that a follow did not already relay.
///
/// Empty marks are the whole of it — no follow was started, or one was and
/// relayed nothing — which is a stream still to read rather than a stream that
/// held nothing. Otherwise everything numbered past the mark **its own stream**
/// stands at, and nothing at or below it: a record relayed twice is the same
/// defect as one lost, seen from the other side.
fn beyond(envelopes: Vec<Envelope>, followed_through: &crate::vcs::Watermarks) -> Vec<Envelope> {
    envelopes
        .into_iter()
        .filter(|envelope| followed_through.beyond(envelope))
        .collect()
}

/// Close the session, and answer with what refused it.
///
/// Still best effort where it mattered — the refusal settles no node, so a node
/// that already failed is not reported as a different failure because its cleanup
/// also failed. It is kept because it is the one thing that explains a stream with
/// no terminator on it.
fn close(token: Option<&onevcs::SessionToken>) -> Option<String> {
    crate::vcs::session_close(token?)
        .err()
        .map(|refusal| refusal.to_string())
}

/// A node's steps in dispatch order, each with the controls its dispatch runs
/// under, or why the node has none it can run.
///
/// One function for both refusals a workstream can carry before it starts — a
/// dependency cycle among its steps, and a step whose declaration no dispatch
/// can honour — because they cost the same thing if they are found late: a
/// branch cut for a node that was never going to finish.
fn dispatchable_steps(node: &Node) -> std::result::Result<Vec<(Step, NodeControls)>, String> {
    ordered_steps(node)?
        .into_iter()
        .map(|step| {
            NodeControls::of_step(&step)
                .map(|controls| (step.clone(), controls))
                .map_err(|why| format!("node '{}': step '{}': {why}", node.id, step.id))
        })
        .collect()
}

/// A node's steps in topological order, or why they have none.
///
/// Steps share one branch and run serially, so the order is a total one: ties
/// are broken by the order the plan wrote them, which keeps a workstream
/// reproducible.
pub fn ordered_steps(node: &Node) -> std::result::Result<Vec<Step>, String> {
    let Some(steps) = &node.steps else {
        // A lifecycle node with no steps is one implicit step: its own persona
        // and task, on its own branch.
        return Ok(vec![Step {
            id: node.id.clone(),
            kind: node.kind,
            task: node.task.clone(),
            persona: node.persona.clone(),
            deps: Vec::new(),
            max_turns: node.max_turns,
            expects_no_diff: node.expects_no_diff,
            executor: node.executor.clone(),
            agent_graph: node.agent_graph.clone(),
        }]);
    };

    let by_id: BTreeMap<&str, &Step> = steps.iter().map(|s| (s.id.as_str(), s)).collect();
    let mut settled: BTreeSet<&str> = BTreeSet::new();
    let mut order: Vec<Step> = Vec::new();
    while order.len() < steps.len() {
        let mut progressed = false;
        for step in steps {
            if settled.contains(step.id.as_str()) {
                continue;
            }
            if step
                .deps
                .iter()
                .all(|dep| settled.contains(dep.as_str()) || !by_id.contains_key(dep.as_str()))
            {
                settled.insert(step.id.as_str());
                order.push(step.clone());
                progressed = true;
            }
        }
        if !progressed {
            return Err(format!(
                "node '{}': its steps have a dependency cycle",
                node.id
            ));
        }
    }
    Ok(order)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The endings this module emits and the endings the contract names are one
    /// set.
    ///
    /// The wire spellings are stated twice — in `docs/contract.md`'s pr-author
    /// paragraph and in [`Undrafted::ending`] — and only one of them is
    /// compiled, so the document needs a gate the way the closed set of kinds
    /// has one in `tests/contract.rs`. It cannot live there: the type is private
    /// to this module, and a public one would widen the surface past what the
    /// contract names.
    #[test]
    fn every_ending_this_module_emits_is_one_the_contract_names() {
        let contract = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/contract.md"),
        )
        .expect("the contract ships");
        let endings = [
            Undrafted::Dispatch(String::new()),
            Undrafted::SchemaRefused,
            Undrafted::Bodyless,
        ];
        for ending in &endings {
            assert!(
                contract.contains(&format!("`{}`", ending.ending())),
                "docs/contract.md does not name the `{}` ending this module emits",
                ending.ending()
            );
        }

        // And the other direction: a spelling the document carries and nothing
        // emits is a promise nobody keeps. The contract lists them in one
        // clause, so the clause is read and its backticked tokens compared with
        // the set above rather than the whole document searched.
        let clause = contract
            .split_once("carrying `ending` —")
            .expect("the contract lists the endings `body-not-drafted` carries")
            .1
            .split_once("— and `detail`")
            .expect("the clause ends where the detail begins")
            .0;
        let listed: Vec<&str> = clause.split('`').skip(1).step_by(2).collect();
        assert_eq!(
            listed,
            endings
                .iter()
                .map(Undrafted::ending)
                .collect::<Vec<&'static str>>(),
            "the contract's endings are not the ones this module emits"
        );

        // The sentences a reader is given are each the ending's own, so two
        // endings cannot arrive under one set of words.
        let why: std::collections::BTreeSet<String> = endings.iter().map(Undrafted::why).collect();
        assert_eq!(why.len(), endings.len(), "two endings say the same thing");
    }

    /// The README summarises the same set, so it is gated the same way.
    ///
    /// It is a third copy of the endings — the enum, the contract, and the
    /// user-facing prose — and the first two already hold each other. Left
    /// ungated the README is the one that goes quietly stale: nothing compiles
    /// it, and a reader meeting an ending it does not list has no way to know
    /// which of the two is behind.
    #[test]
    fn the_readmes_ending_summary_is_the_set_this_module_emits() {
        let raw = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"),
        )
        .expect("the README ships");
        // Wrapped prose, so match on its words rather than its line breaks.
        let readme = raw.split_whitespace().collect::<Vec<_>>().join(" ");
        let clause = readme
            .split_once("under one of three endings —")
            .expect("the README summarises the endings a drafting dispatch can reach")
            .1
            .split_once("— and the node's own settlement")
            .expect("the clause ends where the settlement's own half begins")
            .0;
        let listed: Vec<&str> = clause.split('`').skip(1).step_by(2).collect();
        assert_eq!(
            listed,
            [
                Undrafted::Dispatch(String::new()),
                Undrafted::SchemaRefused,
                Undrafted::Bodyless,
            ]
            .iter()
            .map(Undrafted::ending)
            .collect::<Vec<&'static str>>(),
            "the README's endings are not the ones this module emits"
        );
    }

    /// A workstream refuses before it cuts a branch.
    ///
    /// The step's declaration is one no dispatch can run under, and it is found
    /// while the node is still a document: nothing here opens a session, so the
    /// refusal cannot leave commits on a branch for a node that was never going
    /// to finish. `execute` reports it through the arm a step cycle already
    /// takes.
    #[test]
    fn a_step_whose_budget_no_dispatch_can_run_under_stops_the_workstream() {
        let node = Node {
            id: "service".into(),
            repo: Some("owner/service".into()),
            steps: Some(vec![
                Step {
                    max_turns: Some(45),
                    ..step("implement", &[])
                },
                Step {
                    max_turns: Some(0),
                    ..step("review", &["implement"])
                },
            ]),
            ..Node::default()
        };
        let why = dispatchable_steps(&node)
            .expect_err("a step that can take no turn is not dispatchable");
        assert!(why.contains("node 'service': step 'review':"), "{why}");
        assert!(why.contains("no turn at all"), "{why}");

        // And the workstream itself stops there. The repository is one nothing
        // has registered, so if this refusal came any later the failure would be
        // `onevcs`'s — which is the same as saying a branch would already exist
        // for a node that was never going to finish. The executor is the real
        // one for the same reason: a regression here would go looking for
        // `oneagentgraph` rather than quietly running the step.
        let (tx, rx) = std::sync::mpsc::channel();
        let settlement = execute(
            &crate::executor::LocalExecutor,
            &RunPaths::under(std::path::Path::new("/nowhere"), "demo"),
            &Launch {
                node_graph: "graphs/node-scope.yaml".into(),
                ..Launch::default()
            },
            &node,
            &[],
            &crate::executor::CancellationToken::new(),
            &tx,
        );
        assert_eq!(settlement.status, NodeStatus::Failed);
        assert_eq!(settlement.outcome.as_deref(), Some("invalid-node"));
        let detail = settlement.detail.expect("the settlement says why");
        assert!(detail.contains("step 'review'"), "{detail}");
        assert!(detail.contains("no turn at all"), "{detail}");
        assert_eq!(
            rx.try_iter().count(),
            0,
            "a workstream that could not dispatch a step opened a session anyway"
        );

        // The step that *can* run keeps the budget it declared, narrowed.
        let node = Node {
            steps: Some(vec![Step {
                max_turns: Some(45),
                ..step("implement", &[])
            }]),
            ..node
        };
        let dispatchable = dispatchable_steps(&node).expect("45 is a budget a step can run under");
        assert_eq!(
            dispatchable[0].1.max_turns,
            std::num::NonZeroU32::new(45),
            "the step's own budget did not survive the conversion"
        );
    }

    fn step(id: &str, deps: &[&str]) -> Step {
        Step {
            id: id.into(),
            persona: Some("engineer".into()),
            task: Some("## What\ndo it".into()),
            deps: deps.iter().map(|d| (*d).to_string()).collect(),
            ..Step::default()
        }
    }

    fn lifecycle(steps: Option<Vec<Step>>) -> Node {
        Node {
            id: "service".into(),
            repo: Some("owner/repo".into()),
            persona: steps.is_none().then(|| "engineer".into()),
            task: steps.is_none().then(|| "## What\nship".into()),
            steps,
            ..Node::default()
        }
    }

    #[test]
    fn steps_run_serially_in_topological_order() {
        let node = lifecycle(Some(vec![
            step("publish", &["review"]),
            step("implement", &[]),
            step("review", &["implement"]),
        ]));
        let order: Vec<String> = ordered_steps(&node)
            .expect("the steps order")
            .into_iter()
            .map(|s| s.id)
            .collect();
        assert_eq!(order, vec!["implement", "review", "publish"]);
    }

    #[test]
    fn steps_with_a_cycle_are_reported_rather_than_run_in_some_order() {
        let node = lifecycle(Some(vec![step("a", &["b"]), step("b", &["a"])]));
        let message = ordered_steps(&node).unwrap_err();
        assert!(message.contains("dependency cycle"), "{message}");
    }

    #[test]
    fn a_lifecycle_node_with_no_steps_is_one_implicit_step() {
        let node = lifecycle(None);
        let steps = ordered_steps(&node).expect("one implicit step");
        assert_eq!(steps.len(), 1);
        assert_eq!(steps[0].id, "service");
        assert_eq!(steps[0].persona.as_deref(), Some("engineer"));
    }

    /// The record a follow ended one read short of, relayed exactly once — and
    /// counted against **its own** stream.
    ///
    /// The window this covers is inside a library call now — closing a session
    /// flips its record and only then writes `session-closed`, and the follow
    /// reads and only then asks whether the session closed — so it cannot be
    /// forced from an e2e the way a delayed subprocess once could. This is the
    /// arithmetic that makes "once" true either way, held on its own.
    ///
    /// Two streams rather than one, because reading a session hands back two:
    /// its own records, and the identity's release records that name its
    /// landing, numbered in a series of their own over every session in that
    /// repository. Under one mark over both, a release numbered higher than the
    /// session had reached would hide the session's next record — a relayed
    /// record lost, silently.
    #[test]
    fn relays_only_what_the_follow_did_not_counting_each_stream_on_its_own() {
        let wrote = |stream: &str, seq: u64| Envelope {
            v: crate::event::ENVELOPE_VERSION,
            ts: "2026-01-01T00:00:00.000Z".into(),
            stream: stream.to_owned(),
            seq,
            source: crate::event::Source::Vcs,
            kind: crate::event::EventKind("session-closed".into()),
            phase: None,
            labels: Labels::default(),
            payload: serde_json::Map::new(),
            artifacts: Vec::new(),
        };
        let session: Vec<Envelope> = (1..=4).map(|seq| wrote("s-1", seq)).collect();

        // A follow that reached the third record leaves the tail and nothing
        // else: re-reading the whole stream would put the first three in twice.
        let mut reached = crate::vcs::Watermarks::default();
        for envelope in &session[..3] {
            reached.reached(envelope);
        }
        let tail = beyond(session.clone(), &reached);
        assert_eq!(tail.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![4]);

        // A follow that ended having relayed everything leaves nothing.
        reached.reached(&session[3]);
        assert!(beyond(session.clone(), &reached).is_empty());

        // A release the same read handed back is another stream's record, so a
        // mark four records into the session's says nothing about it.
        let released = wrote("releases-0a1b2c3d4e5f", 2);
        assert_eq!(
            beyond(vec![released.clone()], &reached)
                .iter()
                .map(|e| e.stream.clone())
                .collect::<Vec<_>>(),
            vec!["releases-0a1b2c3d4e5f".to_owned()],
            "a release was hidden by how far the session's own stream had got"
        );
        // And once it has been relayed, the session's tail is still relayable
        // from the mark it stands at rather than from that release's.
        reached.reached(&released);
        assert!(beyond(vec![released], &reached).is_empty());
        assert_eq!(
            beyond(vec![wrote("s-1", 5)], &reached)
                .iter()
                .map(|e| e.seq)
                .collect::<Vec<_>>(),
            vec![5]
        );

        // And a follow that relayed nothing at all leaves the whole stream,
        // which is a stream still to read rather than a stream that held
        // nothing.
        assert_eq!(
            beyond(session, &crate::vcs::Watermarks::default())
                .iter()
                .map(|e| e.seq)
                .collect::<Vec<_>>(),
            vec![1, 2, 3, 4]
        );
    }

    /// A terminator written after the follow ended still reaches the merged
    /// store, and a session that never writes one is **said** rather than left as
    /// a hole in it.
    ///
    /// Driven against the stream **file**, because that is what decides: no
    /// journey can make a real close write its terminator late or not at all. The
    /// sibling is not doubled — the reader under test is its own.
    ///
    /// One test for all three cases: `ONEVCS_HOME` is process-global.
    #[test]
    fn a_session_whose_terminator_arrives_late_still_relays_it_and_one_with_none_says_so() {
        let _home = crate::vcs::scratch_home_held();
        let root =
            std::env::temp_dir().join(format!("onepipeline-terminator-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("streams")).expect("a scratch state root");
        std::env::set_var("ONEVCS_HOME", &root);

        let record = |token: &str, seq: u64, kind: &str| {
            serde_json::json!({
                "v": crate::event::ENVELOPE_VERSION,
                "ts": "2026-01-01T00:00:00.000Z",
                "stream": token,
                "seq": seq,
                "source": "vcs",
                "kind": kind,
                "labels": {},
                "payload": {},
                "artifacts": [],
            })
            .to_string()
        };
        let path = |token: &str| root.join("streams").join(format!("{token}.ndjson"));
        let write = |token: &str, body: &str| {
            std::fs::write(path(token), body).expect("the stream is written");
        };
        // What the loop put in the merged store, in the order it put it there —
        // which is where a record relayed twice shows up as well as one lost.
        let relayed = |rx: &std::sync::mpsc::Receiver<Message>| {
            let mut kinds = Vec::new();
            while let Ok(message) = rx.try_recv() {
                if let Message::Event(envelope) = message {
                    kinds.push(envelope.kind.0.clone());
                }
            }
            kinds
        };
        let end = |token: &str, tx: &Sender<Message>| {
            end_session(
                None,
                tx,
                Some(&onevcs::SessionToken(token.to_owned())),
                &Labels::default(),
                None,
            );
        };

        // A stream that already carries its terminator is read once and answered
        // on: the wait below must cost an ordinary settlement nothing.
        let closed = "s-terminated";
        write(
            closed,
            &format!(
                "{}\n{}\n",
                record(closed, 1, "push"),
                record(closed, 2, "session-closed")
            ),
        );
        let (tx, rx) = std::sync::mpsc::channel();
        let began = Instant::now();
        end(closed, &tx);
        assert_eq!(relayed(&rx), vec!["push", "session-closed"]);
        assert!(
            began.elapsed() < TERMINATOR_GRACE,
            "a session that had already ended was waited on anyway"
        );

        // A terminator the first read did not find. Before this it was lost: the
        // one read had been made, and nothing afterwards reads a session's stream.
        let late = "s-latelyclosed";
        let pushed = record(late, 1, "push");
        let ended = record(late, 2, "session-closed");
        write(late, &format!("{pushed}\n"));
        let writing = {
            let path = path(late);
            std::thread::spawn(move || {
                std::thread::sleep(TERMINATOR_POLL * 2);
                std::fs::write(&path, format!("{pushed}\n{ended}\n"))
                    .expect("the terminator is written");
            })
        };
        let (tx, rx) = std::sync::mpsc::channel();
        end(late, &tx);
        writing.join().expect("the writer finishes");
        assert_eq!(
            relayed(&rx),
            vec!["push", "session-closed"],
            "a terminator written after the first read never reached the merged store"
        );

        // And one that never arrives: bounded, so a node cannot hang on its own
        // cleanup, and the records before it relayed exactly once however many
        // reads the wait made.
        let never = "s-neverclosed";
        write(never, &format!("{}\n", record(never, 1, "push")));
        let (tx, rx) = std::sync::mpsc::channel();
        let began = Instant::now();
        end(never, &tx);
        assert!(
            began.elapsed() >= TERMINATOR_GRACE,
            "the wait for a terminator gave up early"
        );
        assert_eq!(
            relayed(&rx),
            vec!["push"],
            "a re-read handed the same record back a second time"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_step_ordering_ignores_a_dependency_on_something_outside_the_node() {
        let node = lifecycle(Some(vec![step("only", &["elsewhere"])]));
        let steps = ordered_steps(&node).expect("an outside reference does not deadlock");
        assert_eq!(steps.len(), 1);
    }
}