loopflow 0.12.22

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
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
use time::OffsetDateTime;

use crate::child::ChildRef;
use crate::durable::{
    AbandonReceipt, Author, FlowPosition, Home, HomeId, Placement, ProjectId, RunId, Steer,
    SteerComment, TaskFlowBlocker, TaskId, TaskWorkerClaim, TaskWorkerClaimOutcome,
    TaskWorkerOwner, ToolResponseId, ToolResponseReceipt, ToolResponseWrite, WorkRef, WorkStatus,
};
use crate::id::WaveId;
use crate::store::rows::now_unix;
use crate::store::{StoreError, StoreResult};
use crate::work::project::{Project, ProjectEventKind};
use crate::work::task::{Task, TaskEventKind};

use super::SqliteStore;

impl SqliteStore {
    pub fn record_flow_verdict(
        &self,
        task_id: &TaskId,
        run_id: &RunId,
        verdict: &crate::engine::transitions::FlowVerdict,
    ) -> StoreResult<()> {
        if verdict.summary.trim().is_empty() {
            return Err(StoreError::InvalidData(
                "review evidence cannot be empty".to_string(),
            ));
        }
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, &WorkRef::Task(task_id.clone()))?;
        let mut position = flow_position_in(&tx, task_id)?.ok_or(StoreError::NotFound)?;
        if position
            .claim
            .as_ref()
            .and_then(|claim| claim.worker_run_id.as_ref())
            != Some(run_id)
            || position.current().policy.repeat.is_none()
        {
            return Err(StoreError::InvalidAuthority(
                "only the current claimed loop reviewer may record a verdict".to_string(),
            ));
        }
        let progress = &mut position.cursor.leaf_mut().progress;
        if progress
            .verdict
            .as_ref()
            .is_some_and(|saved| saved != verdict)
        {
            return Err(StoreError::InvalidAuthority(
                "step already has a different decision".into(),
            ));
        }
        progress.verdict = Some(verdict.clone());
        tx.execute(
            "UPDATE task_flow_positions SET review_json=?2 WHERE task_id=?1",
            params![task_id.as_str(), serde_json::to_string(&position.cursor)?],
        )?;
        tx.commit()?;
        Ok(())
    }

    pub fn record_flow_route(
        &self,
        task_id: &TaskId,
        run_id: &RunId,
        path: &str,
    ) -> StoreResult<()> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, &WorkRef::Task(task_id.clone()))?;
        let mut position = flow_position_in(&tx, task_id)?.ok_or(StoreError::NotFound)?;
        if position
            .claim
            .as_ref()
            .and_then(|claim| claim.worker_run_id.as_ref())
            != Some(run_id)
        {
            return Err(StoreError::InvalidAuthority(
                "only the current claimed router may select a path".into(),
            ));
        }
        let crate::engine::ConcreteStep::Xor(branch) = position.current_plan() else {
            return Err(StoreError::InvalidAuthority(
                "current Flow step is not a router".into(),
            ));
        };
        if !branch.paths.contains_key(path) {
            return Err(StoreError::InvalidData(format!(
                "unknown Flow route {path:?}"
            )));
        }
        let leaf = position.cursor.leaf_mut();
        if leaf.route.as_deref().is_some_and(|saved| saved != path) {
            return Err(StoreError::InvalidAuthority(
                "step already has a different route".into(),
            ));
        }
        leaf.route = Some(path.to_string());
        tx.execute(
            "UPDATE task_flow_positions SET review_json=?2 WHERE task_id=?1",
            params![task_id.as_str(), serde_json::to_string(&position.cursor)?],
        )?;
        tx.commit()?;
        Ok(())
    }

    pub(crate) fn task_issue_identifier(
        &self,
        external_issue_id: &str,
    ) -> StoreResult<Option<String>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        conn.query_row(
            "SELECT issue_identifier FROM tasks WHERE external_issue_id=?1",
            [external_issue_id],
            |row| row.get(0),
        )
        .optional()
        .map_err(Into::into)
    }

    pub fn home_by_id(&self, home_id: &HomeId) -> StoreResult<Option<Home>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        map_home_by_id(&conn, home_id)
    }

    pub fn local_home(&self) -> StoreResult<Home> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        map_local_home(&conn)
    }

    pub fn observe_home(&self, home_id: &HomeId, route: &str) -> StoreResult<Home> {
        let route = route.trim();
        if route.is_empty() {
            return Err(StoreError::InvalidData(
                "Home route cannot be empty".to_string(),
            ));
        }
        let conn = self.conn.lock().expect("store mutex poisoned");
        if map_home_by_id(&conn, home_id)?
            .is_some_and(|home| home.route == "local" && route != "local")
        {
            return Err(StoreError::InvalidData(format!(
                "cannot replace local Home {home_id} with remote route {route:?}"
            )));
        }
        let existing_id = conn
            .query_row("SELECT id FROM homes WHERE route=?1", [route], |row| {
                row.get::<_, String>(0)
            })
            .optional()?;
        if existing_id
            .as_deref()
            .is_some_and(|id| id != home_id.as_str())
        {
            return Err(StoreError::InvalidData(format!(
                "Home route {route:?} is already observed for {}",
                existing_id.expect("checked as present")
            )));
        }
        let now = now_unix();
        conn.execute(
            "INSERT INTO homes (id, route, created_at, observed_at)
             VALUES (?1, ?2, ?3, ?3)
             ON CONFLICT(id) DO UPDATE SET
                route=excluded.route, observed_at=excluded.observed_at",
            params![home_id.as_str(), route, now],
        )?;
        map_home_by_id(&conn, home_id)?.ok_or(StoreError::NotFound)
    }

    pub fn placement(&self, work: &WorkRef) -> StoreResult<Placement> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        placement_in(&conn, work)
    }

    pub fn set_work_enabled(&self, work: &WorkRef, enabled: bool) -> StoreResult<Placement> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        placement_in(&tx, work)?;
        let enabled = if enabled { 1_i64 } else { 0_i64 };
        match work {
            WorkRef::Wave(id) => tx.execute(
                "UPDATE work_placements SET enabled=?2 WHERE wave_id=?1",
                params![id.as_str(), enabled],
            )?,
            WorkRef::Project(id) => tx.execute(
                "UPDATE work_placements SET enabled=?2 WHERE project_id=?1",
                params![id.as_str(), enabled],
            )?,
            WorkRef::Task(id) => tx.execute(
                "UPDATE work_placements SET enabled=?2 WHERE task_id=?1",
                params![id.as_str(), enabled],
            )?,
        };
        let placement = placement_in(&tx, work)?;
        tx.commit()?;
        Ok(placement)
    }

    pub(crate) fn place_work(&self, work: &WorkRef, home_id: &HomeId) -> StoreResult<Placement> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, work)?;
        tx.query_row(
            "SELECT 1 FROM homes WHERE id=?1",
            [home_id.as_str()],
            |_| Ok(()),
        )?;
        if let Some(current) = find_placement_in(&tx, work)? {
            if current.home_id == *home_id {
                tx.commit()?;
                return Ok(current);
            }
        }
        write_placement(&tx, work, home_id, now_unix())?;
        let placement = placement_in(&tx, work)?;
        tx.commit()?;
        Ok(placement)
    }

    pub fn set_flow_position(
        &self,
        task_id: &TaskId,
        position: &FlowPosition,
    ) -> StoreResult<FlowPosition> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let stored = set_flow_position_in(&tx, task_id, position)?;
        tx.commit()?;
        Ok(stored)
    }

    pub fn flow_position(&self, task_id: &TaskId) -> StoreResult<Option<FlowPosition>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        flow_position_in(&conn, task_id)
    }

    pub fn claim_task_worker(
        &self,
        task_id: &TaskId,
        expected_invocation: &str,
        expected_version: u64,
        owner: &TaskWorkerOwner,
        claimed_at: OffsetDateTime,
    ) -> StoreResult<TaskWorkerClaimOutcome> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let work = WorkRef::Task(task_id.clone());
        require_task_worker_eligible(&tx, &work)?;
        let position = flow_position_in(&tx, task_id)?.ok_or(StoreError::NotFound)?;
        if position.is_human() {
            return Err(StoreError::InvalidAuthority(
                "Review Flow positions wait for their Session to complete".to_string(),
            ));
        }
        if position.invocation.id != expected_invocation || position.version != expected_version {
            return Ok(TaskWorkerClaimOutcome::Stale {
                actual_version: position.version,
            });
        }
        if let Some(claim) = position.claim {
            return Ok(TaskWorkerClaimOutcome::Busy(claim));
        }
        let generation = position.worker_generation.checked_add(1).ok_or_else(|| {
            StoreError::InvalidData("Task worker generation overflow".to_string())
        })?;
        let claim = TaskWorkerClaim {
            invocation_id: position.invocation.id.clone(),
            generation,
            position_version: position.version,
            owner: owner.clone(),
            worker_run_id: None,
            claimed_at,
        };
        let claim_json = serde_json::to_string(&claim)?;
        let changed = tx.execute(
            "UPDATE task_flow_positions
             SET worker_generation=?2, claim_json=?3, failure_json=NULL, updated_at=?4, review_json=?6
             WHERE task_id=?1 AND position_version=?5 AND claim_json IS NULL",
            params![
                task_id.as_str(),
                i64::try_from(generation).map_err(invalid_durable)?,
                claim_json,
                claimed_at.unix_timestamp(),
                i64::try_from(expected_version).map_err(invalid_durable)?,
                serde_json::to_string(&position.cursor)?
            ],
        )?;
        if changed != 1 {
            let current = flow_position_in(&tx, task_id)?.ok_or(StoreError::NotFound)?;
            return Ok(match current.claim {
                Some(claim) => TaskWorkerClaimOutcome::Busy(claim),
                None => TaskWorkerClaimOutcome::Stale {
                    actual_version: current.version,
                },
            });
        }
        tx.commit()?;
        Ok(TaskWorkerClaimOutcome::Claimed(claim))
    }

    pub fn reclaim_task_worker(
        &self,
        task_id: &TaskId,
        expected: &TaskWorkerClaim,
        owner: &TaskWorkerOwner,
        claimed_at: OffsetDateTime,
    ) -> StoreResult<TaskWorkerClaim> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let work = WorkRef::Task(task_id.clone());
        require_task_worker_eligible(&tx, &work)?;
        let position = flow_position_in(&tx, task_id)?.ok_or(StoreError::NotFound)?;
        if position.version != expected.position_version
            || position.claim.as_ref() != Some(expected)
        {
            return Err(stale_task_worker(task_id));
        }
        let generation = position.worker_generation.checked_add(1).ok_or_else(|| {
            StoreError::InvalidData("Task worker generation overflow".to_string())
        })?;
        let replacement = TaskWorkerClaim {
            invocation_id: position.invocation.id.clone(),
            generation,
            position_version: position.version,
            owner: owner.clone(),
            worker_run_id: None,
            claimed_at,
        };
        let expected_json = serde_json::to_string(expected)?;
        let replacement_json = serde_json::to_string(&replacement)?;
        if tx.execute(
            "UPDATE task_flow_positions
             SET worker_generation=?2, claim_json=?3, failure_json=NULL, updated_at=?4, review_json=?7
             WHERE task_id=?1 AND position_version=?5 AND claim_json=?6",
            params![
                task_id.as_str(),
                i64::try_from(generation).map_err(invalid_durable)?,
                replacement_json,
                claimed_at.unix_timestamp(),
                i64::try_from(position.version).map_err(invalid_durable)?,
                expected_json,
                serde_json::to_string(&position.cursor)?
            ],
        )? != 1
        {
            return Err(stale_task_worker(task_id));
        }
        tx.commit()?;
        Ok(replacement)
    }

    pub fn bind_task_worker_run(
        &self,
        task_id: &TaskId,
        expected: &TaskWorkerClaim,
        worker_run_id: &RunId,
        owner: &TaskWorkerOwner,
    ) -> StoreResult<TaskWorkerClaim> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, &WorkRef::Task(task_id.clone()))?;
        let bound = TaskWorkerClaim {
            invocation_id: expected.invocation_id.clone(),
            generation: expected.generation,
            position_version: expected.position_version,
            owner: owner.clone(),
            worker_run_id: Some(worker_run_id.clone()),
            claimed_at: expected.claimed_at,
        };
        let expected_json = serde_json::to_string(expected)?;
        let bound_json = serde_json::to_string(&bound)?;
        if tx.execute(
            "UPDATE task_flow_positions SET claim_json=?2
             WHERE task_id=?1 AND position_version=?3 AND claim_json=?4",
            params![
                task_id.as_str(),
                bound_json,
                i64::try_from(expected.position_version).map_err(invalid_durable)?,
                expected_json
            ],
        )? != 1
        {
            return Err(stale_task_worker(task_id));
        }
        tx.commit()?;
        Ok(bound)
    }

    pub fn human_task_flow_positions(&self) -> StoreResult<Vec<FlowPosition>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        let mut statement = conn.prepare(
            "SELECT task_id, invocation_json, flow, step, node_id, human,
                    session_run_id, ready_summary, step_index, iteration,
                    position_version, worker_generation, claim_json, failure_json,
                    updated_at, review_json
             FROM task_flow_positions WHERE human=1 ORDER BY updated_at, task_id",
        )?;
        let rows = statement.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, String>(3)?,
                row.get::<_, Option<String>>(4)?,
                row.get::<_, bool>(5)?,
                row.get::<_, Option<String>>(6)?,
                row.get::<_, Option<String>>(7)?,
                row.get::<_, i64>(8)?,
                row.get::<_, i64>(9)?,
                row.get::<_, i64>(10)?,
                row.get::<_, i64>(11)?,
                row.get::<_, Option<String>>(12)?,
                row.get::<_, Option<String>>(13)?,
                row.get::<_, i64>(14)?,
                row.get::<_, Option<String>>(15)?,
            ))
        })?;
        let mut positions = Vec::new();
        for row in rows {
            let (
                task_id,
                invocation_json,
                flow,
                step,
                node_id,
                human,
                session_run_id,
                ready_summary,
                step_index,
                iteration,
                position_version,
                worker_generation,
                claim_json,
                failure_json,
                updated_at,
                review_json,
            ) = row?;
            positions.push(decode_flow_position(
                TaskId::parse(&task_id).map_err(invalid_durable)?,
                (
                    invocation_json,
                    flow,
                    step,
                    node_id,
                    human,
                    session_run_id,
                    ready_summary,
                    step_index,
                    iteration,
                    position_version,
                    worker_generation,
                    claim_json,
                    failure_json,
                    updated_at,
                    review_json,
                ),
            )?);
        }
        Ok(positions)
    }

    pub fn abandon(&self, work: &WorkRef, reason: &str) -> StoreResult<AbandonReceipt> {
        let reason = reason.trim();
        if reason.is_empty() {
            return Err(StoreError::InvalidData(
                "abandon reason cannot be empty".to_string(),
            ));
        }
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let now = now_unix();
        let (table, id) = work_table(work);
        if tx.execute(
            &format!(
                "UPDATE {table} SET work_state='abandoned', work_terminal_at=?2
                 WHERE id=?1 AND work_state='ready'"
            ),
            params![id, now],
        )? != 1
        {
            return Err(StoreError::InvalidAuthority(format!(
                "{} {} is not ready",
                work.kind(),
                work.id()
            )));
        }
        tx.commit()?;
        Ok(AbandonReceipt {
            work: work.clone(),
            reason: reason.to_string(),
            abandoned_at: OffsetDateTime::from_unix_timestamp(now)
                .expect("current Unix timestamp must be valid"),
        })
    }

    pub fn work_status(&self, work: &WorkRef) -> StoreResult<WorkStatus> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        work_status_in(&conn, work)
    }

    pub fn work_for_child(&self, target: &ChildRef) -> StoreResult<WorkRef> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        work_for_child_in(&conn, target)
    }

    pub fn task_steers(&self, task_id: &TaskId) -> StoreResult<Vec<Steer>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        Ok(super::children::task_events_after_in(&conn, task_id, 0)?
            .into_iter()
            .filter_map(|event| match event.kind {
                TaskEventKind::Steer { author, text } => Some(Steer {
                    id: event.id,
                    author,
                    text,
                }),
                _ => None,
            })
            .collect())
    }

    /// Steer comments across every Work, issued at or after `since` (unix
    /// seconds) — the cross-Work `lf activity` timeline. Scans the Task and
    /// Project event streams for the `Steer` comment; there is no steers table.
    pub fn steers_since(&self, since: i64) -> StoreResult<Vec<SteerComment>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        let mut comments = Vec::new();
        let mut task_statement = conn.prepare(
            "SELECT task_id, id, kind_json, created_at FROM task_events
             WHERE json_extract(kind_json, '$.kind')='steer' AND created_at >= ?1
             ORDER BY created_at, id",
        )?;
        let task_rows = task_statement.query_map([since], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, i64>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, i64>(3)?,
            ))
        })?;
        for row in task_rows {
            let (task_id, id, kind_json, created_at) = row?;
            let kind: TaskEventKind = serde_json::from_str(&kind_json)?;
            if let TaskEventKind::Steer { author, text } = kind {
                comments.push(SteerComment {
                    work: WorkRef::Task(TaskId::parse(&task_id).map_err(invalid_durable)?),
                    steer: Steer { id, author, text },
                    issued_at: crate::store::rows::unix_to_datetime(created_at),
                });
            }
        }
        let mut project_statement = conn.prepare(
            "SELECT project_id, id, kind_json, created_at FROM project_events
             WHERE json_extract(kind_json, '$.kind')='steer' AND created_at >= ?1
             ORDER BY created_at, id",
        )?;
        let project_rows = project_statement.query_map([since], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, i64>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, i64>(3)?,
            ))
        })?;
        for row in project_rows {
            let (project_id, id, kind_json, created_at) = row?;
            let kind: ProjectEventKind = serde_json::from_str(&kind_json)?;
            if let ProjectEventKind::Steer { author, text } = kind {
                comments.push(SteerComment {
                    work: WorkRef::Project(ProjectId::parse(&project_id).map_err(invalid_durable)?),
                    steer: Steer { id, author, text },
                    issued_at: crate::store::rows::unix_to_datetime(created_at),
                });
            }
        }
        Ok(comments)
    }

    #[cfg(test)]
    pub fn append_steer(&self, work: &WorkRef, author: &Author, text: &str) -> StoreResult<Steer> {
        let WorkRef::Task(task_id) = work else {
            return Err(StoreError::InvalidData("only Tasks take steering".into()));
        };
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        let steer = Self::append_task_steer_in(&tx, task_id, author, text)?;
        tx.commit()?;
        Ok(steer)
    }

    /// Local delivery projection. Authored input is published to Linear first.
    pub(crate) fn append_task_steer_in(
        tx: &Transaction<'_>,
        task_id: &TaskId,
        author: &Author,
        text: &str,
    ) -> StoreResult<Steer> {
        let text = text.trim();
        if text.is_empty() {
            return Err(StoreError::InvalidData("Steer text cannot be empty".into()));
        }
        let task = tx.query_row(
            super::children::TASK_SELECT,
            params![task_id.as_str()],
            super::children::map_task_row,
        )?;
        let event = super::children::insert_task_event_in(
            tx,
            &task,
            &TaskEventKind::Steer {
                author: author.clone(),
                text: text.to_string(),
            },
        )?;
        Ok(Steer {
            id: event.id,
            author: author.clone(),
            text: text.to_string(),
        })
    }

    /// Record an interrupt request as a durable comment on the Work's event
    /// stream. A live run observes it (past its launch cursor) and ends the
    /// current turn; with no live run it is inert history.
    pub fn append_interrupt(&self, work: &WorkRef) -> StoreResult<i64> {
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, work)?;
        let id = match work {
            WorkRef::Task(task_id) => {
                let task = tx.query_row(
                    super::children::TASK_SELECT,
                    params![task_id.as_str()],
                    super::children::map_task_row,
                )?;
                super::children::insert_task_event_in(&tx, &task, &TaskEventKind::Interrupt)?.id
            }
            WorkRef::Project(project_id) => {
                let project = tx.query_row(
                    super::children::PROJECT_SELECT,
                    params![project_id.as_str()],
                    super::children::map_project_row,
                )?;
                super::children::insert_project_event_in(
                    &tx,
                    &project,
                    &ProjectEventKind::Interrupt,
                )?
                .id
            }
            WorkRef::Wave(_) => {
                return Err(StoreError::InvalidData(
                    "Waves are not interrupted through the Work event stream".to_string(),
                ))
            }
        };
        tx.commit()?;
        Ok(id)
    }

    /// The id of the newest interrupt request on the Work, or 0 when there is
    /// none. A run stamps this at launch and re-reads it; a higher value means a
    /// new interrupt to act on.
    pub fn latest_interrupt_id(&self, work: &WorkRef) -> StoreResult<i64> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        let (table, column, id) = match work {
            WorkRef::Task(task_id) => ("task_events", "task_id", task_id.as_str().to_string()),
            WorkRef::Project(project_id) => (
                "project_events",
                "project_id",
                project_id.as_str().to_string(),
            ),
            WorkRef::Wave(_) => return Ok(0),
        };
        let sql = format!(
            "SELECT COALESCE(MAX(id), 0) FROM {table}
             WHERE {column}=?1 AND json_extract(kind_json, '$.kind')='interrupt'"
        );
        conn.query_row(&sql, params![id], |row| row.get(0))
            .map_err(StoreError::from)
    }

    pub fn write_tool_response(
        &self,
        work: &WorkRef,
        write: &ToolResponseWrite,
    ) -> StoreResult<(ToolResponseReceipt, bool)> {
        let choice = write.choice.trim();
        if choice.is_empty() {
            return Err(StoreError::InvalidData(
                "tool response choice cannot be empty".to_string(),
            ));
        }
        let mut conn = self.conn.lock().expect("store mutex poisoned");
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        require_ready_work(&tx, work)?;
        if let Some(existing) = tool_response_in(&tx, work, &write.request_id)? {
            if existing.choice != choice {
                return Err(StoreError::InvalidData(format!(
                    "tool response {} is already resolved as {:?}",
                    write.request_id, existing.choice
                )));
            }
            return Ok((existing, false));
        }
        let receipt = ToolResponseReceipt {
            id: ToolResponseId::new(),
            work: work.clone(),
            request_id: write.request_id.clone(),
            choice: choice.to_string(),
            responded_at: OffsetDateTime::now_utc(),
        };
        tx.execute(
            "INSERT INTO tool_responses (
                id, work_kind, work_id, request_id, choice, responded_at
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                receipt.id.as_str(),
                work.kind(),
                work.id(),
                receipt.request_id,
                receipt.choice,
                receipt.responded_at.unix_timestamp(),
            ],
        )?;
        tx.commit()?;
        Ok((receipt, true))
    }

    pub fn tool_response(
        &self,
        work: &WorkRef,
        request_id: &str,
    ) -> StoreResult<Option<ToolResponseReceipt>> {
        let conn = self.conn.lock().expect("store mutex poisoned");
        tool_response_in(&conn, work, request_id)
    }
}

fn map_local_home(conn: &Connection) -> StoreResult<Home> {
    conn.query_row(
        "SELECT id, route, created_at, observed_at FROM homes WHERE route='local'",
        [],
        |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, i64>(3)?,
            ))
        },
    )
    .map_err(StoreError::from)
    .and_then(|(id, route, created_at, observed_at)| {
        Ok(Home {
            id: HomeId::parse(&id).map_err(invalid_durable)?,
            route,
            created_at: OffsetDateTime::from_unix_timestamp(created_at).map_err(invalid_durable)?,
            observed_at: OffsetDateTime::from_unix_timestamp(observed_at)
                .map_err(invalid_durable)?,
        })
    })
}

fn map_home_by_id(conn: &Connection, home_id: &HomeId) -> StoreResult<Option<Home>> {
    conn.query_row(
        "SELECT id, route, created_at, observed_at FROM homes WHERE id=?1",
        [home_id.as_str()],
        |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, i64>(3)?,
            ))
        },
    )
    .optional()
    .map_err(StoreError::from)?
    .map(|(id, route, created_at, observed_at)| {
        Ok(Home {
            id: HomeId::parse(&id).map_err(invalid_durable)?,
            route,
            created_at: OffsetDateTime::from_unix_timestamp(created_at).map_err(invalid_durable)?,
            observed_at: OffsetDateTime::from_unix_timestamp(observed_at)
                .map_err(invalid_durable)?,
        })
    })
    .transpose()
}

fn placement_in(conn: &Connection, work: &WorkRef) -> StoreResult<Placement> {
    find_placement_in(conn, work)?.ok_or_else(|| {
        StoreError::InvalidData(format!(
            "{} {} has no Home placement",
            work.kind(),
            work.id()
        ))
    })
}

fn find_placement_in(conn: &Connection, work: &WorkRef) -> StoreResult<Option<Placement>> {
    let row = match work {
        WorkRef::Wave(id) => conn.query_row(
            "SELECT home_id, enabled, placed_at FROM work_placements WHERE wave_id=?1",
            [id.as_str()],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, bool>(1)?,
                    row.get::<_, i64>(2)?,
                ))
            },
        ),
        WorkRef::Project(id) => conn.query_row(
            "SELECT home_id, enabled, placed_at FROM work_placements WHERE project_id=?1",
            [id.as_str()],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, bool>(1)?,
                    row.get::<_, i64>(2)?,
                ))
            },
        ),
        WorkRef::Task(id) => conn.query_row(
            "SELECT home_id, enabled, placed_at FROM work_placements WHERE task_id=?1",
            [id.as_str()],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, bool>(1)?,
                    row.get::<_, i64>(2)?,
                ))
            },
        ),
    }
    .optional()?;
    row.map(|(home_id, enabled, placed_at)| {
        Ok(Placement {
            work: work.clone(),
            home_id: HomeId::parse(&home_id).map_err(invalid_durable)?,
            enabled,
            placed_at: OffsetDateTime::from_unix_timestamp(placed_at).map_err(invalid_durable)?,
        })
    })
    .transpose()
}

fn write_placement(
    tx: &Transaction<'_>,
    work: &WorkRef,
    home_id: &HomeId,
    placed_at: i64,
) -> StoreResult<()> {
    match work {
        WorkRef::Wave(id) => tx.execute(
            "INSERT INTO work_placements (wave_id, home_id, enabled, placed_at)
             VALUES (?1, ?2, 1, ?3)
             ON CONFLICT(wave_id) DO UPDATE SET
                home_id=excluded.home_id, placed_at=excluded.placed_at",
            params![id.as_str(), home_id.as_str(), placed_at],
        )?,
        WorkRef::Project(id) => tx.execute(
            "INSERT INTO work_placements (project_id, home_id, enabled, placed_at)
             VALUES (?1, ?2, 1, ?3)
             ON CONFLICT(project_id) DO UPDATE SET
                home_id=excluded.home_id, placed_at=excluded.placed_at",
            params![id.as_str(), home_id.as_str(), placed_at],
        )?,
        WorkRef::Task(id) => tx.execute(
            "INSERT INTO work_placements (task_id, home_id, enabled, placed_at)
             VALUES (?1, ?2, 1, ?3)
             ON CONFLICT(task_id) DO UPDATE SET
                home_id=excluded.home_id, placed_at=excluded.placed_at",
            params![id.as_str(), home_id.as_str(), placed_at],
        )?,
    };
    Ok(())
}

fn inherit_placement(
    tx: &Transaction<'_>,
    work: &WorkRef,
    parent: Option<&WorkRef>,
    placed_at: i64,
) -> StoreResult<()> {
    if find_placement_in(tx, work)?.is_some() {
        return Ok(());
    }
    let home_id = match parent {
        Some(parent) => placement_in(tx, parent)?.home_id,
        None => map_local_home(tx)?.id,
    };
    write_placement(tx, work, &home_id, placed_at)
}

pub(crate) fn work_status_in(conn: &Connection, work: &WorkRef) -> StoreResult<WorkStatus> {
    let (table, id) = work_table(work);
    let state: String = conn.query_row(
        &format!("SELECT work_state FROM {table} WHERE id=?1"),
        [id],
        |row| row.get(0),
    )?;
    match state.as_str() {
        "ready" => Ok(WorkStatus::Ready),
        "done" => Ok(WorkStatus::Done),
        "abandoned" => Ok(WorkStatus::Abandoned),
        other => Err(StoreError::InvalidData(format!(
            "invalid {} Work state {other:?}",
            work.kind()
        ))),
    }
}

pub(super) fn require_ready_work(conn: &Connection, work: &WorkRef) -> StoreResult<()> {
    match work_status_in(conn, work)? {
        WorkStatus::Ready => Ok(()),
        status => Err(StoreError::InvalidAuthority(format!(
            "{} {} is {status}",
            work.kind(),
            work.id()
        ))),
    }
}

fn require_task_worker_eligible(conn: &Connection, work: &WorkRef) -> StoreResult<()> {
    require_ready_work(conn, work)?;
    require_current_task_chapter(conn, work)?;
    if !placement_in(conn, work)?.enabled {
        return Err(StoreError::InvalidAuthority(format!(
            "{} {} is paused",
            work.kind(),
            work.id()
        )));
    }
    Ok(())
}

pub(super) fn require_current_task_chapter(conn: &Connection, work: &WorkRef) -> StoreResult<()> {
    let WorkRef::Task(task) = work else {
        return Ok(());
    };
    let expired: bool = conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM tasks t JOIN projects p ON p.id=t.project_id
         JOIN wave_chapters c ON c.wave_id=p.wave_id AND c.current=1
         WHERE t.id=?1 AND c.project_id != p.external_project_id
         AND NOT EXISTS(SELECT 1 FROM task_events WHERE task_id=t.id AND json_extract(kind_json,'$.kind')='started')
         AND NOT EXISTS(SELECT 1 FROM task_flow_positions WHERE task_id=t.id AND worker_generation>0))",
        [task.as_str()], |row| row.get(0),
    )?;
    if expired {
        return Err(StoreError::InvalidAuthority("this Task belongs to chapter history; resume the chapter transition before starting work".into()));
    }
    Ok(())
}

pub(crate) fn reopen_work_in(conn: &Connection, work: &WorkRef) -> StoreResult<()> {
    if let WorkRef::Task(task_id) = work {
        conn.execute(
            "DELETE FROM task_flow_positions WHERE task_id=?1",
            [task_id.as_str()],
        )?;
    }
    let (table, id) = work_table(work);
    if conn.execute(
        &format!(
            "UPDATE {table} SET work_state='ready', work_terminal_at=NULL
             WHERE id=?1 AND work_state IN ('done', 'abandoned')"
        ),
        [id],
    )? != 1
    {
        return Err(StoreError::InvalidAuthority(format!(
            "{} {} is not terminal",
            work.kind(),
            work.id()
        )));
    }
    Ok(())
}

fn work_table(work: &WorkRef) -> (&'static str, &str) {
    match work {
        WorkRef::Wave(id) => ("waves", id.as_str()),
        WorkRef::Project(id) => ("projects", id.as_str()),
        WorkRef::Task(id) => ("tasks", id.as_str()),
    }
}

type StoredFlowPosition = (
    String,
    String,
    String,
    Option<String>,
    bool,
    Option<String>,
    Option<String>,
    i64,
    i64,
    i64,
    i64,
    Option<String>,
    Option<String>,
    i64,
    Option<String>,
);

pub(super) fn flow_position_in(
    conn: &Connection,
    task_id: &TaskId,
) -> StoreResult<Option<FlowPosition>> {
    let row = conn
        .query_row(
            "SELECT invocation_json, flow, step, node_id, human, session_run_id, ready_summary,
                    step_index, iteration, position_version, worker_generation,
                    claim_json, failure_json, updated_at, review_json
             FROM task_flow_positions WHERE task_id=?1",
            [task_id.as_str()],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, bool>(4)?,
                    row.get::<_, Option<String>>(5)?,
                    row.get::<_, Option<String>>(6)?,
                    row.get::<_, i64>(7)?,
                    row.get::<_, i64>(8)?,
                    row.get::<_, i64>(9)?,
                    row.get::<_, i64>(10)?,
                    row.get::<_, Option<String>>(11)?,
                    row.get::<_, Option<String>>(12)?,
                    row.get::<_, i64>(13)?,
                    row.get::<_, Option<String>>(14)?,
                ))
            },
        )
        .optional()?;
    row.map(|row| decode_flow_position(task_id.clone(), row))
        .transpose()
}

pub(super) fn set_flow_position_in(
    conn: &Connection,
    task_id: &TaskId,
    position: &FlowPosition,
) -> StoreResult<FlowPosition> {
    require_ready_work(conn, &WorkRef::Task(task_id.clone()))?;
    require_current_task_chapter(conn, &WorkRef::Task(task_id.clone()))?;
    validate_flow_position(task_id, position)?;
    if position.claim.is_some() {
        return Err(StoreError::InvalidAuthority(
            "set_flow_position cannot write an advancement claim".to_string(),
        ));
    }
    let failure_json = position
        .failure
        .as_ref()
        .map(serde_json::to_string)
        .transpose()?;
    let step = position.current();
    let changed = if position.version == 0 {
        conn.execute(
            "INSERT INTO task_flow_positions (
                task_id, invocation_json, flow, step, node_id, human, session_run_id,
                ready_summary, step_index, iteration, position_version,
                worker_generation, claim_json, failure_json, updated_at, review_json
             ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1, 0, NULL, ?11, ?12, ?13
             )
             ON CONFLICT(task_id) DO NOTHING",
            params![
                task_id.as_str(),
                serde_json::to_string(&position.invocation)?,
                step.flow,
                step.step,
                step.policy.id,
                step.policy.human,
                position.session_run_id.as_ref().map(RunId::as_str),
                position.ready_summary,
                i64::try_from(position.cursor.index).map_err(invalid_durable)?,
                i64::from(position.cursor.iteration),
                failure_json,
                position.updated_at.unix_timestamp(),
                serde_json::to_string(&position.cursor)?
            ],
        )?
    } else {
        conn.execute(
            "UPDATE task_flow_positions
             SET invocation_json=?2, flow=?3, step=?4, node_id=?5, human=?6, session_run_id=?7,
                 ready_summary=?8, step_index=?9, iteration=?10,
                 position_version=position_version + 1,
                 worker_generation=0, claim_json=NULL, failure_json=?11,
                 updated_at=?12, review_json=?14
             WHERE task_id=?1 AND position_version=?13 AND claim_json IS NULL",
            params![
                task_id.as_str(),
                serde_json::to_string(&position.invocation)?,
                step.flow,
                step.step,
                step.policy.id,
                step.policy.human,
                position.session_run_id.as_ref().map(RunId::as_str),
                position.ready_summary,
                i64::try_from(position.cursor.index).map_err(invalid_durable)?,
                i64::from(position.cursor.iteration),
                failure_json,
                position.updated_at.unix_timestamp(),
                i64::try_from(position.version).map_err(invalid_durable)?,
                serde_json::to_string(&position.cursor)?
            ],
        )?
    };
    if changed != 1 {
        return Err(StoreError::InvalidAuthority(format!(
            "Flow position for Task {task_id} changed or is actively claimed"
        )));
    }
    flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)
}

pub(super) fn block_task_flow_in(
    conn: &Connection,
    task_id: &TaskId,
    expected: &TaskWorkerClaim,
    failure: &TaskFlowBlocker,
) -> StoreResult<FlowPosition> {
    require_ready_work(conn, &WorkRef::Task(task_id.clone()))?;
    let expected_json = serde_json::to_string(expected)?;
    let failure_json = serde_json::to_string(failure)?;
    let mut position = flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)?;
    let leaf = position.cursor.leaf_mut();
    leaf.progress.verdict = None;
    leaf.route = None;
    if conn.execute(
        "UPDATE task_flow_positions
         SET claim_json=NULL, failure_json=?2, updated_at=?3, review_json=?6
         WHERE task_id=?1 AND position_version=?4 AND claim_json=?5",
        params![
            task_id.as_str(),
            failure_json,
            failure.observed_at.unix_timestamp(),
            i64::try_from(expected.position_version).map_err(invalid_durable)?,
            expected_json,
            serde_json::to_string(&position.cursor)?
        ],
    )? != 1
    {
        return Err(stale_task_worker(task_id));
    }
    flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)
}

pub(super) fn release_task_worker_in(
    conn: &Connection,
    task_id: &TaskId,
    expected: &TaskWorkerClaim,
) -> StoreResult<FlowPosition> {
    require_ready_work(conn, &WorkRef::Task(task_id.clone()))?;
    let expected_json = serde_json::to_string(expected)?;
    let mut position = flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)?;
    let leaf = position.cursor.leaf_mut();
    leaf.progress.verdict = None;
    leaf.route = None;
    if conn.execute(
        "UPDATE task_flow_positions
         SET claim_json=NULL, failure_json=NULL, updated_at=?2,
             review_json=?5
         WHERE task_id=?1 AND position_version=?3 AND claim_json=?4",
        params![
            task_id.as_str(),
            OffsetDateTime::now_utc().unix_timestamp(),
            i64::try_from(expected.position_version).map_err(invalid_durable)?,
            expected_json,
            serde_json::to_string(&position.cursor)?
        ],
    )? != 1
    {
        return Err(stale_task_worker(task_id));
    }
    flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)
}

pub(super) fn settle_task_worker_in(
    conn: &Connection,
    task_id: &TaskId,
    expected: &TaskWorkerClaim,
    next: &FlowPosition,
) -> StoreResult<FlowPosition> {
    validate_flow_position(task_id, next)?;
    if expected.worker_run_id.is_none() {
        return Err(StoreError::InvalidAuthority(
            "only a bound Task worker Run may settle a Task Flow".to_string(),
        ));
    }
    if next.version != expected.position_version || next.claim.is_some() || next.failure.is_some() {
        return Err(stale_task_worker(task_id));
    }
    require_ready_work(conn, &WorkRef::Task(task_id.clone()))?;
    let expected_json = serde_json::to_string(expected)?;
    let step = next.current();
    if conn.execute(
        "UPDATE task_flow_positions
         SET invocation_json=?2, flow=?3, step=?4, node_id=?5, human=?6, session_run_id=?7,
             ready_summary=?8, step_index=?9, iteration=?10,
             position_version=position_version + 1,
             worker_generation=0, claim_json=NULL, failure_json=NULL,
             updated_at=?11, review_json=?14
         WHERE task_id=?1 AND position_version=?12 AND claim_json=?13",
        params![
            task_id.as_str(),
            serde_json::to_string(&next.invocation)?,
            step.flow,
            step.step,
            step.policy.id,
            step.policy.human,
            next.session_run_id.as_ref().map(RunId::as_str),
            next.ready_summary,
            i64::try_from(next.cursor.index).map_err(invalid_durable)?,
            i64::from(next.cursor.iteration),
            next.updated_at.unix_timestamp(),
            i64::try_from(expected.position_version).map_err(invalid_durable)?,
            expected_json,
            serde_json::to_string(&next.cursor)?
        ],
    )? != 1
    {
        return Err(stale_task_worker(task_id));
    }
    flow_position_in(conn, task_id)?.ok_or(StoreError::NotFound)
}

pub(super) fn finish_task_flow_in(
    conn: &Connection,
    task_id: &TaskId,
    expected: &TaskWorkerClaim,
) -> StoreResult<()> {
    if expected.worker_run_id.is_none() {
        return Err(StoreError::InvalidAuthority(
            "only a bound Task worker Run may finish a Task Flow".to_string(),
        ));
    }
    require_ready_work(conn, &WorkRef::Task(task_id.clone()))?;
    let expected_json = serde_json::to_string(expected)?;
    if conn.execute(
        "DELETE FROM task_flow_positions
         WHERE task_id=?1 AND position_version=?2 AND claim_json=?3",
        params![
            task_id.as_str(),
            i64::try_from(expected.position_version).map_err(invalid_durable)?,
            expected_json
        ],
    )? != 1
    {
        return Err(stale_task_worker(task_id));
    }
    Ok(())
}

fn decode_flow_progress(
    json: Option<&str>,
    failure: &mut Option<TaskFlowBlocker>,
    observed_at: OffsetDateTime,
) -> StoreResult<crate::engine::transitions::FlowProgress> {
    let Some(json) = json else {
        return Ok(Default::default());
    };
    let mut value: serde_json::Value = serde_json::from_str(json)?;
    if let Some(node) = value
        .get("node_id")
        .and_then(|v| v.as_str())
        .map(str::to_string)
    {
        let count = value
            .get("completed_passes")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        value = serde_json::json!({
            "repeats": {node: count}, "direction": value.get("direction"),
            "verdict": value.get("verdict"),
        });
    }
    // Blocked was historically serialized as a navigation verdict. Preserve
    // its evidence as a retryable stop without inventing a forward decision.
    if value.pointer("/verdict/decision").and_then(|v| v.as_str()) == Some("blocked") {
        let reason = value
            .pointer("/verdict/summary")
            .and_then(|v| v.as_str())
            .ok_or_else(|| StoreError::InvalidData("blocked Flow verdict has no summary".into()))?;
        let reason = if reason.trim().is_empty() {
            "legacy Flow verdict is blocked without evidence"
        } else {
            reason
        };
        match failure {
            Some(existing) if existing.reason != reason => {
                existing
                    .reason
                    .push_str(&format!("\nLegacy Flow blocker: {reason}"));
            }
            Some(_) => {}
            None => {
                *failure = Some(TaskFlowBlocker {
                    reason: reason.into(),
                    restart_required: false,
                    observed_at,
                })
            }
        }
        value["verdict"] = serde_json::Value::Null;
    }
    Ok(serde_json::from_value(value)?)
}

fn decode_flow_position(
    task_id: TaskId,
    (
        invocation_json,
        flow,
        step,
        node_id,
        human,
        session_run_id,
        ready_summary,
        step_index,
        iteration,
        position_version,
        worker_generation,
        claim_json,
        failure_json,
        updated_at,
        review_json,
    ): StoredFlowPosition,
) -> StoreResult<FlowPosition> {
    let updated_at = OffsetDateTime::from_unix_timestamp(updated_at).map_err(invalid_durable)?;
    let mut failure = failure_json
        .map(|failure| serde_json::from_str::<TaskFlowBlocker>(&failure))
        .transpose()?;
    let root_index = usize::try_from(step_index).map_err(invalid_durable)?;
    let root_iteration = u32::try_from(iteration).map_err(invalid_durable)?;
    let saved = review_json
        .as_deref()
        .map(serde_json::from_str::<serde_json::Value>)
        .transpose()?;
    let cursor = match saved {
        Some(value) if value.get("index").is_some() => serde_json::from_value(value)?,
        _ => crate::engine::ExecutionCursor {
            index: root_index,
            iteration: root_iteration,
            progress: decode_flow_progress(review_json.as_deref(), &mut failure, updated_at)?,
            ..Default::default()
        },
    };
    if cursor.index != root_index || cursor.iteration != root_iteration {
        return Err(StoreError::InvalidData(
            "stored Flow cursor does not match its root projection".into(),
        ));
    }
    let position = FlowPosition {
        cursor,
        task_id,
        invocation: serde_json::from_str(&invocation_json)?,
        session_run_id: session_run_id
            .map(|run_id| RunId::parse(&run_id).map_err(invalid_durable))
            .transpose()?,
        ready_summary,
        version: u64::try_from(position_version).map_err(invalid_durable)?,
        worker_generation: u64::try_from(worker_generation).map_err(invalid_durable)?,
        claim: claim_json
            .map(|claim| serde_json::from_str::<TaskWorkerClaim>(&claim))
            .transpose()?,
        failure,
        updated_at,
    };
    validate_flow_position(&position.task_id, &position)?;
    let current = position
        .current_checked()
        .ok_or_else(|| StoreError::InvalidData("Flow position has no current step".to_string()))?;
    if current.flow != flow
        || current.step != step
        || current.policy.id != node_id
        || current.policy.human != human
    {
        return Err(StoreError::InvalidData(
            "stored Flow position projection does not match its invocation".to_string(),
        ));
    }
    Ok(position)
}

fn validate_flow_position(task_id: &TaskId, position: &FlowPosition) -> StoreResult<()> {
    crate::engine::flow::validate_repeats(&position.invocation.steps).map_err(invalid_durable)?;
    if &position.task_id != task_id {
        return Err(StoreError::InvalidAuthority(
            "Flow position does not belong to this Task".to_string(),
        ));
    }
    let step = position
        .current_checked()
        .ok_or_else(|| StoreError::InvalidData("Flow position has no current step".to_string()))?;
    if step.flow.trim().is_empty() || step.step.trim().is_empty() {
        return Err(StoreError::InvalidData(
            "flow and step cannot be empty".to_string(),
        ));
    }
    if step.policy.human && step.policy.id.is_none() {
        return Err(StoreError::InvalidData(
            "review flow positions require a stable node id".to_string(),
        ));
    }
    if position.claim.as_ref().is_some_and(|claim| {
        claim.invocation_id != position.invocation.id
            || claim.position_version != position.version
            || claim.generation != position.worker_generation
    }) {
        return Err(StoreError::InvalidData(
            "Task worker claim does not belong to its Flow position".to_string(),
        ));
    }
    Ok(())
}

fn stale_task_worker(task_id: &TaskId) -> StoreError {
    StoreError::InvalidAuthority(format!("Task worker for {task_id} is stale"))
}

fn invalid_durable(error: impl std::fmt::Display) -> StoreError {
    StoreError::InvalidData(error.to_string())
}

pub(crate) fn create_wave_work(
    tx: &Transaction<'_>,
    wave_id: &WaveId,
    created_at: i64,
) -> StoreResult<()> {
    let work = WorkRef::Wave(wave_id.clone());
    inherit_placement(tx, &work, None, created_at)
}

pub(crate) fn create_project_work(tx: &Transaction<'_>, project: &Project) -> StoreResult<()> {
    let project_id = tx
        .query_row(
            "SELECT id FROM projects WHERE external_project_id=?1",
            [project.plan.id.as_str()],
            |row| row.get::<_, String>(0),
        )
        .optional()?
        .unwrap_or_else(|| ProjectId::new().to_string());
    tx.execute(
        "INSERT OR IGNORE INTO projects (
            id, wave_id, external_project_id, created_at
         ) VALUES (?1, ?2, ?3, ?4)",
        params![
            project_id,
            project.wave_id.as_str(),
            project.plan.id.as_str(),
            project.created_at.unix_timestamp(),
        ],
    )?;
    let work = WorkRef::Project(ProjectId::parse(&project_id).map_err(invalid_durable)?);
    let parent = WorkRef::Wave(project.wave_id.clone());
    inherit_placement(
        tx,
        &work,
        Some(&parent),
        project.created_at.unix_timestamp(),
    )?;
    Ok(())
}

pub(crate) fn create_task_work(tx: &Transaction<'_>, task: &Task) -> StoreResult<()> {
    let project_id = task.project_id.as_str().to_string();
    let task_id = tx
        .query_row(
            "SELECT id FROM tasks WHERE external_issue_id=?1",
            [task.plan.id.as_str()],
            |row| row.get::<_, String>(0),
        )
        .optional()?
        .unwrap_or_else(|| TaskId::new().to_string());
    tx.execute(
        "INSERT OR IGNORE INTO tasks (
            id, project_id, external_issue_id, issue_identifier, created_at
         ) VALUES (?1, ?2, ?3, ?4, ?5)",
        params![
            task_id,
            project_id,
            task.plan.id.as_str(),
            task.plan.identifier,
            task.created_at.unix_timestamp(),
        ],
    )?;
    let work = WorkRef::Task(TaskId::parse(&task_id).map_err(invalid_durable)?);
    let parent = WorkRef::Project(ProjectId::parse(&project_id).map_err(invalid_durable)?);
    inherit_placement(tx, &work, Some(&parent), task.created_at.unix_timestamp())?;
    Ok(())
}

pub(crate) fn work_for_child_in(conn: &Connection, target: &ChildRef) -> StoreResult<WorkRef> {
    match target {
        ChildRef::Project(project_id) => {
            conn.query_row(
                "SELECT 1 FROM projects WHERE id=?1",
                [project_id.as_str()],
                |_| Ok(()),
            )?;
            Ok(WorkRef::Project(project_id.clone()))
        }
        ChildRef::Task(task_id) => {
            conn.query_row(
                "SELECT 1 FROM tasks WHERE id=?1",
                [task_id.as_str()],
                |_| Ok(()),
            )?;
            Ok(WorkRef::Task(task_id.clone()))
        }
    }
}

fn tool_response_in(
    conn: &Connection,
    work: &WorkRef,
    request_id: &str,
) -> StoreResult<Option<ToolResponseReceipt>> {
    let row = conn
        .query_row(
            "SELECT id, choice, responded_at FROM tool_responses
             WHERE work_kind=?1 AND work_id=?2 AND request_id=?3",
            params![work.kind(), work.id(), request_id],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i64>(2)?,
                ))
            },
        )
        .optional()?;
    let Some((id, choice, responded_at)) = row else {
        return Ok(None);
    };
    Ok(Some(ToolResponseReceipt {
        id: ToolResponseId::parse(&id).map_err(|error| {
            StoreError::InvalidData(format!("invalid stored ToolResponse id: {error}"))
        })?,
        work: work.clone(),
        request_id: request_id.to_string(),
        choice,
        responded_at: OffsetDateTime::from_unix_timestamp(responded_at).map_err(|error| {
            StoreError::InvalidData(format!("invalid Decision timestamp: {error}"))
        })?,
    }))
}

#[cfg(test)]
mod durable_store_tests {
    use std::path::PathBuf;
    use std::sync::{Arc, Barrier};
    use std::thread;

    use crate::durable::{
        FlowPosition, ProjectId, RunId, TaskFlowBlocker, TaskId, TaskWorkerClaimOutcome,
        TaskWorkerOwner,
    };
    use crate::engine::execution::NestedCursor;
    use crate::engine::flow::{ConcretePath, ConcreteXor};
    use crate::engine::transitions::{FlowDecision, FlowVerdict};
    use crate::engine::{ConcreteStep, ExecutionCursor, Skill};
    use crate::id::{ExecId, TraceId, WaveId};
    use crate::planning::{LinearIssueId, LinearProjectId, ProjectPlan, TaskPlan};
    use crate::store::sqlite::SqliteStore;
    use crate::work::project::Project;
    use crate::work::task::{PmWritebackState, Task, TaskEventKind, TaskPr, TaskPrId};

    fn store_with_task() -> (tempfile::TempDir, SqliteStore, TaskId) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("loopflow.db");
        let store = SqliteStore::new(&path).expect("open a fresh store");
        let wave_id = WaveId::new();
        let project_id = ProjectId::new();
        let task_id = TaskId::new();
        let now = time::OffsetDateTime::now_utc();
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute(
            "INSERT INTO waves (id, name, repo, created_at, parent_wave_id)
             VALUES (?1, 'probe', '/repo', 1700000000, NULL)",
            [wave_id.as_str()],
        )
        .unwrap();
        drop(conn);
        // Reach the crate-private spine builder the public upsert path calls.
        {
            let mut raw = rusqlite::Connection::open(&path).unwrap();
            let tx = raw.transaction().unwrap();
            super::create_wave_work(&tx, &wave_id, 1_700_000_000).unwrap();
            tx.commit().unwrap();
        }
        let project = Project {
            id: project_id.clone(),
            plan: ProjectPlan {
                id: LinearProjectId::new("project-uuid").unwrap(),
                slug: "probe".to_string(),
                name: "Probe".to_string(),
                prompt_context: "Probe Task execution".to_string(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            wave_id: wave_id.clone(),
            iteration: 0,
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        };
        store.insert_project(&project).unwrap();
        let task = Task {
            id: task_id.clone(),
            plan: TaskPlan {
                id: LinearIssueId::new("task-uuid").unwrap(),
                identifier: "PROBE-1".to_string(),
                title: "Probe Task execution".to_string(),
                description: "Exercise the Task Flow store".to_string(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id,
            project_id,
            worktree: PathBuf::from("/repo.probe"),
            workspace_slug: "probe".to_string(),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::work::task::Observation::NotRequired,
        };
        let pr = TaskPr {
            id: TaskPrId::new(),
            task_id: task_id.clone(),
            sequence: 1,
            slug: "probe".to_string(),
            branch: "probe".to_string(),
            base_commit: "deadbeef".to_string(),
            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: now,
            updated_at: now,
        };
        store.insert_task(&task, &pr).unwrap();
        (dir, store, task_id)
    }

    fn autonomous_position(task_id: &TaskId) -> FlowPosition {
        FlowPosition {
            task_id: task_id.clone(),
            invocation: crate::durable::test_flow_invocation(
                "task",
                0,
                "implement",
                Some("implement"),
                false,
            ),
            session_run_id: None,
            ready_summary: None,
            cursor: Default::default(),
            version: 0,
            worker_generation: 0,
            claim: None,
            failure: None,
            updated_at: time::OffsetDateTime::now_utc(),
        }
    }

    fn owner(pid: u32) -> TaskWorkerOwner {
        TaskWorkerOwner {
            trace_id: TraceId::new(),
            exec_id: ExecId::new(),
            pid,
            started_at: 1_700_000_000,
        }
    }

    #[test]
    fn legacy_flow_decisions_preserve_pinned_progress() {
        let (_dir, store, task_id) = store_with_task();
        let mut position = autonomous_position(&task_id);
        position.invocation = crate::engine::invocation::QueuedInvocation::load(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
            "pursue",
        )
        .unwrap();
        position.cursor.index = 4;
        position.cursor.iteration = 5;
        let position = store.set_flow_position(&task_id, &position).unwrap();
        for (saved, expected) in [
            ("continue", FlowDecision::Iterate),
            ("complete", FlowDecision::Advance),
            ("repeat", FlowDecision::Iterate),
            ("next", FlowDecision::Advance),
        ] {
            for legacy_shape in [true, false] {
                let verdict = serde_json::json!({"decision": saved, "summary": "saved proof"});
                let json = if legacy_shape {
                    serde_json::json!({"node_id": "decide", "completed_passes": 2,
                        "direction": "previous direction", "verdict": verdict})
                } else {
                    serde_json::json!({"repeats": {"decide": 2},
                        "direction": "previous direction", "verdict": verdict})
                }
                .to_string();
                store
                    .conn
                    .lock()
                    .unwrap()
                    .execute(
                        "UPDATE task_flow_positions SET review_json=?2 WHERE task_id=?1",
                        rusqlite::params![task_id.as_str(), json],
                    )
                    .unwrap();
                let recovered = store.flow_position(&task_id).unwrap().unwrap();
                assert_eq!(recovered.invocation, position.invocation);
                assert_eq!(recovered.cursor.index, position.cursor.index);
                assert_eq!(recovered.cursor.iteration, position.cursor.iteration);
                assert_eq!(recovered.cursor.progress.repeats["decide"], 2);
                assert_eq!(
                    recovered.cursor.progress.direction.as_deref(),
                    Some("previous direction")
                );
                assert_eq!(
                    recovered.cursor.progress.verdict.as_ref().unwrap().decision,
                    expected
                );
                assert_eq!(
                    recovered.cursor.progress.verdict.as_ref().unwrap().summary,
                    "saved proof"
                );
                assert!(recovered.failure.is_none());
            }
        }
    }

    #[test]
    fn legacy_blocked_verdict_stops_and_retries_without_advancing() {
        for legacy_shape in [true, false] {
            let (_dir, store, task_id) = store_with_task();
            let mut position = autonomous_position(&task_id);
            position.invocation = crate::engine::invocation::QueuedInvocation::load(
                std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
                "pursue",
            )
            .unwrap();
            position.cursor.index = 4;
            let position = store.set_flow_position(&task_id, &position).unwrap();
            let verdict =
                serde_json::json!({"decision": "blocked", "summary": "need a policy choice"});
            let json = if legacy_shape {
                serde_json::json!({"node_id": "decide", "completed_passes": 2,
                    "direction": "previous direction", "verdict": verdict})
            } else {
                serde_json::json!({"repeats": {"decide": 2},
                    "direction": "previous direction", "verdict": verdict})
            }
            .to_string();
            store
                .conn
                .lock()
                .unwrap()
                .execute(
                    "UPDATE task_flow_positions SET review_json=?2 WHERE task_id=?1",
                    rusqlite::params![task_id.as_str(), json],
                )
                .unwrap();
            let blocked = store.flow_position(&task_id).unwrap().unwrap();
            let failure = blocked.failure.as_ref().unwrap();
            assert_eq!(failure.reason, "need a policy choice");
            assert!(!failure.restart_required);
            assert_eq!(failure.observed_at, blocked.updated_at);
            assert!(!blocked.has_pending_decision());
            assert_eq!(blocked.invocation, position.invocation);
            assert_eq!(blocked.cursor.index, position.cursor.index);
            assert_eq!(blocked.cursor.progress.repeats["decide"], 2);
            assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), blocked);
            let claimed = store
                .claim_task_worker(
                    &task_id,
                    &blocked.invocation.id,
                    blocked.version,
                    &owner(303),
                    time::OffsetDateTime::now_utc(),
                )
                .unwrap();
            assert!(matches!(claimed, TaskWorkerClaimOutcome::Claimed(_)));
            let retry = store.flow_position(&task_id).unwrap().unwrap();
            assert!(retry.failure.is_none());
            assert!(!retry.has_pending_decision());
            assert_eq!(retry.cursor.index, blocked.cursor.index);
            assert_eq!(retry.invocation, blocked.invocation);
            assert_eq!(retry.cursor.progress, blocked.cursor.progress);
        }
    }

    #[test]
    fn loop_verdict_survives_recovery_and_rejects_unrelated_runs() {
        let (_dir, store, task_id) = store_with_task();
        let mut position = autonomous_position(&task_id);
        position.invocation = crate::engine::invocation::QueuedInvocation::load(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
            "feature",
        )
        .unwrap();
        position.cursor.index = 6;
        let position = store.set_flow_position(&task_id, &position).unwrap();
        let first_owner = owner(301);
        let claim = match store
            .claim_task_worker(
                &task_id,
                &position.invocation.id,
                position.version,
                &first_owner,
                time::OffsetDateTime::now_utc(),
            )
            .unwrap()
        {
            crate::durable::TaskWorkerClaimOutcome::Claimed(claim) => claim,
            other => panic!("unexpected {other:?}"),
        };
        let run = RunId::new();
        let bound = store
            .bind_task_worker_run(&task_id, &claim, &run, &first_owner)
            .unwrap();
        let verdict = crate::engine::transitions::FlowVerdict {
            decision: crate::engine::transitions::FlowDecision::Iterate,
            summary: "repair the missing case".into(),
        };
        let before = store.flow_position(&task_id).unwrap().unwrap();
        assert!(store
            .record_flow_verdict(&task_id, &RunId::new(), &verdict)
            .is_err());
        assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), before);
        store.record_flow_verdict(&task_id, &run, &verdict).unwrap();
        store.record_flow_verdict(&task_id, &run, &verdict).unwrap();
        let different = crate::engine::transitions::FlowVerdict {
            decision: crate::engine::transitions::FlowDecision::Advance,
            summary: "changed mind".into(),
        };
        let before = store.flow_position(&task_id).unwrap().unwrap();
        assert!(store
            .record_flow_verdict(&task_id, &run, &different)
            .is_err());
        assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), before);
        let replacement = store
            .reclaim_task_worker(
                &task_id,
                &bound,
                &owner(302),
                time::OffsetDateTime::now_utc(),
            )
            .unwrap();
        let before = store.flow_position(&task_id).unwrap().unwrap();
        assert!(store.record_flow_verdict(&task_id, &run, &verdict).is_err());
        assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), before);
        let recovered = store.flow_position(&task_id).unwrap().unwrap();
        assert_eq!(recovered.cursor.progress.verdict, Some(verdict));
        assert_eq!(recovered.claim, Some(replacement.clone()));
        // A reported provider failure differs from a crash: its result cannot
        // authorize a later retry, even though the review direction survives.
        let released = store.release_task_worker(&task_id, &replacement).unwrap();
        assert!(released.cursor.progress.verdict.is_none());
    }

    #[test]
    fn nested_cursor_recovers_routes_and_verdicts_under_exact_worker_authority() {
        for routing in [true, false] {
            let (_dir, store, task_id) = store_with_task();
            let mut position = autonomous_position(&task_id);
            let body = crate::engine::invocation::QueuedInvocation::load(
                std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
                "pursue",
            )
            .unwrap()
            .steps;
            let branch = ConcreteStep::Xor(ConcreteXor {
                router: Skill::named("nested-router"),
                paths: ["chosen", "other"]
                    .into_iter()
                    .map(|name| {
                        (
                            name.into(),
                            ConcretePath {
                                description: name.into(),
                                steps: body.clone(),
                            },
                        )
                    })
                    .collect(),
                flow_parents: Vec::new(),
            });
            let steps = if routing { vec![branch] } else { body };
            position.invocation.steps = vec![ConcreteStep::Xor(ConcreteXor {
                router: Skill::named("outer-router"),
                paths: [(
                    "outer".into(),
                    ConcretePath {
                        description: "outer".into(),
                        steps,
                    },
                )]
                .into_iter()
                .collect(),
                flow_parents: Vec::new(),
            })];
            position.cursor.iteration = 7;
            position.cursor.progress.repeats.insert("root".into(), 3);
            let mut leaf = ExecutionCursor {
                index: if routing { 0 } else { 4 },
                iteration: 2,
                ..Default::default()
            };
            leaf.progress.repeats.insert("decide".into(), 1);
            leaf.progress.direction = Some("preserved direction".into());
            position.cursor.child = Some(Box::new(NestedCursor::Xor {
                selected: "outer".into(),
                cursor: leaf,
            }));
            let position = store.set_flow_position(&task_id, &position).unwrap();
            assert_eq!(position.current().iteration, 7);
            assert_eq!(
                position.current().step,
                if routing {
                    "nested-router"
                } else {
                    "loop-decide"
                }
            );
            let saved = store.set_flow_position(&task_id, &position).unwrap();
            assert_eq!(saved.cursor, position.cursor);
            let worker = owner(501);
            let TaskWorkerClaimOutcome::Claimed(claim) = store
                .claim_task_worker(
                    &task_id,
                    &saved.invocation.id,
                    saved.version,
                    &worker,
                    time::OffsetDateTime::now_utc(),
                )
                .unwrap()
            else {
                panic!("worker must be claimed")
            };
            let run = RunId::new();
            let bound = store
                .bind_task_worker_run(&task_id, &claim, &run, &worker)
                .unwrap();
            let verdict = FlowVerdict {
                decision: FlowDecision::Iterate,
                summary: "next pass".into(),
            };
            if routing {
                let before = store.flow_position(&task_id).unwrap().unwrap();
                assert!(store
                    .record_flow_route(&task_id, &RunId::new(), "chosen")
                    .is_err());
                assert!(store.record_flow_route(&task_id, &run, "missing").is_err());
                assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), before);
                store.record_flow_route(&task_id, &run, "chosen").unwrap();
                store.record_flow_route(&task_id, &run, "chosen").unwrap();
                let before = store.flow_position(&task_id).unwrap().unwrap();
                assert!(store.record_flow_route(&task_id, &run, "other").is_err());
                assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), before);
            } else {
                store.record_flow_verdict(&task_id, &run, &verdict).unwrap();
                assert!(store.record_flow_route(&task_id, &run, "chosen").is_err());
            }
            let pending = store.flow_position(&task_id).unwrap().unwrap();
            assert!(pending.has_pending_decision());
            assert_eq!(pending.cursor.progress, saved.cursor.progress);
            let replacement = store
                .reclaim_task_worker(
                    &task_id,
                    &bound,
                    &owner(502),
                    time::OffsetDateTime::now_utc(),
                )
                .unwrap();
            let recovered = store.flow_position(&task_id).unwrap().unwrap();
            assert_eq!(recovered.cursor, pending.cursor);
            assert!(store.record_flow_route(&task_id, &run, "chosen").is_err());
            assert!(store.record_flow_verdict(&task_id, &run, &verdict).is_err());
            assert_eq!(store.flow_position(&task_id).unwrap().unwrap(), recovered);
            let cleared = if routing {
                store
                    .block_task_flow(
                        &task_id,
                        &replacement,
                        &TaskFlowBlocker {
                            reason: "router failed after publishing".into(),
                            restart_required: false,
                            observed_at: time::OffsetDateTime::now_utc(),
                        },
                    )
                    .unwrap()
            } else {
                store.release_task_worker(&task_id, &replacement).unwrap()
            };
            assert_eq!(cleared.cursor, saved.cursor);
            assert!(!cleared.has_pending_decision());
        }
    }

    #[test]
    fn human_session_runtime_survives_a_store_round_trip() {
        let (_dir, store, work) = store_with_task();
        let run_id = RunId::new();
        let position = FlowPosition {
            task_id: work.clone(),
            invocation: crate::durable::test_flow_invocation(
                "review",
                1,
                "review-design",
                Some("human_review"),
                true,
            ),
            session_run_id: Some(run_id.clone()),
            ready_summary: Some("Ready for review".to_string()),
            cursor: crate::engine::ExecutionCursor {
                index: 1,
                iteration: 2,
                ..Default::default()
            },
            version: 0,
            worker_generation: 0,
            claim: None,
            failure: None,
            updated_at: time::OffsetDateTime::now_utc(),
        };

        store.set_flow_position(&work, &position).unwrap();

        let stored = store.flow_position(&work).unwrap().unwrap();
        assert_eq!(stored.session_run_id, Some(run_id));
        assert_eq!(stored.ready_summary.as_deref(), Some("Ready for review"));
    }

    #[test]
    fn concurrent_task_worker_claims_choose_one_worker() {
        let (dir, store, work) = store_with_task();
        let position = store
            .set_flow_position(&work, &autonomous_position(&work))
            .unwrap();
        let barrier = Arc::new(Barrier::new(20));
        let stores = (0..20)
            .map(|_| SqliteStore::new(&dir.path().join("loopflow.db")).unwrap())
            .collect::<Vec<_>>();
        let handles = stores
            .into_iter()
            .enumerate()
            .map(|(index, store)| {
                let work = work.clone();
                let position = position.clone();
                let barrier = barrier.clone();
                thread::spawn(move || {
                    barrier.wait();
                    store
                        .claim_task_worker(
                            &work,
                            &position.invocation.id,
                            position.version,
                            &owner(1_000 + u32::try_from(index).unwrap()),
                            time::OffsetDateTime::from_unix_timestamp(1_700_000_100).unwrap(),
                        )
                        .unwrap()
                })
            })
            .collect::<Vec<_>>();
        let outcomes = handles
            .into_iter()
            .map(|handle| handle.join().unwrap())
            .collect::<Vec<_>>();
        let claimed = outcomes
            .iter()
            .filter_map(|outcome| match outcome {
                TaskWorkerClaimOutcome::Claimed(claim) => Some(claim),
                _ => None,
            })
            .collect::<Vec<_>>();

        assert_eq!(claimed.len(), 1);
        assert_eq!(claimed[0].generation, 1);
        assert!(outcomes.iter().all(|outcome| match outcome {
            TaskWorkerClaimOutcome::Claimed(claim) | TaskWorkerClaimOutcome::Busy(claim) =>
                claim == claimed[0],
            TaskWorkerClaimOutcome::Stale { .. } => false,
        }));
    }

    #[test]
    fn only_the_bound_worker_can_settle_a_position() {
        let (_dir, store, work) = store_with_task();
        let task = store.task(&work).unwrap().unwrap();
        let mut initial = autonomous_position(&work);
        initial.invocation = crate::durable::test_flow_invocation("task", 1, "review", None, false);
        let position = store.set_flow_position(&work, &initial).unwrap();
        let claim = match store
            .claim_task_worker(
                &work,
                &position.invocation.id,
                position.version,
                &owner(101),
                time::OffsetDateTime::now_utc(),
            )
            .unwrap()
        {
            TaskWorkerClaimOutcome::Claimed(claim) => claim,
            outcome => panic!("unexpected claim outcome: {outcome:?}"),
        };
        let worker_run_id = RunId::new();
        let bound = store
            .bind_task_worker_run(&work, &claim, &worker_run_id, &owner(102))
            .unwrap();
        let mut next = store.flow_position(&work).unwrap().unwrap();
        next.cursor.index = 1;
        next.claim = None;
        next.updated_at = time::OffsetDateTime::now_utc();

        assert!(store
            .settle_task_worker(&task, &claim, &next, Some("advanced"))
            .is_err());
        let settled = store
            .settle_task_worker(&task, &bound, &next, Some("advanced"))
            .unwrap();
        assert_eq!(settled.version, position.version + 1);
        assert_eq!(settled.current().step, "review");
        assert_eq!(settled.invocation, position.invocation);
        assert_eq!(settled.worker_generation, 0);
        assert!(settled.claim.is_none());
        assert!(store
            .settle_task_worker(&task, &bound, &next, Some("advanced"))
            .is_err());
        let events = store.task_events_after(&work, 0).unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind, TaskEventKind::Started);
        assert!(matches!(
            &events[1].kind,
            TaskEventKind::Progress { summary } if summary == "advanced"
        ));
    }

    #[test]
    fn only_the_bound_worker_can_finish_a_position_without_a_successor() {
        let (_dir, store, work) = store_with_task();
        let task = store.task(&work).unwrap().unwrap();
        let position = store
            .set_flow_position(&work, &autonomous_position(&work))
            .unwrap();
        let claim = match store
            .claim_task_worker(
                &work,
                &position.invocation.id,
                position.version,
                &owner(111),
                time::OffsetDateTime::now_utc(),
            )
            .unwrap()
        {
            TaskWorkerClaimOutcome::Claimed(claim) => claim,
            outcome => panic!("unexpected claim outcome: {outcome:?}"),
        };
        let bound = store
            .bind_task_worker_run(&work, &claim, &RunId::new(), &owner(112))
            .unwrap();

        assert!(store
            .finish_task_flow(&task, &claim, Some("finished"))
            .is_err());
        store
            .finish_task_flow(&task, &bound, Some("finished"))
            .unwrap();
        assert!(store.flow_position(&work).unwrap().is_none());
        assert!(store
            .finish_task_flow(&task, &bound, Some("finished"))
            .is_err());
        let events = store.task_events_after(&work, 0).unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind, TaskEventKind::Started);
        assert!(matches!(
            &events[1].kind,
            TaskEventKind::FlowFinished { summary, .. } if summary == "finished"
        ));
    }

    #[test]
    fn reclaim_fences_the_old_worker_and_increments_generation() {
        let (_dir, store, work) = store_with_task();
        let position = store
            .set_flow_position(&work, &autonomous_position(&work))
            .unwrap();
        let first = match store
            .claim_task_worker(
                &work,
                &position.invocation.id,
                position.version,
                &owner(201),
                time::OffsetDateTime::now_utc(),
            )
            .unwrap()
        {
            TaskWorkerClaimOutcome::Claimed(claim) => claim,
            outcome => panic!("unexpected claim outcome: {outcome:?}"),
        };
        let replacement = store
            .reclaim_task_worker(&work, &first, &owner(202), time::OffsetDateTime::now_utc())
            .unwrap();

        assert_eq!(replacement.generation, 2);
        assert!(store
            .bind_task_worker_run(&work, &first, &RunId::new(), &owner(203))
            .is_err());

        let bound = store
            .bind_task_worker_run(&work, &replacement, &RunId::new(), &owner(204))
            .unwrap();
        let failure = TaskFlowBlocker {
            reason: "provider exited".to_string(),
            restart_required: false,
            observed_at: time::OffsetDateTime::now_utc(),
        };
        let failed = store.block_task_flow(&work, &bound, &failure).unwrap();
        assert!(failed.claim.is_none());
        assert_eq!(failed.failure.as_ref(), Some(&failure));
        assert!(store.block_task_flow(&work, &first, &failure).is_err());
        let events = store.task_events_after(&work, 0).unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].kind, TaskEventKind::Started);
        assert!(matches!(
            &events[1].kind,
            TaskEventKind::Failed { error, resumable: true } if error == &failure.reason
        ));

        let retried = match store
            .claim_task_worker(
                &work,
                &position.invocation.id,
                position.version,
                &owner(205),
                time::OffsetDateTime::now_utc(),
            )
            .unwrap()
        {
            TaskWorkerClaimOutcome::Claimed(claim) => claim,
            outcome => panic!("unexpected claim outcome: {outcome:?}"),
        };
        assert_eq!(retried.generation, 3);
        assert!(store
            .flow_position(&work)
            .unwrap()
            .unwrap()
            .failure
            .is_none());
    }
}