loopflow 0.12.0

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
//! Shared durable control submission for Project and Task Sessions.
//!
//! The public nouns stay explicit. This module owns only the protocol that is
//! already common at both edges: persist one command, supersede or version its
//! directive atomically, wake the right child, and report the durable receipt.

use std::time::Duration;

use crate::child_session::{
    AbandonIntent, ChildBodyHandoffRequest, ChildBodyOutcome, ChildCommand, ChildCommandEffect,
    ChildCommandId, ChildCommandKind, ChildCommandSource, ChildCommandState, ChildDirective,
    ChildProcessGeneration, ChildRef,
};
use crate::project_session::{ProjectEventKind, ProjectSession, ProjectSessionStatus};
use crate::store::SharedStore;
use crate::task::{TaskEventKind, TaskSession, TaskSessionStatus};

use super::{OpsError, OpsResult};

const CHILD_STARTUP_GRACE_SECONDS: i64 = 10;
pub(crate) const CHILD_STARTUP_GRACE: Duration = Duration::from_secs(10);

#[cfg(test)]
struct BeforeLaunchHook {
    target: ChildRef,
    callback: Box<dyn FnOnce() -> OpsResult<()> + Send>,
}

#[cfg(test)]
fn _before_launch_hook() -> &'static std::sync::Mutex<Option<BeforeLaunchHook>> {
    static HOOK: std::sync::OnceLock<std::sync::Mutex<Option<BeforeLaunchHook>>> =
        std::sync::OnceLock::new();
    HOOK.get_or_init(|| std::sync::Mutex::new(None))
}

#[cfg(test)]
fn _set_before_launch_hook(
    target: ChildRef,
    callback: impl FnOnce() -> OpsResult<()> + Send + 'static,
) {
    let mut hook = _before_launch_hook()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    *hook = Some(BeforeLaunchHook {
        target,
        callback: Box::new(callback),
    });
}

#[cfg(test)]
fn _run_before_launch_hook(target: &ChildRef) -> OpsResult<()> {
    let mut guard = _before_launch_hook()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if guard.as_ref().is_none_or(|hook| hook.target != *target) {
        return Ok(());
    }
    let hook = guard.take().expect("matching test hook is present");
    drop(guard);
    (hook.callback)()
}

pub(crate) fn child_body_reservation_is_fresh(process: &ChildProcessGeneration) -> bool {
    if process.state != crate::child_session::ChildLeaseState::Reserved {
        return false;
    }
    process
        .started_at
        .checked_add(time::Duration::seconds(CHILD_STARTUP_GRACE_SECONDS))
        .is_some_and(|deadline| time::OffsetDateTime::now_utc() < deadline)
}

pub(crate) fn lost_child_body_outcome(
    process: &ChildProcessGeneration,
    reason: &str,
) -> ChildBodyOutcome {
    if process.state == crate::child_session::ChildLeaseState::Legacy {
        ChildBodyOutcome::LegacyStopped {
            reason: reason.to_string(),
        }
    } else {
        ChildBodyOutcome::Lost {
            reason: reason.to_string(),
        }
    }
}

pub(crate) async fn revoke_and_reap_child_body(
    store: &SharedStore,
    target: &ChildRef,
    outcome: ChildBodyOutcome,
) -> OpsResult<ChildProcessGeneration> {
    let revoked = match target {
        ChildRef::Project(session_id) => store
            .revoke_project_process(session_id, &outcome)
            .await
            .map_err(child_error)?,
        ChildRef::Task(session_id) => store
            .revoke_task_process(session_id, &outcome)
            .await
            .map_err(child_error)?,
    };
    reap_revoked_child_body(store, target, revoked).await
}

pub(crate) async fn reap_revoked_child_body(
    store: &SharedStore,
    target: &ChildRef,
    revoked: ChildProcessGeneration,
) -> OpsResult<ChildProcessGeneration> {
    if let Err(error) = crate::engine::process::reap_child_process(&revoked, Duration::from_secs(2))
        .await
        .map_err(child_error)
    {
        // The kill failed, and this used to return here — leaving the lease at
        // `revoked` forever, because nothing ever re-examines it and the reserve
        // CAS accepts only NULL or `finished`. But a lease exists to bar a second
        // body, and a body we can prove is gone cannot run anything, so it has no
        // claim on the lease whatever happened during the reap. Release on proof;
        // anything short of proof keeps the lease and surfaces the real failure.
        // ("refusing to reap current process group" self-classifies as `Present`:
        // that group is us.)
        return match release_dead_revoked_child_body(store, target, &revoked).await? {
            Some(finished) => Ok(finished),
            None => Err(error),
        };
    }
    finish_revoked_child_body(store, target, revoked.generation).await
}

/// Release a lease stuck at `revoked` whose body is provably gone.
///
/// `Some(finished)` only when the body probes [`Presence::Absent`]; `None` when
/// it is present or unprovable, which leaves the lease exactly as it was.
///
/// This never re-signals. A stuck lease is old by construction and a pid is a
/// recycled resource, so retrying the kill would mean sending TERM to whatever
/// inherited the number — the release path would become a way to end a
/// stranger's work. And if the body is provably gone there is nothing left to
/// kill anyway.
///
/// The store's CAS pins both the generation and `process_lease_state='revoked'`,
/// so only the same generation still awaiting reap can become `finished`.
pub(crate) async fn release_dead_revoked_child_body(
    store: &SharedStore,
    target: &ChildRef,
    revoked: &ChildProcessGeneration,
) -> OpsResult<Option<ChildProcessGeneration>> {
    if revoked.state != crate::child_session::ChildLeaseState::Revoked {
        return Ok(None);
    }
    if crate::engine::process::probe_child_body_presence(revoked).await
        != crate::engine::process::Presence::Absent
    {
        return Ok(None);
    }
    finish_revoked_child_body(store, target, revoked.generation)
        .await
        .map(Some)
}

async fn finish_revoked_child_body(
    store: &SharedStore,
    target: &ChildRef,
    generation: u32,
) -> OpsResult<ChildProcessGeneration> {
    match target {
        ChildRef::Project(session_id) => store
            .finish_revoked_project_process(session_id, generation)
            .await
            .map_err(child_error),
        ChildRef::Task(session_id) => store
            .finish_revoked_task_process(session_id, generation)
            .await
            .map_err(child_error),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ChildReceiptUntil {
    Applied,
    Incorporated,
}

#[derive(Debug)]
pub(crate) enum ChildSession {
    Project(Box<ProjectSession>),
    Task(Box<TaskSession>),
}

impl ChildSession {
    fn target(&self) -> ChildRef {
        match self {
            Self::Project(session) => ChildRef::Project(session.id.clone()),
            Self::Task(session) => ChildRef::Task(session.id.clone()),
        }
    }

    fn label(&self) -> String {
        match self {
            Self::Project(session) => format!("Project {}", session.launch.project.slug),
            Self::Task(session) => format!("Task {}", session.launch.issue.identifier),
        }
    }

    fn status(&self) -> &'static str {
        match self {
            Self::Project(session) => session.status.as_str(),
            Self::Task(session) => session.status.as_str(),
        }
    }

    fn is_terminal(&self) -> bool {
        match self {
            Self::Project(session) => session.status.is_terminal(),
            Self::Task(session) => session.status.is_terminal(),
        }
    }

    fn is_process_active(&self) -> bool {
        match self {
            Self::Project(session) => session.status.is_process_active(),
            Self::Task(session) => session.status.is_process_active(),
        }
    }

    fn agent(&self) -> &str {
        match self {
            Self::Project(session) => &session.agent,
            Self::Task(session) => &session.agent,
        }
    }

    async fn handoff(
        &mut self,
        store: &SharedStore,
        request: &ChildBodyHandoffRequest,
    ) -> OpsResult<()> {
        *self = match self {
            Self::Project(session) => Self::Project(Box::new(
                store
                    .handoff_project_body(&session.id, request)
                    .await
                    .map_err(child_error)?,
            )),
            Self::Task(session) => Self::Task(Box::new(
                store
                    .handoff_task_body(&session.id, request)
                    .await
                    .map_err(child_error)?,
            )),
        };
        Ok(())
    }

    async fn supervisor_restart_bar(&self, store: &SharedStore) -> OpsResult<Option<String>> {
        match self {
            Self::Project(session) => Ok(session.supervisor_restart_bar()),
            Self::Task(session) => {
                let pr = store
                    .active_task_pr(&session.id)
                    .await
                    .map_err(child_error)?;
                Ok(session.supervisor_restart_bar(pr.as_ref()))
            }
        }
    }

    /// The `ci-fix` wake bar. Task-only: it permits the open-PR restart the
    /// supervisor bar forbids, but only on a warranted current-head failure. A
    /// Project is never woken this way, so it falls back to the supervisor bar.
    async fn ci_fix_restart_bar(&self, store: &SharedStore) -> OpsResult<Option<String>> {
        match self {
            Self::Project(session) => Ok(session.supervisor_restart_bar()),
            Self::Task(session) => {
                let pr = store
                    .active_task_pr(&session.id)
                    .await
                    .map_err(child_error)?;
                Ok(session.ci_fix_restart_bar(pr.as_ref()))
            }
        }
    }

    /// The automatic-recovery bar: terminal and abandoning work only.
    ///
    /// Unlike the supervisor bar, this does **not** consult the PR phase. A
    /// strand is decided by durable status — `plan_stranded_recovery` only ever
    /// reaches a launch for a Session whose status claims a body that does not
    /// exist, and delivered work parks at `Waiting`, which it never selects. So
    /// the open-PR/W2-129 bar is already honoured upstream, and re-applying it
    /// here would refuse exactly the crashed-mid-publication strands this path
    /// exists to recover (their PR phase moves to `Open` after the fact, when
    /// the receipt is finally observed).
    fn recovery_restart_bar(&self) -> Option<String> {
        match self {
            Self::Project(session) => session.supervisor_restart_bar(),
            Self::Task(session) => session.terminal_or_abandon_bar(),
        }
    }

    fn current_directive_version(&self) -> u32 {
        match self {
            Self::Project(session) => session.current_directive_version,
            Self::Task(session) => session.current_directive_version,
        }
    }

    fn set_current_directive_version(&mut self, version: u32) {
        match self {
            Self::Project(session) => session.current_directive_version = version,
            Self::Task(session) => session.current_directive_version = version,
        }
    }

    async fn refresh(&mut self, store: &SharedStore) -> OpsResult<()> {
        *self = match self {
            Self::Project(session) => Self::Project(Box::new(
                store
                    .get_project_session(&session.id)
                    .await
                    .map_err(child_error)?
                    .ok_or_else(|| child_error("Project Session disappeared"))?,
            )),
            Self::Task(session) => Self::Task(Box::new(
                store
                    .get_task_session(&session.id)
                    .await
                    .map_err(child_error)?
                    .ok_or_else(|| child_error("Task Session disappeared"))?,
            )),
        };
        Ok(())
    }

    fn record_abandon_intent(&mut self, intent: AbandonIntent) {
        match self {
            Self::Project(session) => session.abandon_intent = Some(intent),
            Self::Task(session) => session.abandon_intent = Some(intent),
        }
    }

    fn abandon_intent_reason(&self) -> Option<String> {
        let intent = match self {
            Self::Project(session) => session.abandon_intent.as_ref(),
            Self::Task(session) => session.abandon_intent.as_ref(),
        };
        intent.map(|intent| {
            format!(
                "{} is being abandoned: {}",
                self.label(),
                intent.reason.clone()
            )
        })
    }

    /// Start a process generation, unless this Session's own state forbids it.
    ///
    /// `intent` decides how much is forbidden. A supervisor — a project waking on
    /// a task observation, a queued steer, an internal retry — may not restart
    /// delivered or abandoning work. An operator typing `lf task resume` may
    /// restart delivered work (that is how review feedback gets answered), but
    /// not abandoning work.
    async fn launch(&mut self, store: &SharedStore, intent: LaunchIntent) -> OpsResult<()> {
        let bar = match intent {
            LaunchIntent::Supervisor => self.supervisor_restart_bar(store).await?,
            LaunchIntent::ExplicitResume => self.abandon_intent_reason(),
            LaunchIntent::CiFix => self.ci_fix_restart_bar(store).await?,
            LaunchIntent::Recovery => self.recovery_restart_bar(),
        };
        if let Some(bar) = bar {
            return Err(child_error(bar));
        }
        match self {
            Self::Project(session) => super::project::launch_project_process(store, session).await,
            Self::Task(session) => super::task::relaunch_inactive_process(store, session).await,
        }
    }

    async fn append_command_event(
        &self,
        store: &SharedStore,
        command_id: ChildCommandId,
        state: ChildCommandState,
        effect: Option<ChildCommandEffect>,
        error: Option<String>,
    ) -> OpsResult<()> {
        match self {
            Self::Project(session) => store
                .append_project_event(
                    &session.id,
                    &ProjectEventKind::CommandChanged {
                        command_id,
                        state,
                        effect,
                        error,
                    },
                )
                .await
                .map(|_| ())
                .map_err(child_error),
            Self::Task(session) => store
                .append_task_event(
                    &session.id,
                    &TaskEventKind::CommandChanged {
                        command_id,
                        state,
                        effect,
                        error,
                    },
                )
                .await
                .map(|_| ())
                .map_err(child_error),
        }
    }

    async fn append_directive_event(
        &self,
        store: &SharedStore,
        directive: &ChildDirective,
    ) -> OpsResult<()> {
        match self {
            Self::Project(session) => store
                .append_project_event(
                    &session.id,
                    &ProjectEventKind::DirectiveChanged {
                        directive_id: directive.id.clone(),
                        version: directive.version,
                        directive_kind: directive.kind,
                    },
                )
                .await
                .map(|_| ())
                .map_err(child_error),
            Self::Task(session) => store
                .append_task_event(
                    &session.id,
                    &TaskEventKind::DirectiveChanged {
                        directive_id: directive.id.clone(),
                        version: directive.version,
                        directive_kind: directive.kind,
                    },
                )
                .await
                .map(|_| ())
                .map_err(child_error),
        }
    }

    /// Record that an interrupt landed on a Session whose process was already gone.
    ///
    /// Without this the command is accepted silently: the receipt says `accepted`
    /// while `lf task show` still reads whatever it read before, so an operator
    /// cannot tell an interrupt that landed from one that evaporated. A delivered
    /// (`Open`) Session keeps its status — interrupting it must not erase the
    /// fact that its PR is open.
    async fn record_interrupt_of_inactive_process(&mut self, store: &SharedStore) -> OpsResult<()> {
        let reason = "interrupted while no process was running; \
                      resume the Session to start one"
            .to_string();
        match self {
            Self::Project(session) => {
                let from = session.status;
                session.set_status(ProjectSessionStatus::Waiting, reason);
                store
                    .update_project_session(session)
                    .await
                    .map_err(child_error)?;
                store
                    .append_project_event(
                        &session.id,
                        &ProjectEventKind::StatusChanged {
                            from,
                            to: ProjectSessionStatus::Waiting,
                            reason: session.status_reason.clone(),
                        },
                    )
                    .await
                    .map_err(child_error)?;
            }
            Self::Task(session) => {
                let submitted = store
                    .active_task_pr(&session.id)
                    .await
                    .map_err(child_error)?
                    .is_some_and(|pr| pr.phase() == crate::task::PrPhase::Open);
                if submitted {
                    return Ok(());
                }
                let from = session.status;
                session.set_status(TaskSessionStatus::Waiting, reason);
                store
                    .update_task_session(session)
                    .await
                    .map_err(child_error)?;
                store
                    .append_task_event(
                        &session.id,
                        &TaskEventKind::StatusChanged {
                            from,
                            to: TaskSessionStatus::Waiting,
                            reason: session.status_reason.clone(),
                        },
                    )
                    .await
                    .map_err(child_error)?;
            }
        }
        Ok(())
    }

    async fn abandon(&mut self, store: &SharedStore, reason: &str) -> OpsResult<()> {
        match self {
            Self::Project(session) => {
                let from = session.status;
                session.set_status(
                    ProjectSessionStatus::Abandoned,
                    format!("Project Session explicitly abandoned: {reason}"),
                );
                store
                    .update_project_session(session)
                    .await
                    .map_err(child_error)?;
                store
                    .append_project_event(
                        &session.id,
                        &ProjectEventKind::StatusChanged {
                            from,
                            to: ProjectSessionStatus::Abandoned,
                            reason: session.status_reason.clone(),
                        },
                    )
                    .await
                    .map_err(child_error)?;
            }
            Self::Task(session) => {
                let from = session.status;
                session.set_status(
                    TaskSessionStatus::Abandoned,
                    format!("Task Session explicitly abandoned: {reason}"),
                );
                store
                    .update_task_session(session)
                    .await
                    .map_err(child_error)?;
                store
                    .append_task_event(
                        &session.id,
                        &TaskEventKind::StatusChanged {
                            from,
                            to: TaskSessionStatus::Abandoned,
                            reason: session.status_reason.clone(),
                        },
                    )
                    .await
                    .map_err(child_error)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChildControlResult {
    pub session_id: String,
    pub command_id: String,
    pub directive_version: Option<u32>,
    pub state: ChildCommandState,
    pub effect: Option<ChildCommandEffect>,
    pub incorporated: bool,
    pub generation: Option<u32>,
    pub accepted_at: Option<time::OffsetDateTime>,
    pub incorporated_at: Option<time::OffsetDateTime>,
    pub error: Option<String>,
}

/// Who is asking for a process, which decides what state may refuse them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LaunchIntent {
    Supervisor,
    ExplicitResume,
    /// An automated `ci-fix` wake, carried by a durable `ChildCommandKind::CiFix`.
    /// Allowed past the open-PR bar, but only when the active PR carries a
    /// current-head required-check failure (`TaskSession::ci_fix_restart_bar`).
    /// The bar decides legality; the command ledger decides whether this wake has
    /// already fired.
    CiFix,
    /// Automatic recovery of a Session whose body died while its status still
    /// claimed one. Barred only by terminal and abandoning work; the strand
    /// predicate upstream (`plan_stranded_recovery`) is what keeps it off
    /// delivered work.
    Recovery,
}

/// Re-dispatch a Task Session whose body died, with no human asking.
///
/// The one automatic path for a strand. Barred only by terminal and abandoning
/// work — see [`ChildSession::recovery_restart_bar`] for why the PR phase is
/// deliberately not consulted here.
pub(crate) async fn redispatch_task_body(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<()> {
    let mut child = ChildSession::Task(Box::new(session.clone()));
    child.launch(store, LaunchIntent::Recovery).await?;
    if let ChildSession::Task(relaunched) = child {
        *session = *relaunched;
    }
    Ok(())
}

pub(crate) async fn resume_session(
    store: &SharedStore,
    mut session: ChildSession,
    source: ChildCommandSource,
    message: Option<String>,
    model: Option<String>,
    reason: Option<String>,
) -> OpsResult<ChildControlResult> {
    if let Some(model) = model {
        let request = handoff_request(&model, reason.as_deref())?;
        if session.agent() != request.agent {
            if !matches!(&source, ChildCommandSource::Human) {
                if let Some(bar) = session.supervisor_restart_bar(store).await? {
                    return Err(child_error(bar));
                }
            }
            session.handoff(store, &request).await?;
        }
    }
    queue_command(store, session, source, ChildCommandKind::Resume { message }).await
}

fn handoff_request(model: &str, reason: Option<&str>) -> OpsResult<ChildBodyHandoffRequest> {
    let agent = model.trim();
    if agent.is_empty() {
        return Err(child_error("handoff model cannot be empty"));
    }
    let (provider, model_name) = agent
        .split_once(':')
        .map_or((agent, None), |(provider, model_name)| {
            (provider, Some(model_name))
        });
    let provider = crate::harness::canonical_harness(provider)
        .ok_or_else(|| child_error(format!("unsupported session harness: {provider}")))?;
    let agent = match model_name {
        Some(model_name) if model_name.trim().is_empty() => {
            return Err(child_error("handoff model name cannot be empty"));
        }
        Some(model_name) => format!("{provider}:{}", model_name.trim()),
        None => provider.to_string(),
    };
    let reason = reason
        .unwrap_or("operator requested provider handoff")
        .trim();
    if reason.is_empty() {
        return Err(child_error("handoff reason cannot be empty"));
    }
    Ok(ChildBodyHandoffRequest {
        agent,
        provider: provider.to_string(),
        reason: reason.to_string(),
    })
}

/// Whether a deduplicated command should relaunch an inactive Session.
///
/// A `Decide` re-sent by a human means "run this" — an unsettled one relaunches.
/// A `CiFix` is re-sent by a *supervision pass*, not a person, so the same rule
/// would spin a body on every poll for as long as the repair is unsettled. It
/// keys on `Persisted` instead: nobody ever claimed that wake, so the launch that
/// should have consumed it never happened. Once it is `Claimed`, a generation
/// owns the repair, and a dead one is recovery's problem — recovery re-enters
/// ci-fix and reclaims this same command.
fn relaunch_on_duplicate(command: &ChildCommand) -> bool {
    match &command.kind {
        ChildCommandKind::CiFix { .. } => command.state == ChildCommandState::Persisted,
        _ => !command.state.is_terminal(),
    }
}

pub(crate) async fn queue_command(
    store: &SharedStore,
    mut session: ChildSession,
    source: ChildCommandSource,
    kind: ChildCommandKind,
) -> OpsResult<ChildControlResult> {
    if session.is_terminal() {
        return Err(child_error(format!(
            "{} is {}; terminal Sessions cannot accept commands",
            session.label(),
            session.status()
        )));
    }
    // Abandonment is decided the moment it is requested. Between that moment and
    // the runner consuming the command, the Session must accept nothing else —
    // otherwise a steer arriving in the gap relaunches work someone just ended.
    if !matches!(kind, ChildCommandKind::Abandon { .. }) {
        if let Some(bar) = session.abandon_intent_reason() {
            return Err(child_error(bar));
        }
    }

    // Only an operator's explicit resume may restart delivered work.
    let launch_intent = match (&kind, &source) {
        (ChildCommandKind::Resume { .. }, ChildCommandSource::Human) => {
            LaunchIntent::ExplicitResume
        }
        (ChildCommandKind::CiFix { .. }, _) => LaunchIntent::CiFix,
        _ => LaunchIntent::Supervisor,
    };

    // Move 2 (fast bar): a supervisor `Resume` of a non-active body that is
    // already barred (open PR / publishing / terminal) refuses *before* any
    // command row is created, so the steady-state refusal — the common W2-319
    // case where the PR is already Open — writes nothing to the ledger.
    // (Operator `ExplicitResume` is abandon-only and answers review; `CiFix`
    // owns its own persist-then-bar attribution.)
    if matches!(kind, ChildCommandKind::Resume { .. })
        && launch_intent == LaunchIntent::Supervisor
        && !session.is_process_active()
    {
        if let Some(bar) = session.supervisor_restart_bar(store).await? {
            return Err(child_error(bar));
        }
    }

    let command = ChildCommand::new(session.target(), source, kind);
    // A ci-fix wake is fire-and-forget like a follow-up: the supervision pass
    // that observed the failure must not block on a body's boot.
    let wait_for_resolution = !matches!(
        &command.kind,
        ChildCommandKind::FollowUp { .. } | ChildCommandKind::CiFix { .. }
    );
    let replacement = match &command.kind {
        ChildCommandKind::Steer { text } => Some(text.clone()),
        ChildCommandKind::Interrupt {
            replacement: Some(text),
        } => Some(text.clone()),
        _ => None,
    };

    let (command, created, superseded, directive) = if let Some(text) = replacement {
        let directive = ChildDirective::replacement(
            session.target(),
            session.current_directive_version() + 1,
            text,
            command.source.clone(),
            command.id.clone(),
        );
        let superseded = store
            .create_child_command_with_directive(&command, &directive)
            .await
            .map_err(child_error)?;
        session.set_current_directive_version(directive.version);
        (command, true, superseded, Some(directive))
    } else if matches!(&command.kind, ChildCommandKind::Decide { .. }) {
        let (command, created) = store
            .ensure_child_decision_command(&command)
            .await
            .map_err(child_error)?;
        (command, created, Vec::new(), None)
    } else if matches!(&command.kind, ChildCommandKind::CiFix { .. }) {
        let (command, created) = store
            .ensure_child_ci_fix_command(&command)
            .await
            .map_err(child_error)?;
        (command, created, Vec::new(), None)
    } else if matches!(&command.kind, ChildCommandKind::Interrupt { .. }) {
        let superseded = store
            .supersede_and_create_child_command(&command)
            .await
            .map_err(child_error)?;
        (command, true, superseded, None)
    } else if let ChildCommandKind::Abandon { reason } = &command.kind {
        // The intent lands with the command, in one transaction. From here on
        // every launch path reads it and refuses to start a process.
        let intent = AbandonIntent {
            requested_at: time::OffsetDateTime::now_utc(),
            reason: reason.clone(),
        };
        store
            .create_child_abandon_command(&command, &intent)
            .await
            .map_err(child_error)?;
        session.record_abandon_intent(intent);
        (command, true, Vec::new(), None)
    } else {
        store
            .create_child_command(&command)
            .await
            .map_err(child_error)?;
        (command, true, Vec::new(), None)
    };

    // Link the wake to its evidence before anything can service it.
    //
    // Launching is what leads to a body, and a body stamps `responded_at` the
    // moment it arms. Linking after the launch returns leaves a window — widened
    // by `wait_for_resolution = false`, which returns without waiting — where a
    // crash strands an incident reading "responded, trigger unknown": the one
    // state the recovery ledger exists to make impossible. The durable order is
    // incident exists -> command ensure -> trigger link -> launch/claim/respond.
    //
    // Runs on the duplicate path too: `ensure_` returned the surviving command, so
    // this re-links the same id and the COALESCE makes it a no-op.
    //
    // The link must actually land. `mark_ci_incident_triggered` reports whether an
    // incident matched, and a missed link is refused rather than logged: launching
    // anyway would produce exactly the unattributable body this ordering exists to
    // prevent, and the caller would have no way to know.
    if let ChildCommandKind::CiFix {
        incident_identity, ..
    } = &command.kind
    {
        let linked = store
            .mark_ci_incident_triggered(
                incident_identity,
                &command.id,
                time::OffsetDateTime::now_utc(),
            )
            .await
            .map_err(child_error)?;
        if !linked {
            return Err(child_error(format!(
                "ci-fix wake {} names incident {incident_identity}, which is not recorded; \
                 the observation that opens an incident must run before its wake is enqueued. \
                 Refusing to launch a repair nothing can attribute.",
                command.id
            )));
        }
    }

    if !created {
        if relaunch_on_duplicate(&command) && !session.is_process_active() {
            session.launch(store, launch_intent).await?;
        }
        let receipt = resolve_receipt(store, &command.id, wait_for_resolution).await?;
        return control_result(store, &command, receipt).await;
    }

    for command_id in superseded {
        session
            .append_command_event(store, command_id, ChildCommandState::Superseded, None, None)
            .await?;
    }
    if let Some(directive) = &directive {
        session.append_directive_event(store, directive).await?;
    }
    session
        .append_command_event(
            store,
            command.id.clone(),
            ChildCommandState::Persisted,
            command.effect,
            None,
        )
        .await?;

    // The unit fixture interposes here to make the real post-persist/pre-launch
    // PR race deterministic. Production builds contain no hook.
    #[cfg(test)]
    _run_before_launch_hook(&command.target)?;

    if let ChildCommandKind::Abandon { reason } = &command.kind {
        if !session.is_process_active() {
            store
                .accept_child_command(&command.id, None)
                .await
                .map_err(child_error)?;
            session
                .append_command_event(
                    store,
                    command.id.clone(),
                    ChildCommandState::Accepted,
                    None,
                    None,
                )
                .await?;
            session.abandon(store, reason).await?;
            let receipt = read_receipt(store, &command.id).await?;
            return control_result(store, &command, receipt).await;
        }
    }

    // Interrupt never starts a process. It ends the current turn; it does not
    // begin one. Interrupting an inactive Session used to relaunch it whenever a
    // replacement rode along — the exact path that respawned a Session under
    // whatever binary the interrupting shell happened to be using. The
    // replacement lands as the pending directive, and `resume` is the one verb
    // that starts a process.
    if matches!(&command.kind, ChildCommandKind::Interrupt { .. }) && !session.is_process_active() {
        store
            .accept_child_command(&command.id, None)
            .await
            .map_err(child_error)?;
        session
            .append_command_event(
                store,
                command.id.clone(),
                ChildCommandState::Accepted,
                None,
                None,
            )
            .await?;
        session.record_interrupt_of_inactive_process(store).await?;
        let receipt = read_receipt(store, &command.id).await?;
        return control_result(store, &command, receipt).await;
    }

    if !session.is_process_active() {
        if let Err(bar) = session.launch(store, launch_intent).await {
            // Move 2 (terminalize on race): the fast bar and `launch`'s own bar
            // read the PR at different instants, so a `Working → Open` flip after
            // creation can leave this just-created supervisor `Resume` barred and
            // `Persisted`. `launch` bars *before* reserving a generation, so the
            // generation is unchanged; terminalize the still-`Persisted` command
            // to `Failed` (pre-delivery rejection — `fail_child_command` matches
            // only `claimed`/`delivering` and cannot) so no orphan remains.
            if matches!(&command.kind, ChildCommandKind::Resume { .. }) {
                store
                    .reject_persisted_child_command(&command.id, bar.to_string())
                    .await
                    .map_err(child_error)?;
                session
                    .append_command_event(
                        store,
                        command.id.clone(),
                        ChildCommandState::Failed,
                        command.effect,
                        Some(bar.to_string()),
                    )
                    .await?;
            }
            return Err(bar);
        }
    }
    let mut receipt = resolve_receipt(store, &command.id, wait_for_resolution).await?;
    if matches!(
        receipt.state,
        ChildCommandState::Persisted | ChildCommandState::Claimed | ChildCommandState::Delivering
    ) {
        session.refresh(store).await?;
        if !session.is_process_active() && !session.is_terminal() {
            session.launch(store, launch_intent).await?;
            receipt = resolve_receipt(store, &command.id, wait_for_resolution).await?;
        }
    }
    control_result(store, &command, receipt).await
}

pub(crate) async fn control_result(
    store: &SharedStore,
    command: &ChildCommand,
    receipt: ChildCommand,
) -> OpsResult<ChildControlResult> {
    let directive = store
        .child_directive_for_command(&command.id)
        .await
        .map_err(child_error)?;
    Ok(ChildControlResult {
        session_id: command.target.target_id().to_string(),
        command_id: command.id.to_string(),
        directive_version: directive.as_ref().map(|directive| directive.version),
        state: receipt.state,
        effect: receipt.effect,
        incorporated: directive
            .as_ref()
            .is_some_and(|directive| directive.incorporated_at.is_some()),
        generation: receipt.claimed_by_generation,
        accepted_at: receipt.accepted_at,
        incorporated_at: directive.and_then(|directive| directive.incorporated_at),
        error: receipt.error,
    })
}

async fn resolve_receipt(
    store: &SharedStore,
    command_id: &ChildCommandId,
    wait: bool,
) -> OpsResult<ChildCommand> {
    if wait {
        Ok(wait_for_receipt(store, command_id, Duration::from_secs(2))
            .await?
            .0)
    } else {
        read_receipt(store, command_id).await
    }
}

pub(crate) async fn read_receipt(
    store: &SharedStore,
    command_id: &ChildCommandId,
) -> OpsResult<ChildCommand> {
    store
        .get_child_command(command_id)
        .await
        .map_err(child_error)?
        .ok_or_else(|| child_error(format!("child command {command_id} disappeared")))
}

pub(crate) async fn wait_for_receipt(
    store: &SharedStore,
    command_id: &ChildCommandId,
    timeout: Duration,
) -> OpsResult<(ChildCommand, bool)> {
    let deadline = tokio::time::Instant::now() + timeout;
    loop {
        let command = read_receipt(store, command_id).await?;
        if command.state.is_terminal() {
            return Ok((command, false));
        }
        if tokio::time::Instant::now() >= deadline {
            return Ok((command, true));
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
}

pub(crate) async fn wait_for_receipt_condition(
    store: &SharedStore,
    command_id: &ChildCommandId,
    until: ChildReceiptUntil,
    timeout: Duration,
) -> OpsResult<(ChildCommand, bool)> {
    let deadline = tokio::time::Instant::now() + timeout;
    loop {
        let command = read_receipt(store, command_id).await?;
        if matches!(
            command.state,
            ChildCommandState::Failed
                | ChildCommandState::Superseded
                | ChildCommandState::Uncertain
        ) {
            return Ok((command, false));
        }
        let settled = match until {
            ChildReceiptUntil::Applied => command.state.is_terminal(),
            ChildReceiptUntil::Incorporated => store
                .child_directive_for_command(command_id)
                .await
                .map_err(child_error)?
                .ok_or_else(|| {
                    child_error(format!(
                        "child command {command_id} does not carry a directive to incorporate"
                    ))
                })?
                .incorporated_at
                .is_some(),
        };
        if settled {
            return Ok((command, false));
        }
        if tokio::time::Instant::now() >= deadline {
            return Ok((command, true));
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
}

fn child_error(error: impl std::fmt::Display) -> OpsError {
    OpsError::Message(error.to_string())
}

#[cfg(test)]
mod tests {
    use std::io::{BufRead, BufReader};
    use std::os::unix::process::CommandExt;
    use std::sync::Arc;

    use time::OffsetDateTime;

    use crate::child_session::{
        ChildBodyOutcome, ChildCommand, ChildCommandKind, ChildCommandSource, ChildCommandState,
        ChildLeaseState, ChildProcessGeneration, ChildRef,
    };
    use crate::id::WaveId;
    use crate::project_session::{
        ProjectEventKind, ProjectSession, ProjectSessionId, ProjectSessionStatus,
    };
    use crate::session_context::{
        LinearIssueId, LinearIssueSnapshot, LinearProjectId, LinearProjectSnapshot,
        ProjectLaunchReceipt, TaskLaunchReceipt,
    };
    use crate::store::{open_store, StorageConfig};
    use crate::task::{
        GithubPr, PrPublication, TaskEventKind, TaskPr, TaskPrId, TaskSessionStatus,
    };
    use crate::wave::Wave;

    use super::{
        _set_before_launch_hook, child_body_reservation_is_fresh, handoff_request, queue_command,
        relaunch_on_duplicate, resume_session, revoke_and_reap_child_body, ChildSession,
    };

    #[test]
    fn a_fresh_reservation_is_adopted_while_a_stale_one_can_be_reaped() {
        let mut process = ChildProcessGeneration {
            generation: 1,
            pid: None,
            process_group_id: None,
            tmux_name: "starting".to_string(),
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: None,
            started_at: OffsetDateTime::now_utc(),
            state: crate::child_session::ChildLeaseState::Reserved,
            outcome: None,
            provenance: None,
        };
        assert!(child_body_reservation_is_fresh(&process));
        process.started_at -= time::Duration::seconds(11);
        assert!(!child_body_reservation_is_fresh(&process));
    }

    #[tokio::test]
    async fn recovery_reaps_the_old_process_group_before_reserving_its_successor() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();
        let mut task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        store
            .create_task_session(&task, &make_task_pr(&task))
            .await
            .unwrap();
        task.begin_generation("recovery-body".to_string());
        let lease = store
            .reserve_task_process(&task, TaskSessionStatus::Waiting)
            .await
            .unwrap()
            .expect("reserve generation one");

        let mut child = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg("sleep 60 & echo $!; wait")
            .process_group(0)
            .stdout(std::process::Stdio::piped())
            .spawn()
            .expect("spawn isolated body process group");
        let group = child.id();
        let stdout = child.stdout.take().expect("capture grandchild pid");
        let mut line = String::new();
        BufReader::new(stdout)
            .read_line(&mut line)
            .expect("read grandchild pid");
        let grandchild: u32 = line.trim().parse().expect("grandchild pid");
        let waiter = std::thread::spawn(move || child.wait().expect("reap shell"));

        let process = task.latest_process.as_mut().expect("reserved process");
        process.pid = Some(group);
        process.process_group_id = Some(group);
        process.state = ChildLeaseState::Active;
        task.set_status(TaskSessionStatus::Running, "fake provider is alive");
        store.activate_task_process(&task, &lease).await.unwrap();

        let finished = revoke_and_reap_child_body(
            &store,
            &ChildRef::Task(task.id.clone()),
            ChildBodyOutcome::Superseded {
                reason: "deterministic recovery".to_string(),
            },
        )
        .await
        .unwrap();
        waiter.join().unwrap();
        assert_eq!(finished.state, ChildLeaseState::Finished);
        // SAFETY: signal 0 is an existence probe and uses no pointers.
        assert_ne!(unsafe { libc::kill(group as i32, 0) }, 0);
        // SAFETY: signal 0 is an existence probe and uses no pointers.
        assert_ne!(unsafe { libc::kill(grandchild as i32, 0) }, 0);

        let mut stopped = store.get_task_session(&task.id).await.unwrap().unwrap();
        stopped.set_status(TaskSessionStatus::Waiting, "old body fully reaped");
        store.update_task_session(&stopped).await.unwrap();
        let mut successor = store.get_task_session(&task.id).await.unwrap().unwrap();
        assert_eq!(
            successor.begin_generation("recovery-successor".to_string()),
            2
        );
        assert!(store
            .reserve_task_process(&successor, TaskSessionStatus::Waiting)
            .await
            .unwrap()
            .is_some());
    }

    fn make_wave(repo: &str) -> Wave {
        let id = WaveId::new();
        Wave::new(id.clone(), format!("wave-{id}"), repo.to_string())
    }

    fn make_project(wave: &Wave, status: ProjectSessionStatus) -> ProjectSession {
        let now = OffsetDateTime::now_utc();
        let active = status.is_process_active();
        ProjectSession {
            id: ProjectSessionId::new(),
            launch: ProjectLaunchReceipt {
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new(format!("project-{}", WaveId::new())).unwrap(),
                    slug: format!("project-{}", WaveId::new()),
                    name: "Child control".to_string(),
                    prompt_context: "Keep one control protocol.".to_string(),
                },
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            wave_id: wave.id().clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status,
            status_reason: "test project session".to_string(),
            status_at: now,
            iteration: 1,
            observation_cursor: 0,
            last_state_fingerprint: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: active.then(|| "thread-project".to_string()),
            latest_process: active.then_some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "lf-project-test".to_string(),
                agent: "codex".to_string(),
                provider: "codex".to_string(),
                provider_session_id: active.then(|| "thread-project".to_string()),
                started_at: now,
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        }
    }

    fn make_task(
        wave: &Wave,
        project: &ProjectSession,
        status: TaskSessionStatus,
    ) -> crate::task::TaskSession {
        let now = OffsetDateTime::now_utc();
        let active = status.is_process_active();
        let id = WaveId::new();
        crate::task::TaskSession {
            id: crate::task::TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(format!("issue-{id}")).unwrap(),
                    identifier: "W2-129".to_string(),
                    title: "Terminal intent dominates process liveness".to_string(),
                    description: "Delivered work must not restart itself.".to_string(),
                },
                project: project.launch.project.clone(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: crate::task::PmWritebackState::Current,
            wave_id: wave.id().clone(),
            project_session_id: project.id.clone(),
            current_directive_version: 1,
            incorporated_directive_version: 0,
            status,
            status_reason: "test task session".to_string(),
            status_at: now,
            worktree: std::path::PathBuf::from(format!("/tmp/loopflow.{id}")),
            workspace_slug: format!("test-{id}"),
            lifecycle: crate::task::TaskLifecyclePlan::standard("task"),
            lifecycle_phase: crate::task::TaskLifecyclePhase::Iterate,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent: "claude".to_string(),
            provider: "claude".to_string(),
            provider_session_id: active.then(|| "thread-task".to_string()),
            observation: crate::task::Observation::NotRequired,
            latest_process: active.then_some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "lf-task-test".to_string(),
                agent: "claude".to_string(),
                provider: "claude".to_string(),
                provider_session_id: active.then(|| "thread-task".to_string()),
                started_at: now,
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        }
    }

    fn make_task_pr(task: &crate::task::TaskSession) -> TaskPr {
        TaskPr {
            id: TaskPrId::new(),
            task_session_id: task.id.clone(),
            sequence: 1,
            slug: task.workspace_slug.clone(),
            branch: format!("test/{}", task.workspace_slug),
            base_commit: "0".repeat(40),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: task.created_at,
            updated_at: task.updated_at,
        }
    }

    #[tokio::test]
    async fn project_follow_up_returns_once_durable() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let result = queue_command(
            &store,
            ChildSession::Project(Box::new(project)),
            ChildCommandSource::Human,
            ChildCommandKind::FollowUp {
                text: "Inspect the boundary next".to_string(),
            },
        )
        .await
        .unwrap();

        assert_eq!(result.state, ChildCommandState::Persisted);
        assert_eq!(result.accepted_at, None);
    }

    #[tokio::test]
    async fn inactive_project_abandonment_does_not_launch_a_process() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Created);
        let project_id = project.id.clone();
        store.create_project_session(&project).await.unwrap();

        let result = queue_command(
            &store,
            ChildSession::Project(Box::new(project)),
            ChildCommandSource::Human,
            ChildCommandKind::Abandon {
                reason: "The measured bet no longer matters".to_string(),
            },
        )
        .await
        .unwrap();
        let persisted = store
            .get_project_session(&project_id)
            .await
            .unwrap()
            .unwrap();

        assert_eq!(result.state, ChildCommandState::Accepted);
        assert_eq!(persisted.status, ProjectSessionStatus::Abandoned);
        assert_eq!(persisted.latest_process, None);
    }

    #[tokio::test]
    async fn interrupting_an_inactive_project_does_not_launch_a_process() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Waiting);
        let project_id = project.id.clone();
        store.create_project_session(&project).await.unwrap();

        let result = queue_command(
            &store,
            ChildSession::Project(Box::new(project)),
            ChildCommandSource::Human,
            ChildCommandKind::Interrupt { replacement: None },
        )
        .await
        .unwrap();
        let persisted = store
            .get_project_session(&project_id)
            .await
            .unwrap()
            .unwrap();

        assert_eq!(result.state, ChildCommandState::Accepted);
        assert_eq!(persisted.status, ProjectSessionStatus::Waiting);
        assert_eq!(persisted.latest_process, None);
    }

    /// The 2026-07-14 W2-129 sequence, preserved as a regression.
    ///
    /// Task Session `ts_c33d8dc7…` emitted `pull_request_opened` for #878 and went
    /// `submitted` with no live process. Supervision then launched generation 2
    /// and drove it back to `running` at `task_clarify` — re-deriving a design
    /// whose PR was already open for review, because `Open` is neither
    /// terminal nor process-active and so reads exactly like a Session that
    /// merely stopped.
    ///
    /// Terminal intent dominates process liveness: delivered work is not a
    /// restart candidate, whatever the liveness fields say.
    #[tokio::test]
    async fn a_submitted_task_with_an_open_pr_is_never_restarted_by_supervision() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let mut pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();
        pr.publication = Some(PrPublication {
            requested_at: pr.updated_at,
            after_merge: crate::task::AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 878,
                url: "https://github.com/loopflow/loopflow/pull/878".to_string(),
                head_sha: None,
            }),
        });
        store.update_task_pr(&pr).await.unwrap();
        let task_id = task.id.clone();

        // The supervisor's steer: exactly the path the Project wake took.
        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task)),
            ChildCommandSource::Project(project.id.clone()),
            ChildCommandKind::Steer {
                text: "Keep going on the design".to_string(),
            },
        )
        .await
        .expect_err("supervision must not restart a submitted Task");

        assert!(
            error.to_string().contains("#878"),
            "the refusal should name the open PR, got: {error}"
        );

        // No generation 2, and the Session still reads as delivered.
        let persisted = store.get_task_session(&task_id).await.unwrap().unwrap();
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);
        assert_eq!(persisted.latest_process, None);
    }

    /// Move 2 (fast bar): a supervisor `Resume` of a submitted Task refuses
    /// *before* creating any command, so the steady-state open-PR case — the
    /// exact W2-319 shape — leaves the command ledger empty rather than stranding
    /// an inert `Persisted` row. Sabotage that deletes the fast bar would create
    /// the command, then `launch` would bar, leaving it `Persisted` and failing
    /// the `is_empty` assertion.
    #[tokio::test]
    async fn a_supervisor_resume_of_an_open_pr_refuses_before_creating_a_command() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let mut pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();
        pr.publication = Some(PrPublication {
            requested_at: pr.updated_at,
            after_merge: crate::task::AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 1077,
                url: "https://github.com/loopflow/loopflow/pull/1077".to_string(),
                head_sha: None,
            }),
        });
        store.update_task_pr(&pr).await.unwrap();
        let target = ChildRef::Task(task.id.clone());
        let task_id = task.id.clone();

        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task)),
            ChildCommandSource::Wave(wave.id().clone()),
            ChildCommandKind::Resume { message: None },
        )
        .await
        .expect_err("a supervisor cannot restart a submitted Task");
        assert!(
            error.to_string().contains("#1077") && error.to_string().contains("reviewer"),
            "the refusal names the open PR and the real owner: {error}"
        );

        // Nothing was queued: no command row, and no generation started.
        assert!(
            store.list_child_commands(&target).await.unwrap().is_empty(),
            "the barred supervisor Resume left no command in the ledger"
        );
        let persisted = store.get_task_session(&task_id).await.unwrap().unwrap();
        assert_eq!(persisted.latest_process, None);
    }

    #[tokio::test]
    async fn a_working_to_open_race_rejects_the_persisted_resume() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let generation_before = task.latest_process.as_ref().map(|body| body.generation);
        let pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();
        let target = ChildRef::Task(task.id.clone());
        let task_id = task.id.clone();
        let flip_store = store.clone();
        let mut open_pr = pr;

        _set_before_launch_hook(target.clone(), move || {
            std::thread::spawn(move || {
                let runtime = tokio::runtime::Runtime::new().unwrap();
                runtime.block_on(async move {
                    open_pr.publication = Some(PrPublication {
                        requested_at: open_pr.updated_at,
                        after_merge: crate::task::AfterMerge::Review,
                        next_slug: None,
                        github: Some(GithubPr {
                            number: 1080,
                            url: "https://github.com/loopflow/loopflow/pull/1080".to_string(),
                            head_sha: None,
                        }),
                    });
                    flip_store.update_task_pr(&open_pr).await.unwrap();
                });
            })
            .join()
            .unwrap();
            Ok(())
        });

        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task)),
            ChildCommandSource::Wave(wave.id().clone()),
            ChildCommandKind::Resume { message: None },
        )
        .await
        .expect_err("the launch re-read must observe the newly open PR");
        let bar = error.to_string();
        assert!(bar.contains("#1080") && bar.contains("reviewer"), "{bar}");

        let commands = store.list_child_commands(&target).await.unwrap();
        assert_eq!(commands.len(), 1);
        assert_eq!(commands[0].state, ChildCommandState::Failed);
        assert_eq!(commands[0].error.as_deref(), Some(bar.as_str()));
        assert!(
            commands.iter().all(|command| !matches!(
                command.state,
                ChildCommandState::Persisted
                    | ChildCommandState::Claimed
                    | ChildCommandState::Uncertain
            )),
            "the raced Resume must leave no live or uncertain orphan: {commands:?}"
        );

        let persisted = store.get_task_session(&task_id).await.unwrap().unwrap();
        assert_eq!(
            persisted
                .latest_process
                .as_ref()
                .map(|body| body.generation),
            generation_before,
            "launch bars before reserving a generation"
        );
        let events = store.task_events_after(&task_id, 0).await.unwrap();
        assert!(events.iter().any(|event| matches!(
            &event.kind,
            TaskEventKind::CommandChanged {
                state: ChildCommandState::Failed,
                error: Some(recorded),
                ..
            } if recorded == &bar
        )));
    }

    #[tokio::test]
    async fn ci_fix_wake_refuses_an_open_pr_without_a_warranted_failure() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let mut pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();
        // Open PR, head observed green: no failure warrants a ci-fix wake.
        pr.publication = Some(PrPublication {
            requested_at: pr.updated_at,
            after_merge: crate::task::AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 878,
                url: "https://github.com/loopflow/loopflow/pull/878".to_string(),
                head_sha: Some("h1".to_string()),
            }),
        });
        pr.ci_observation = Some(crate::task::CiObservation {
            head_sha: "h1".to_string(),
            state: crate::task::CiState::Passing,
            failing_checks: vec![],
            observed_at: pr.updated_at,
        });
        store.update_task_pr(&pr).await.unwrap();

        // The wake must be attributable before the launch is even asked about, so
        // the incident has to exist for this test to reach the bar at all.
        let identity = "github:ci:loopflow/loopflow:878:h1:0000".to_string();
        store
            .observe_ci_incident(&crate::task::CiIncident {
                identity: identity.clone(),
                task_session_id: task.id.clone(),
                pr_id: pr.id.clone(),
                repo: "loopflow/loopflow".to_string(),
                pr_number: 878,
                failed_head_sha: "h1".to_string(),
                repaired_head_sha: None,
                failure_set: vec!["cargo-fmt".to_string()],
                provider_completed_at: None,
                poll_observed_at: Some(pr.updated_at),
                webhook_received_at: None,
                trigger_command_id: None,
                responded_at: None,
                green_at: None,
                merged_at: None,
                blocked_at: None,
                blocked_reason: None,
                created_at: pr.updated_at,
                updated_at: pr.updated_at,
            })
            .await
            .unwrap();

        // Reached through the ledger rather than a bespoke wake call: a `CiFix`
        // command is the only way to ask for this launch now. The observer never
        // enqueues one against a green head, so this asks the bar directly —
        // legality is the bar's question, and a green PR is not legal.
        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task.clone())),
            ChildCommandSource::System,
            ChildCommandKind::CiFix {
                incident_identity: identity,
                pr_number: 878,
                head_sha: "h1".to_string(),
                failing_checks: vec![],
            },
        )
        .await
        .expect_err("a green open PR must not wake a ci-fix turn");
        assert!(
            error.to_string().contains("#878"),
            "the refusal names the open PR, got: {error}"
        );
        let persisted = store.get_task_session(&task.id).await.unwrap().unwrap();
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);
        assert_eq!(persisted.latest_process, None);
    }

    /// A duplicate observation must not spin a body on every supervision pass.
    ///
    /// A `Decide` re-sent by a human means "run this", so an unsettled one
    /// relaunches. A `CiFix` is re-sent by a *poll*, not a person: once a
    /// generation has claimed it, that generation owns the repair, and a dead one
    /// is recovery's job — recovery re-enters ci-fix and reclaims this same
    /// command. Only a wake nobody ever claimed is worth retrying.
    #[test]
    fn a_claimed_ci_fix_wake_does_not_relaunch_a_parked_task() {
        let wake = |state| {
            let mut command = ChildCommand::new(
                ChildRef::Task(crate::task::TaskSessionId::new()),
                ChildCommandSource::System,
                ChildCommandKind::CiFix {
                    incident_identity: "github:ci:owner/repo:1:h1:d".to_string(),
                    pr_number: 1,
                    head_sha: "h1".to_string(),
                    failing_checks: vec![],
                },
            );
            command.state = state;
            command
        };
        // Nobody claimed it: the launch that should have consumed it never
        // happened, so retry.
        assert!(relaunch_on_duplicate(&wake(ChildCommandState::Persisted)));
        // A generation owns the repair. Relaunching here is the every-pass spin.
        assert!(!relaunch_on_duplicate(&wake(ChildCommandState::Claimed)));
        assert!(!relaunch_on_duplicate(&wake(ChildCommandState::Superseded)));
        assert!(!relaunch_on_duplicate(&wake(ChildCommandState::Accepted)));

        // Every other kind keeps the human-facing rule: unsettled means relaunch.
        let mut decide = ChildCommand::new(
            ChildRef::Task(crate::task::TaskSessionId::new()),
            ChildCommandSource::Human,
            ChildCommandKind::Decide {
                decision_id: crate::child_session::ChildDecisionId::new(),
                choice: "yes".to_string(),
                message: None,
            },
        );
        decide.state = ChildCommandState::Claimed;
        assert!(relaunch_on_duplicate(&decide));
        decide.state = ChildCommandState::Accepted;
        assert!(!relaunch_on_duplicate(&decide));
    }

    /// The durable order is incident -> command ensure -> trigger link -> launch.
    ///
    /// Asserted at the launch seam, not eventually. Launching leads to a body, and
    /// a body stamps `responded_at` as soon as it arms; linking after the launch
    /// returns — which `wait_for_resolution = false` makes a wider window still —
    /// leaves a crash able to strand an incident reading "responded, trigger
    /// unknown". Here the launch is *barred*, so nothing downstream of it runs: if
    /// the link were downstream, it would be missing.
    #[tokio::test]
    async fn a_ci_fix_wake_is_attributable_before_anything_can_service_it() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();

        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let mut pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();
        // A green head bars the launch, which is exactly the seam we want: the
        // launch never happens, so only an upstream link survives.
        pr.publication = Some(PrPublication {
            requested_at: pr.updated_at,
            after_merge: crate::task::AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 878,
                url: "https://github.com/loopflow/loopflow/pull/878".to_string(),
                head_sha: Some("h1".to_string()),
            }),
        });
        pr.ci_observation = Some(crate::task::CiObservation {
            head_sha: "h1".to_string(),
            state: crate::task::CiState::Passing,
            failing_checks: vec![],
            observed_at: pr.updated_at,
        });
        store.update_task_pr(&pr).await.unwrap();

        let identity = "github:ci:loopflow/loopflow:878:h1:digest".to_string();
        store
            .observe_ci_incident(&crate::task::CiIncident {
                identity: identity.clone(),
                task_session_id: task.id.clone(),
                pr_id: pr.id.clone(),
                repo: "loopflow/loopflow".to_string(),
                pr_number: 878,
                failed_head_sha: "h1".to_string(),
                repaired_head_sha: None,
                failure_set: vec!["cargo-fmt".to_string()],
                provider_completed_at: None,
                poll_observed_at: Some(pr.updated_at),
                webhook_received_at: None,
                trigger_command_id: None,
                responded_at: None,
                green_at: None,
                merged_at: None,
                blocked_at: None,
                blocked_reason: None,
                created_at: pr.updated_at,
                updated_at: pr.updated_at,
            })
            .await
            .unwrap();

        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task.clone())),
            ChildCommandSource::System,
            ChildCommandKind::CiFix {
                incident_identity: identity.clone(),
                pr_number: 878,
                head_sha: "h1".to_string(),
                failing_checks: vec![],
            },
        )
        .await
        .expect_err("the bar refuses the launch");
        assert!(error.to_string().contains("#878"));

        // The launch failed, and the wake is still attributable.
        let commands = store
            .list_child_commands(&ChildRef::Task(task.id.clone()))
            .await
            .unwrap();
        assert_eq!(
            commands.len(),
            1,
            "the wake was persisted before the launch"
        );
        let incident = store
            .ci_incidents_since(pr.updated_at - time::Duration::seconds(1), None, None)
            .await
            .unwrap();
        assert_eq!(
            incident[0].incident.trigger_command_id.as_ref(),
            Some(&commands[0].id),
            "the trigger link is already present at the launch seam, not merely eventually"
        );
        assert_eq!(
            incident[0].incident.responded_at, None,
            "and nothing responded: no body was ever born"
        );
    }

    /// The ordering is enforced, not documented. `mark_ci_incident_triggered`
    /// reports whether it matched an incident, and a wake naming one that does not
    /// exist is refused: launching anyway would produce the unattributable body
    /// the link exists to prevent, and no caller would learn of it.
    #[tokio::test]
    async fn a_ci_fix_wake_naming_no_incident_refuses_rather_than_launching() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();
        let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        let pr = make_task_pr(&task);
        store.create_task_session(&task, &pr).await.unwrap();

        // No `observe_ci_incident` ran: the wake names evidence that isn't there.
        let error = queue_command(
            &store,
            ChildSession::Task(Box::new(task.clone())),
            ChildCommandSource::System,
            ChildCommandKind::CiFix {
                incident_identity: "github:ci:loopflow/loopflow:99:h9:missing".to_string(),
                pr_number: 99,
                head_sha: "h9".to_string(),
                failing_checks: vec![],
            },
        )
        .await
        .expect_err("an unattributable wake must not launch");
        assert!(
            error.to_string().contains("not recorded"),
            "the refusal says the incident is missing, got: {error}"
        );

        let persisted = store.get_task_session(&task.id).await.unwrap().unwrap();
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);
        assert_eq!(
            persisted.latest_process, None,
            "no body was launched for a wake nothing can attribute"
        );
    }

    /// A human may still answer review on a submitted Task. The bar is on the
    /// supervisor, not the operator — otherwise delivered work becomes unreachable.
    #[tokio::test]
    async fn an_operator_may_still_resume_a_submitted_task_to_answer_review() {
        let (task, pr) = {
            let wave = make_wave("/tmp");
            let project = make_project(&wave, ProjectSessionStatus::Running);
            let task = make_task(&wave, &project, TaskSessionStatus::Waiting);
            let mut pr = make_task_pr(&task);
            pr.publication = Some(PrPublication {
                requested_at: pr.updated_at,
                after_merge: crate::task::AfterMerge::Review,
                next_slug: None,
                github: Some(GithubPr {
                    number: 878,
                    url: "https://github.com/loopflow/loopflow/pull/878".to_string(),
                    head_sha: None,
                }),
            });
            (task, pr)
        };

        // The supervisor is barred...
        assert!(task.supervisor_restart_bar(Some(&pr)).is_some());
        // ...but nothing about the Session itself is terminal, so an explicit
        // `lf task resume` still has a Session to resume.
        assert!(!task.status.is_terminal());
        assert!(task.abandon_intent.is_none());
    }

    #[tokio::test]
    async fn project_handoff_reuses_compatible_history_and_records_the_transition() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let mut project = make_project(&wave, ProjectSessionStatus::Waiting);
        project.provider_session_id = Some("claude-thread".to_string());
        project.latest_process = Some(ChildProcessGeneration {
            generation: 4,
            pid: None,
            process_group_id: None,
            tmux_name: "lf-project-old".to_string(),
            agent: "claude:sonnet".to_string(),
            provider: "claude".to_string(),
            provider_session_id: Some("claude-thread".to_string()),
            started_at: project.updated_at,
            state: crate::child_session::ChildLeaseState::Finished,
            outcome: Some(crate::child_session::ChildBodyOutcome::LegacyStopped {
                reason: "test body stopped".to_string(),
            }),
            provenance: None,
        });
        project.agent = "claude:sonnet".to_string();
        project.provider = "claude".to_string();
        let project_id = project.id.clone();
        store.create_project_session(&project).await.unwrap();

        let request = handoff_request("claude:opus", Some("use the larger context window"))
            .expect("valid same-provider handoff");
        let mut child = ChildSession::Project(Box::new(project));
        child.handoff(&store, &request).await.unwrap();

        let persisted = store
            .get_project_session(&project_id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(persisted.agent, "claude:opus");
        assert_eq!(persisted.provider, "claude");
        assert_eq!(
            persisted.provider_session_id.as_deref(),
            Some("claude-thread")
        );
        let events = store.project_events_after(&project_id, 0).await.unwrap();
        assert!(matches!(
            events.last().map(|event| &event.kind),
            Some(ProjectEventKind::BodyHandedOff { handoff })
                if handoff.from_agent == "claude:sonnet"
                    && handoff.to_agent == "claude:opus"
                    && handoff.reason == "use the larger context window"
        ));
    }

    #[tokio::test]
    async fn live_task_writer_rejects_provider_handoff_without_mutation() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();
        let task = make_task(&wave, &project, TaskSessionStatus::Running);
        let task_id = task.id.clone();
        store
            .create_task_session(&task, &make_task_pr(&task))
            .await
            .unwrap();

        let request = handoff_request("codex", Some("Claude quota exhausted")).unwrap();
        let error = store
            .handoff_task_body(&task_id, &request)
            .await
            .expect_err("a live writer must be interrupted before handoff");
        assert!(error.to_string().contains("active writer"));

        let persisted = store.get_task_session(&task_id).await.unwrap().unwrap();
        assert_eq!(persisted.agent, "claude");
        assert_eq!(
            persisted.provider_session_id.as_deref(),
            Some("thread-task")
        );
        assert!(store
            .task_events_after(&task_id, 0)
            .await
            .unwrap()
            .is_empty());
    }

    #[tokio::test]
    async fn task_handoff_preserves_an_open_pr_and_its_supervisor_bar() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();
        let mut task = make_task(&wave, &project, TaskSessionStatus::Waiting);
        task.provider_session_id = Some("claude-review-thread".to_string());
        let mut pr = make_task_pr(&task);
        let task_id = task.id.clone();
        let pr_id = pr.id.clone();
        store.create_task_session(&task, &pr).await.unwrap();
        pr.publication = Some(PrPublication {
            requested_at: pr.updated_at,
            after_merge: crate::task::AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 898,
                url: "https://github.com/loopflow/loopflow/pull/898".to_string(),
                head_sha: None,
            }),
        });
        store.update_task_pr(&pr).await.unwrap();

        let error = resume_session(
            &store,
            ChildSession::Task(Box::new(task)),
            ChildCommandSource::Project(project.id.clone()),
            None,
            Some("codex".to_string()),
            Some("supervisor tried to answer review".to_string()),
        )
        .await
        .expect_err("supervision must not hand off an open PR");
        assert!(error.to_string().contains("#898"));
        assert_eq!(
            store
                .get_task_session(&task_id)
                .await
                .unwrap()
                .unwrap()
                .agent,
            "claude"
        );

        let request = handoff_request("codex", Some("answer review on Codex")).unwrap();
        let persisted = store.handoff_task_body(&task_id, &request).await.unwrap();
        let active_pr = store.active_task_pr(&task_id).await.unwrap().unwrap();

        assert_eq!(active_pr.id, pr_id);
        assert!(persisted.supervisor_restart_bar(Some(&active_pr)).is_some());
        assert_eq!(persisted.agent, "codex");
        assert_eq!(persisted.provider_session_id, None);
    }

    #[tokio::test]
    async fn terminal_task_rejects_handoff() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        let project = make_project(&wave, ProjectSessionStatus::Running);
        store.create_project_session(&project).await.unwrap();
        let task = make_task(&wave, &project, TaskSessionStatus::Completed);
        let task_id = task.id.clone();
        store
            .create_task_session(&task, &make_task_pr(&task))
            .await
            .unwrap();

        let request = handoff_request("codex", Some("should not restart")).unwrap();
        let error = store
            .handoff_task_body(&task_id, &request)
            .await
            .expect_err("terminal Sessions never hand off");
        assert!(error.to_string().contains("terminal Sessions"));
    }

    /// Abandonment is decided when it is *queued*, not when a runner consumes it.
    /// Until this landed, the intent lived only in the command row while the
    /// Session still read `Running` — so anything that launched in that window
    /// revived work someone had already ended.
    #[tokio::test]
    async fn queueing_abandon_stamps_intent_and_bars_every_later_command() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let wave = make_wave(dir.path().to_str().unwrap());
        store.create_wave(&wave).await.unwrap();
        // Active: the abandon command stays pending rather than being applied,
        // which is exactly the window the race used to live in.
        let project = make_project(&wave, ProjectSessionStatus::Running);
        let project_id = project.id.clone();
        store.create_project_session(&project).await.unwrap();

        queue_command(
            &store,
            ChildSession::Project(Box::new(project)),
            ChildCommandSource::Human,
            ChildCommandKind::Abandon {
                reason: "Superseded by a different bet".to_string(),
            },
        )
        .await
        .unwrap();

        let persisted = store
            .get_project_session(&project_id)
            .await
            .unwrap()
            .unwrap();
        // The runner has not consumed the command, so the Session is not yet
        // Abandoned — but the intent is durable and already dominates.
        assert_eq!(persisted.status, ProjectSessionStatus::Running);
        let intent = persisted
            .abandon_intent
            .as_ref()
            .expect("abandon intent is stamped when the command is queued");
        assert_eq!(intent.reason, "Superseded by a different bet");
        assert!(persisted.supervisor_restart_bar().is_some());

        let error = queue_command(
            &store,
            ChildSession::Project(Box::new(persisted)),
            ChildCommandSource::Human,
            ChildCommandKind::FollowUp {
                text: "One more thing".to_string(),
            },
        )
        .await
        .expect_err("a Session being abandoned accepts nothing else");
        assert!(
            error.to_string().contains("being abandoned"),
            "got: {error}"
        );
    }
}