aidaemon-work 0.28.0

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
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
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
use super::*;
use crate::traits::{
    DEFAULT_PROJECT_ID, GOAL_RUN_MISSED, GoalRun, HandoffArtifact, TaskAttempt, TaskAttemptPatch,
    TaskHandoff, TaskJournalEntry, TaskWorkspace, WorkCoordinationStore, WorkGoalSummary,
    WorkProject, WorkTaskSummary, WorkerProfile,
};

const DEFAULT_LEASE_SECS: i64 = 180;

fn normalized_lease_secs(lease_secs: i64) -> i64 {
    if lease_secs <= 0 {
        DEFAULT_LEASE_SECS
    } else {
        lease_secs.clamp(30, 3600)
    }
}

fn goal_run_from_row(row: &sqlx::sqlite::SqliteRow) -> GoalRun {
    GoalRun {
        id: row.get("id"),
        project_id: row.get("project_id"),
        goal_id: row.get("goal_id"),
        trigger_type: row.get("trigger_type"),
        schedule_id: row.get("schedule_id"),
        root_task_id: row.get("root_task_id"),
        status: row.get("status"),
        outcome_summary: row.get("outcome_summary"),
        started_at: row.get("started_at"),
        completed_at: row.get("completed_at"),
        created_at: row.get("created_at"),
        updated_at: row.get("updated_at"),
    }
}

fn task_attempt_from_row(row: &sqlx::sqlite::SqliteRow) -> TaskAttempt {
    TaskAttempt {
        id: row.get("id"),
        task_id: row.get("task_id"),
        goal_run_id: row.get("goal_run_id"),
        worker_profile_id: row.get("worker_profile_id"),
        worker_instance_id: row.get("worker_instance_id"),
        lease_token: row.get("lease_token"),
        status: row.get("status"),
        lease_expires_at: row.get("lease_expires_at"),
        last_heartbeat_at: row.get("last_heartbeat_at"),
        workspace_id: row.get("workspace_id"),
        started_at: row.get("started_at"),
        completed_at: row.get("completed_at"),
    }
}

fn worker_profile_from_row(row: &sqlx::sqlite::SqliteRow) -> WorkerProfile {
    WorkerProfile {
        id: row.get("id"),
        project_id: row.get("project_id"),
        name: row.get("name"),
        specialist: row.get("specialist"),
        model: row.get("model"),
        tools_json: row.get("tools_json"),
        max_iterations: row.get("max_iterations"),
        tool_budget: row.get("tool_budget"),
        timeout_secs: row.get("timeout_secs"),
        max_concurrency: row.get("max_concurrency"),
        workspace_policy: row.get("workspace_policy"),
        memory_scope: row.get("memory_scope"),
        version: row.get("version"),
        enabled: row.get::<i64, _>("enabled") != 0,
        created_at: row.get("created_at"),
        updated_at: row.get("updated_at"),
    }
}

fn task_from_row(row: &sqlx::sqlite::SqliteRow) -> Task {
    Task {
        id: row.get("id"),
        goal_id: row.get("goal_id"),
        description: row.get("description"),
        status: row.get("status"),
        priority: row.get("priority"),
        task_order: row.get("task_order"),
        parallel_group: row.get("parallel_group"),
        depends_on: row.get("depends_on"),
        agent_id: row.get("agent_id"),
        context: row.get("context"),
        result: row.get("result"),
        error: row.get("error"),
        blocker: row.get("blocker"),
        idempotent: row.get::<i64, _>("idempotent") != 0,
        retry_count: row.get("retry_count"),
        max_retries: row.get("max_retries"),
        created_at: row.get("created_at"),
        started_at: row.get("started_at"),
        completed_at: row.get("completed_at"),
    }
}

async fn insert_journal<S: WorkDatabase>(
    db: &S,
    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    entry: &TaskJournalEntry,
) -> anyhow::Result<()> {
    let payload = entry.payload.as_deref().map(|text| db.redact_secrets(text));
    sqlx::query(
        "INSERT INTO task_journal
            (id, project_id, goal_id, goal_run_id, task_id, attempt_id,
             entry_type, actor_type, actor_id, source_channel, body, payload, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(&entry.id)
    .bind(&entry.project_id)
    .bind(&entry.goal_id)
    .bind(&entry.goal_run_id)
    .bind(&entry.task_id)
    .bind(&entry.attempt_id)
    .bind(&entry.entry_type)
    .bind(&entry.actor_type)
    .bind(&entry.actor_id)
    .bind(&entry.source_channel)
    .bind(db.redact_secrets(&entry.body))
    .bind(payload)
    .bind(&entry.created_at)
    .execute(&mut **tx)
    .await?;
    Ok(())
}

async fn task_scope(
    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    task_id: &str,
) -> anyhow::Result<Option<(String, String, String)>> {
    let row = sqlx::query(
        "SELECT g.project_id, t.goal_id, t.goal_run_id
         FROM tasks t
         JOIN goals g ON g.id = t.goal_id
         WHERE t.id = ?",
    )
    .bind(task_id)
    .fetch_optional(&mut **tx)
    .await?;
    Ok(row.map(|row| {
        (
            row.get("project_id"),
            row.get("goal_id"),
            row.get("goal_run_id"),
        )
    }))
}

async fn close_pending_task_escalations(
    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    task_id: &str,
) -> anyhow::Result<()> {
    sqlx::query(
        "UPDATE notification_queue
         SET delivered_at = datetime('now')
         WHERE task_id = ? AND notification_type = 'escalation'
           AND delivered_at IS NULL",
    )
    .bind(task_id)
    .execute(&mut **tx)
    .await?;
    Ok(())
}

#[async_trait]
impl<S: WorkDatabase> WorkCoordinationStore for S {
    async fn create_work_project(
        &self,
        name: &str,
        description: Option<&str>,
    ) -> anyhow::Result<WorkProject> {
        let name = name.trim();
        anyhow::ensure!(!name.is_empty(), "project name cannot be empty");
        anyhow::ensure!(name.chars().count() <= 80, "project name is too long");
        let now = chrono::Utc::now().to_rfc3339();
        let project = WorkProject {
            id: format!("project-{}", uuid::Uuid::new_v4()),
            name: name.to_string(),
            description: description
                .map(str::trim)
                .filter(|v| !v.is_empty())
                .map(str::to_string),
            path: None,
            created_at: now.clone(),
            updated_at: now,
        };
        sqlx::query(
            "INSERT INTO work_projects (id, name, description, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?)",
        )
        .bind(&project.id)
        .bind(&project.name)
        .bind(&project.description)
        .bind(&project.created_at)
        .bind(&project.updated_at)
        .execute(self.work_pool())
        .await?;
        Ok(project)
    }

    async fn list_work_projects(&self) -> anyhow::Result<Vec<WorkProject>> {
        let rows = sqlx::query(
            "SELECT id, name, description, path, created_at, updated_at
             FROM work_projects ORDER BY name COLLATE NOCASE",
        )
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows
            .iter()
            .map(|row| WorkProject {
                id: row.get("id"),
                name: row.get("name"),
                description: row.get("description"),
                path: row.get("path"),
                created_at: row.get("created_at"),
                updated_at: row.get("updated_at"),
            })
            .collect())
    }

    async fn update_work_project(
        &self,
        id: &str,
        name: Option<&str>,
        path: Option<Option<&str>>,
    ) -> anyhow::Result<Option<WorkProject>> {
        let name = name.map(str::trim);
        if let Some(name) = name {
            anyhow::ensure!(!name.is_empty(), "project name cannot be empty");
            anyhow::ensure!(name.chars().count() <= 80, "project name is too long");
        }
        let path = path.map(|p| p.map(str::trim).filter(|p| !p.is_empty()));
        let now = chrono::Utc::now().to_rfc3339();
        let updated = sqlx::query(
            "UPDATE work_projects
             SET name = COALESCE(?, name),
                 path = CASE WHEN ? THEN ? ELSE path END,
                 updated_at = ?
             WHERE id = ?",
        )
        .bind(name)
        .bind(path.is_some())
        .bind(path.flatten())
        .bind(&now)
        .bind(id)
        .execute(self.work_pool())
        .await?
        .rows_affected();
        if updated == 0 {
            return Ok(None);
        }
        Ok(self
            .list_work_projects()
            .await?
            .into_iter()
            .find(|project| project.id == id))
    }

    async fn delete_work_project(&self, id: &str) -> anyhow::Result<bool> {
        anyhow::ensure!(
            id != DEFAULT_PROJECT_ID,
            "conversations in no project cannot be deleted"
        );
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        for moved in [
            "UPDATE session_work_projects SET project_id = ?, updated_at = datetime('now') WHERE project_id = ?",
            "UPDATE goals SET project_id = ? WHERE project_id = ?",
            "UPDATE goal_runs SET project_id = ? WHERE project_id = ?",
            "UPDATE task_journal SET project_id = ? WHERE project_id = ?",
        ] {
            sqlx::query(moved)
                .bind(DEFAULT_PROJECT_ID)
                .bind(id)
                .execute(&mut *tx)
                .await?;
        }
        for gone in [
            "DELETE FROM channel_work_projects WHERE project_id = ?",
            "DELETE FROM worker_profiles WHERE project_id = ?",
        ] {
            sqlx::query(gone).bind(id).execute(&mut *tx).await?;
        }
        let deleted = sqlx::query("DELETE FROM work_projects WHERE id = ?")
            .bind(id)
            .execute(&mut *tx)
            .await?
            .rows_affected();
        if deleted == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        tx.commit().await?;
        Ok(true)
    }

    async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(sqlx::query_as::<_, (String, String)>(
            "SELECT session_id, project_id FROM session_work_projects WHERE project_id != ?",
        )
        .bind(DEFAULT_PROJECT_ID)
        .fetch_all(self.work_pool())
        .await?)
    }

    async fn get_session_work_project(&self, session_id: &str) -> anyhow::Result<String> {
        let project = sqlx::query_scalar::<_, String>(
            "SELECT project_id FROM session_work_projects WHERE session_id = ?",
        )
        .bind(session_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(project.unwrap_or_else(|| DEFAULT_PROJECT_ID.to_string()))
    }

    async fn set_session_work_project(
        &self,
        session_id: &str,
        project_id: &str,
    ) -> anyhow::Result<bool> {
        let exists =
            sqlx::query_scalar::<_, i64>("SELECT 1 FROM work_projects WHERE id = ? LIMIT 1")
                .bind(project_id)
                .fetch_optional(self.work_pool())
                .await?
                .is_some();
        if !exists {
            return Ok(false);
        }
        sqlx::query(
            "INSERT INTO session_work_projects (session_id, project_id, updated_at)
             VALUES (?, ?, datetime('now'))
             ON CONFLICT(session_id) DO UPDATE
             SET project_id = excluded.project_id, updated_at = excluded.updated_at",
        )
        .bind(session_id)
        .bind(project_id)
        .execute(self.work_pool())
        .await?;
        Ok(true)
    }

    async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(sqlx::query_as::<_, (String, String)>(
            "SELECT channel, project_id FROM channel_work_projects ORDER BY channel",
        )
        .fetch_all(self.work_pool())
        .await?)
    }

    async fn set_channel_work_project(
        &self,
        channel: &str,
        project_id: Option<&str>,
    ) -> anyhow::Result<bool> {
        let Some(project_id) = project_id.filter(|id| *id != DEFAULT_PROJECT_ID) else {
            sqlx::query("DELETE FROM channel_work_projects WHERE channel = ?")
                .bind(channel)
                .execute(self.work_pool())
                .await?;
            return Ok(true);
        };
        let exists =
            sqlx::query_scalar::<_, i64>("SELECT 1 FROM work_projects WHERE id = ? LIMIT 1")
                .bind(project_id)
                .fetch_optional(self.work_pool())
                .await?
                .is_some();
        if !exists {
            return Ok(false);
        }
        sqlx::query(
            "INSERT INTO channel_work_projects (channel, project_id, updated_at)
             VALUES (?, ?, datetime('now'))
             ON CONFLICT(channel) DO UPDATE
             SET project_id = excluded.project_id, updated_at = excluded.updated_at",
        )
        .bind(channel)
        .bind(project_id)
        .execute(self.work_pool())
        .await?;
        Ok(true)
    }

    async fn place_chat_by_channel(&self, session_id: &str, channel: &str) -> anyhow::Result<bool> {
        // One statement: a chat placed meanwhile (by the owner) keeps its
        // place.
        let placed = sqlx::query(
            "INSERT INTO session_work_projects (session_id, project_id, updated_at)
             SELECT ?, project_id, datetime('now') FROM channel_work_projects
             WHERE channel = ?
             ON CONFLICT(session_id) DO NOTHING",
        )
        .bind(session_id)
        .bind(channel)
        .execute(self.work_pool())
        .await?;
        Ok(placed.rows_affected() > 0)
    }

    async fn start_goal_run(
        &self,
        goal_id: &str,
        trigger_type: &str,
        schedule_id: Option<&str>,
        root_task_id: Option<&str>,
    ) -> anyhow::Result<GoalRun> {
        anyhow::ensure!(
            matches!(
                trigger_type,
                "finite" | "scheduled" | "manual" | "mandate" | "recovery" | "legacy"
            ),
            "unsupported goal run trigger type"
        );
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let project_id = sqlx::query_scalar::<_, String>(
            "SELECT project_id FROM goals
             WHERE id = ? AND domain = 'orchestration'",
        )
        .bind(goal_id)
        .fetch_optional(&mut *tx)
        .await?
        .ok_or_else(|| anyhow::anyhow!("goal not found or not dispatchable"))?;

        if let Some(row) = sqlx::query(
            "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
                    status, outcome_summary, started_at, completed_at, created_at, updated_at
             FROM goal_runs
             WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')
             ORDER BY julianday(started_at) DESC, id DESC LIMIT 1",
        )
        .bind(goal_id)
        .fetch_optional(&mut *tx)
        .await?
        {
            let mut existing = goal_run_from_row(&row);
            let task_count =
                sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM tasks WHERE goal_run_id = ?")
                    .bind(&existing.id)
                    .fetch_one(&mut *tx)
                    .await?;
            if task_count == 0 {
                sqlx::query(
                    "UPDATE goal_runs
                     SET trigger_type = ?, schedule_id = ?, root_task_id = COALESCE(?, root_task_id),
                         status = 'pending', updated_at = datetime('now')
                     WHERE id = ?",
                )
                .bind(trigger_type)
                .bind(schedule_id)
                .bind(root_task_id)
                .bind(&existing.id)
                .execute(&mut *tx)
                .await?;
                existing.trigger_type = trigger_type.to_string();
                existing.schedule_id = schedule_id.map(str::to_string);
                if root_task_id.is_some() {
                    existing.root_task_id = root_task_id.map(str::to_string);
                }
                existing.status = "pending".to_string();
                existing.updated_at = chrono::Utc::now().to_rfc3339();
                tx.commit().await?;
                return Ok(existing);
            }
            if trigger_type != "scheduled" {
                anyhow::bail!(
                    "goal already has an open run {}; finish or cancel it before starting another",
                    existing.id
                );
            }
        }

        let mut run = GoalRun::new(goal_id, &project_id, trigger_type);
        run.schedule_id = schedule_id.map(str::to_string);
        run.root_task_id = root_task_id.map(str::to_string);
        sqlx::query(
            "INSERT INTO goal_runs
                (id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
                 status, outcome_summary, started_at, completed_at, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&run.id)
        .bind(&run.project_id)
        .bind(&run.goal_id)
        .bind(&run.trigger_type)
        .bind(&run.schedule_id)
        .bind(&run.root_task_id)
        .bind(&run.status)
        .bind(&run.outcome_summary)
        .bind(&run.started_at)
        .bind(&run.completed_at)
        .bind(&run.created_at)
        .bind(&run.updated_at)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(run)
    }

    async fn record_missed_goal_run(
        &self,
        goal_id: &str,
        schedule_id: Option<&str>,
        due_at: &str,
        summary: &str,
    ) -> anyhow::Result<GoalRun> {
        let project_id = sqlx::query_scalar::<_, String>(
            "SELECT project_id FROM goals
             WHERE id = ? AND domain = 'orchestration'",
        )
        .bind(goal_id)
        .fetch_optional(self.work_pool())
        .await?
        .ok_or_else(|| anyhow::anyhow!("goal not found or not dispatchable"))?;
        // Closed from the start: no task, no worker, and never through
        // `finish_goal_run`, so the scheduled recovery ledger (the failure
        // budget that pauses an automation) does not see it.
        let mut run = GoalRun::new(goal_id, &project_id, "scheduled");
        run.schedule_id = schedule_id.map(str::to_string);
        run.status = GOAL_RUN_MISSED.to_string();
        run.outcome_summary = Some(summary.to_string());
        run.started_at = due_at.to_string();
        run.completed_at = Some(run.created_at.clone());
        sqlx::query(
            "INSERT INTO goal_runs
                (id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
                 status, outcome_summary, started_at, completed_at, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&run.id)
        .bind(&run.project_id)
        .bind(&run.goal_id)
        .bind(&run.trigger_type)
        .bind(&run.schedule_id)
        .bind(&run.status)
        .bind(&run.outcome_summary)
        .bind(&run.started_at)
        .bind(&run.completed_at)
        .bind(&run.created_at)
        .bind(&run.updated_at)
        .execute(self.work_pool())
        .await?;
        Ok(run)
    }

    async fn get_current_goal_run(&self, goal_id: &str) -> anyhow::Result<Option<GoalRun>> {
        let row = sqlx::query(
            "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
                    status, outcome_summary, started_at, completed_at, created_at, updated_at
             FROM goal_runs
             WHERE goal_id = ? AND status IN ('pending', 'running', 'blocked')
             ORDER BY julianday(started_at) DESC, id DESC LIMIT 1",
        )
        .bind(goal_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.as_ref().map(goal_run_from_row))
    }

    async fn get_goal_runs(&self, goal_id: &str) -> anyhow::Result<Vec<GoalRun>> {
        let rows = sqlx::query(
            "SELECT id, project_id, goal_id, trigger_type, schedule_id, root_task_id,
                    status, outcome_summary, started_at, completed_at, created_at, updated_at
             FROM goal_runs WHERE goal_id = ?
             ORDER BY julianday(started_at) DESC, id DESC",
        )
        .bind(goal_id)
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows.iter().map(goal_run_from_row).collect())
    }

    async fn get_goal_run_for_task(&self, task_id: &str) -> anyhow::Result<Option<GoalRun>> {
        let row = sqlx::query(
            "SELECT gr.id, gr.project_id, gr.goal_id, gr.trigger_type, gr.schedule_id,
                    gr.root_task_id, gr.status, gr.outcome_summary, gr.started_at,
                    gr.completed_at, gr.created_at, gr.updated_at
             FROM tasks AS t
             JOIN goal_runs AS gr ON gr.id = t.goal_run_id
             WHERE t.id = ?",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.as_ref().map(goal_run_from_row))
    }

    async fn get_tasks_for_goal_run(&self, run_id: &str) -> anyhow::Result<Vec<Task>> {
        let rows = sqlx::query(
            "SELECT id, goal_id, description, status, priority, task_order,
                    parallel_group, depends_on, agent_id, context, result, error, blocker,
                    idempotent, retry_count, max_retries, created_at, started_at, completed_at
             FROM tasks WHERE goal_run_id = ?
             ORDER BY task_order ASC, julianday(created_at) ASC, id ASC",
        )
        .bind(run_id)
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows.iter().map(task_from_row).collect())
    }

    async fn finish_goal_run(
        &self,
        run_id: &str,
        status: &str,
        summary: Option<&str>,
    ) -> anyhow::Result<bool> {
        anyhow::ensure!(
            matches!(status, "completed" | "failed" | "blocked" | "cancelled"),
            "unsupported terminal run status"
        );
        let completed_at = if status == "blocked" {
            None
        } else {
            Some(chrono::Utc::now().to_rfc3339())
        };
        let now = chrono::Utc::now().to_rfc3339();
        // Read-then-write transaction: under WAL a deferred BEGIN loses its
        // snapshot (SQLITE_BUSY_SNAPSHOT, bypassing busy_timeout) when any
        // writer commits between the read and the write. Take the write lock
        // up front so lifecycle reconciliation waits instead of failing with
        // "database is locked" (same shape as the claim/bind fixes).
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let run = sqlx::query(
            "SELECT gr.goal_id, gr.status AS prior_status, gr.trigger_type, gr.root_task_id,
                    g.goal_type, g.session_id, g.description, g.context AS goal_context,
                    EXISTS(SELECT 1 FROM goal_schedules s WHERE s.goal_id = gr.goal_id) AS has_schedule,
                    json_extract(t.context, '$.recovery_for_run') AS recovery_for_run
             FROM goal_runs gr
             JOIN goals g ON g.id = gr.goal_id
             LEFT JOIN tasks t ON t.id = gr.root_task_id
             WHERE gr.id = ?",
        )
        .bind(run_id)
        .fetch_optional(&mut *tx)
        .await?;
        let Some(run) = run else {
            tx.rollback().await?;
            return Ok(false);
        };
        let goal_id: String = run.get("goal_id");
        let prior_status: String = run.get("prior_status");
        let trigger_type: String = run.get("trigger_type");
        let goal_type: String = run.get("goal_type");
        let session_id: String = run.get("session_id");
        let has_schedule = run.get::<i64, _>("has_schedule") != 0;
        let recovery_for_run: Option<String> = run.get("recovery_for_run");
        if trigger_type == "scheduled" && status == "completed" {
            // The run's root task is the lead itself. While it is still
            // active it is the caller completing the run, not an unresolved
            // obligation; counting it made every lead-driven complete_goal
            // fail. A root that ended failed or blocked still counts.
            let root_task_id: Option<String> = run.get("root_task_id");
            let incomplete_task_count = sqlx::query_scalar::<_, i64>(
                "SELECT COUNT(*) FROM tasks
                 WHERE goal_run_id = ?
                   AND NOT (id IS ? AND status IN ('pending', 'claimed', 'running'))
                   -- Mirrors Task::satisfies_run_completion: skipped and
                   -- superseded work is resolved whatever note it carries;
                   -- a completed task must be clean.
                   AND status NOT IN ('skipped', 'superseded')
                   AND (status != 'completed'
                        OR length(trim(COALESCE(error, ''))) > 0
                        OR length(trim(COALESCE(blocker, ''))) > 0)",
            )
            .bind(run_id)
            .bind(root_task_id)
            .fetch_one(&mut *tx)
            .await?;
            anyhow::ensure!(
                incomplete_task_count == 0,
                "scheduled run cannot complete while {incomplete_task_count} task obligation(s) remain unresolved"
            );
        }
        let result = sqlx::query(
            "UPDATE goal_runs
             SET status = ?, outcome_summary = ?, completed_at = ?,
                 updated_at = datetime('now')
             WHERE id = ? AND status IN ('pending', 'running', 'blocked')",
        )
        .bind(status)
        .bind(summary)
        .bind(completed_at)
        .bind(run_id)
        .execute(&mut *tx)
        .await?;
        if result.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        if trigger_type == "scheduled" && matches!(status, "failed" | "cancelled") {
            sqlx::query(
                "UPDATE tasks
                 SET status = 'cancelled',
                     error = COALESCE(NULLIF(error, ''),
                                      'Parent scheduled occurrence reached a terminal state.'),
                     completed_at = COALESCE(completed_at, ?)
                 WHERE goal_run_id = ?
                   AND status IN ('pending', 'claimed', 'running')",
            )
            .bind(&now)
            .bind(run_id)
            .execute(&mut *tx)
            .await?;
        }

        let scheduled_objective = goal_type == "continuous" && has_schedule;
        if scheduled_objective {
            // Consecutive unproven failures a scheduled objective absorbs
            // before it escalates.
            let failure_budget: i64 = 3;
            // Live receipts carry the AGENT-LOOP task id, which exists
            // nowhere in the goals-table task graph. The typed edge from the
            // recovery task to its receipts is the task ATTEMPT: the worker
            // session bound to the root task's attempt is the session every
            // one of its tool_result events is recorded under. Match through
            // both lanes — the direct task-id join stays for flows that emit
            // goal-task ids — so a genuinely verified recovery is recognized
            // instead of being recorded as an unproven failure forever.
            let recovery_proof_receipt_ids = if recovery_for_run.is_some() {
                sqlx::query_scalar::<_, String>(
                    "SELECT json_extract(e.data, '$.tool_call_id') FROM events e
                     JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
                     WHERE t.goal_run_id = ?1 AND e.event_type = 'tool_result'
                       AND json_extract(t.context, '$.terminal_recovery') = 1
                       AND json_extract(t.context, '$.recovery_for_run') = ?2
                       AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
                       AND json_extract(e.data, '$.receipt.outcome_evidence')
                           IN ('tool_reported', 'structured_metadata', 'durable_replay')
                     UNION
                     SELECT json_extract(e.data, '$.tool_call_id') FROM events e
                     JOIN task_attempts ta ON ta.worker_instance_id = e.session_id
                     JOIN tasks t ON t.id = ta.task_id
                     WHERE t.goal_run_id = ?1 AND e.event_type = 'tool_result'
                       AND json_extract(t.context, '$.terminal_recovery') = 1
                       AND json_extract(t.context, '$.recovery_for_run') = ?2
                       AND json_extract(e.data, '$.receipt.outcome_status') = 'succeeded'
                       AND json_extract(e.data, '$.receipt.outcome_evidence')
                           IN ('tool_reported', 'structured_metadata', 'durable_replay')",
                )
                .bind(run_id)
                .bind(recovery_for_run.as_deref())
                .fetch_all(&mut *tx)
                .await?
            } else {
                Vec::new()
            };
            let recovery_completion_verified =
                recovery_for_run.is_none() || !recovery_proof_receipt_ids.is_empty();

            if status == "completed" && recovery_completion_verified {
                sqlx::query(
                    "INSERT INTO scheduled_recovery_state
                        (goal_id, consecutive_failures, failure_budget, disposition,
                         latest_failure_kind, last_failed_run_id, last_recovery_run_id, updated_at)
                     VALUES (?, 0, ?, 'healthy', NULL, NULL, ?, ?)
                     ON CONFLICT(goal_id) DO UPDATE SET
                        consecutive_failures = 0,
                        failure_budget = excluded.failure_budget,
                        disposition = 'healthy',
                        latest_failure_kind = NULL,
                        last_recovery_run_id = COALESCE(excluded.last_recovery_run_id,
                                                        scheduled_recovery_state.last_recovery_run_id),
                        updated_at = excluded.updated_at",
                )
                .bind(&goal_id)
                .bind(failure_budget)
                .bind(recovery_for_run.as_ref().map(|_| run_id))
                .bind(&now)
                .execute(&mut *tx)
                .await?;
                // Resume only schedules this state machine paused. An owner's
                // independent pause is never silently reversed.
                sqlx::query(
                    "UPDATE goal_schedules SET is_paused = 0, updated_at = ?
                     WHERE id IN (
                         SELECT schedule_id FROM scheduled_recovery_paused_schedules
                         WHERE goal_id = ?
                     )",
                )
                .bind(&now)
                .bind(&goal_id)
                .execute(&mut *tx)
                .await?;
                sqlx::query("DELETE FROM scheduled_recovery_paused_schedules WHERE goal_id = ?")
                    .bind(&goal_id)
                    .execute(&mut *tx)
                    .await?;
            } else if (matches!(status, "failed" | "blocked")
                || status == "completed" && !recovery_completion_verified)
                // A run already counted when it blocked must not be counted a
                // second time when its close-out relabels it `failed`;
                // otherwise a three-failure budget escalates after one or two
                // real occurrences.
                && prior_status != "blocked"
            {
                let authorization_blocked = sqlx::query_scalar::<_, i64>(
                    "SELECT 1 FROM events e
                     JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
                     WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
                       AND json_extract(e.data, '$.receipt.authorization_preflight.status')
                           IN ('blocked', 'unverifiable') LIMIT 1",
                )
                .bind(run_id)
                .fetch_optional(&mut *tx)
                .await?
                .is_some();
                let retryable_tool = sqlx::query_scalar::<_, i64>(
                    "SELECT 1 FROM events e
                     JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
                     WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
                       AND json_extract(e.data, '$.receipt.outcome_status') = 'failed_retryable'
                     LIMIT 1",
                )
                .bind(run_id)
                .fetch_optional(&mut *tx)
                .await?
                .is_some();
                let permanent_tool = sqlx::query_scalar::<_, i64>(
                    "SELECT 1 FROM events e
                     JOIN tasks t ON t.id = json_extract(e.data, '$.task_id')
                     WHERE t.goal_run_id = ? AND e.event_type = 'tool_result'
                       AND json_extract(e.data, '$.receipt.outcome_status')
                           IN ('failed_permanent', 'blocked') LIMIT 1",
                )
                .bind(run_id)
                .fetch_optional(&mut *tx)
                .await?
                .is_some();
                let task_failed = sqlx::query_scalar::<_, i64>(
                    "SELECT 1 FROM tasks WHERE goal_run_id = ?
                       AND (status IN ('failed', 'interrupted')
                            OR error IS NOT NULL OR blocker IS NOT NULL) LIMIT 1",
                )
                .bind(run_id)
                .fetch_optional(&mut *tx)
                .await?
                .is_some();
                let failure_kind = if authorization_blocked {
                    crate::traits::ScheduledFailureKind::AuthorizationBlocked
                } else if retryable_tool {
                    crate::traits::ScheduledFailureKind::RetryableTool
                } else if permanent_tool {
                    crate::traits::ScheduledFailureKind::PermanentTool
                } else if task_failed {
                    crate::traits::ScheduledFailureKind::TaskFailed
                } else {
                    crate::traits::ScheduledFailureKind::OutcomeUnproven
                };
                let previous_failures = sqlx::query_scalar::<_, i64>(
                    "SELECT consecutive_failures FROM scheduled_recovery_state
                     WHERE goal_id = ?",
                )
                .bind(&goal_id)
                .fetch_optional(&mut *tx)
                .await?
                .unwrap_or(0);
                let consecutive_failures = previous_failures.saturating_add(1);
                let escalated = consecutive_failures >= failure_budget;
                let newly_escalated = escalated && previous_failures < failure_budget;
                let disposition = if escalated {
                    crate::traits::ScheduledRecoveryDisposition::Escalated
                } else {
                    crate::traits::ScheduledRecoveryDisposition::Recovering
                };
                sqlx::query(
                    "INSERT INTO scheduled_recovery_state
                        (goal_id, consecutive_failures, failure_budget, disposition,
                         latest_failure_kind, last_failed_run_id, last_recovery_run_id, updated_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                     ON CONFLICT(goal_id) DO UPDATE SET
                        consecutive_failures = excluded.consecutive_failures,
                        failure_budget = excluded.failure_budget,
                        disposition = excluded.disposition,
                        latest_failure_kind = excluded.latest_failure_kind,
                        last_failed_run_id = excluded.last_failed_run_id,
                        last_recovery_run_id = COALESCE(excluded.last_recovery_run_id,
                                                        scheduled_recovery_state.last_recovery_run_id),
                        updated_at = excluded.updated_at",
                )
                .bind(&goal_id)
                .bind(consecutive_failures)
                .bind(failure_budget)
                .bind(disposition.as_str())
                .bind(failure_kind.as_str())
                .bind(run_id)
                .bind(recovery_for_run.as_ref().map(|_| run_id))
                .bind(&now)
                .execute(&mut *tx)
                .await?;

                if newly_escalated {
                    sqlx::query(
                        "INSERT OR IGNORE INTO scheduled_recovery_paused_schedules
                            (schedule_id, goal_id, paused_at)
                         SELECT id, goal_id, ? FROM goal_schedules
                         WHERE goal_id = ? AND is_paused = 0",
                    )
                    .bind(&now)
                    .bind(&goal_id)
                    .execute(&mut *tx)
                    .await?;
                    sqlx::query(
                        "UPDATE goal_schedules SET is_paused = 1, updated_at = ?
                         WHERE goal_id = ?",
                    )
                    .bind(&now)
                    .bind(&goal_id)
                    .execute(&mut *tx)
                    .await?;
                    let notification_id = format!(
                        "scheduled-recovery-budget:{}:{}",
                        goal_id, consecutive_failures
                    );
                    sqlx::query(
                        "INSERT OR IGNORE INTO notification_queue
                            (id, goal_id, session_id, notification_type, priority, message,
                             created_at, delivered_at, attempts, expires_at, task_id, action_token)
                         VALUES (?, ?, ?, 'escalation', 'critical', ?, ?, NULL, 0, NULL, NULL, NULL)",
                    )
                    .bind(notification_id)
                    .bind(&goal_id)
                    .bind(&session_id)
                    .bind(paused_notice(
                        &crate::automations::name_from_context(
                            run.get::<Option<String>, _>("goal_context").as_deref(),
                        )
                        .unwrap_or_else(|| {
                            aidaemon_tools::sanitize::short_goal_label(
                                &run.get::<String, _>("description"),
                            )
                        }),
                        consecutive_failures,
                        failure_kind,
                        summary,
                    ))
                    .bind(&now)
                    .execute(&mut *tx)
                    .await?;
                }
            }

            if let Some(failed_run_id) = recovery_for_run.as_deref() {
                let link_status = if status == "completed" && recovery_completion_verified {
                    "verified"
                } else if matches!(status, "completed" | "failed" | "cancelled") {
                    "failed"
                } else {
                    "recovering"
                };
                sqlx::query(
                    "INSERT INTO goal_run_recovery_links
                        (failed_run_id, recovery_run_id, outcome_status,
                         proof_receipt_ids_json, created_at, updated_at)
                     VALUES (?, ?, ?, ?, ?, ?)
                     ON CONFLICT(failed_run_id, recovery_run_id) DO UPDATE SET
                        outcome_status = excluded.outcome_status,
                        proof_receipt_ids_json = excluded.proof_receipt_ids_json,
                        updated_at = excluded.updated_at",
                )
                .bind(failed_run_id)
                .bind(run_id)
                .bind(link_status)
                .bind(serde_json::to_string(&recovery_proof_receipt_ids)?)
                .bind(&now)
                .bind(&now)
                .execute(&mut *tx)
                .await?;
            }
        }
        tx.commit().await?;
        Ok(true)
    }

    async fn claim_task_with_lease(
        &self,
        task_id: &str,
        worker_instance_id: &str,
        worker_profile_id: Option<&str>,
        lease_secs: i64,
    ) -> anyhow::Result<Option<TaskAttempt>> {
        let lease_secs = normalized_lease_secs(lease_secs);
        let now = chrono::Utc::now();
        let expires = now + chrono::Duration::seconds(lease_secs);
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let row = sqlx::query(
            "SELECT t.goal_id, t.goal_run_id, t.worker_profile_id, g.project_id
             FROM tasks t JOIN goals g ON g.id = t.goal_id
             WHERE t.id = ? AND t.status IN ('pending', 'claimed')
               AND t.current_attempt_id IS NULL",
        )
        .bind(task_id)
        .fetch_optional(&mut *tx)
        .await?;
        let Some(row) = row else {
            return Ok(None);
        };
        let goal_id: String = row.get("goal_id");
        let goal_run_id: String = row.get("goal_run_id");
        let project_id: String = row.get("project_id");
        let assigned_profile_id: Option<String> = row.get("worker_profile_id");
        let profile_id = assigned_profile_id
            .or_else(|| worker_profile_id.map(str::to_string))
            .unwrap_or_else(|| "profile-executor".to_string());

        let unmet = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*)
             FROM task_dependencies dep
             WHERE dep.task_id = ?
               AND NOT EXISTS (
                SELECT 1 FROM tasks d
                WHERE d.id = dep.depends_on_task_id
                  AND d.goal_run_id = ?
                  AND d.status IN ('completed', 'skipped', 'superseded')
             )",
        )
        .bind(task_id)
        .bind(&goal_run_id)
        .fetch_one(&mut *tx)
        .await?;
        if unmet > 0 {
            return Ok(None);
        }

        let profile = sqlx::query(
            "SELECT max_concurrency FROM worker_profiles
             WHERE id = ? AND enabled = 1
               AND (project_id IS NULL OR project_id = ?)",
        )
        .bind(&profile_id)
        .bind(&project_id)
        .fetch_optional(&mut *tx)
        .await?;
        let Some(profile) = profile else {
            anyhow::bail!("worker profile '{}' is unavailable", profile_id);
        };
        // Acquire SQLite's write reservation before counting active slots so
        // two concurrent claims cannot both observe the same final capacity.
        sqlx::query("UPDATE worker_profiles SET updated_at = updated_at WHERE id = ?")
            .bind(&profile_id)
            .execute(&mut *tx)
            .await?;
        let max_concurrency: i64 = profile.get("max_concurrency");
        let active = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM task_attempts
             WHERE worker_profile_id = ?
               AND status IN ('claimed', 'running')
               AND datetime(lease_expires_at) > datetime('now')",
        )
        .bind(&profile_id)
        .fetch_one(&mut *tx)
        .await?;
        if active >= max_concurrency {
            return Ok(None);
        }

        let attempt = TaskAttempt {
            id: uuid::Uuid::new_v4().to_string(),
            task_id: task_id.to_string(),
            goal_run_id: goal_run_id.clone(),
            worker_profile_id: Some(profile_id.clone()),
            worker_instance_id: worker_instance_id.to_string(),
            lease_token: uuid::Uuid::new_v4().to_string(),
            status: "claimed".to_string(),
            lease_expires_at: expires.to_rfc3339(),
            last_heartbeat_at: now.to_rfc3339(),
            workspace_id: None,
            started_at: now.to_rfc3339(),
            completed_at: None,
        };
        sqlx::query(
            "INSERT INTO task_attempts
                (id, task_id, goal_run_id, worker_profile_id, worker_instance_id,
                 lease_token, status, lease_expires_at, last_heartbeat_at,
                 workspace_id, started_at, completed_at)
             VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?, NULL, ?, NULL)",
        )
        .bind(&attempt.id)
        .bind(&attempt.task_id)
        .bind(&attempt.goal_run_id)
        .bind(&attempt.worker_profile_id)
        .bind(&attempt.worker_instance_id)
        .bind(&attempt.lease_token)
        .bind(&attempt.lease_expires_at)
        .bind(&attempt.last_heartbeat_at)
        .bind(&attempt.started_at)
        .execute(&mut *tx)
        .await?;
        let updated = sqlx::query(
            "UPDATE tasks
             SET status = 'claimed', agent_id = ?, current_attempt_id = ?,
                 worker_profile_id = ?, started_at = COALESCE(started_at, datetime('now')),
                 result = NULL, error = NULL, blocker = NULL, completed_at = NULL,
                 updated_at = datetime('now'), version = version + 1
             WHERE id = ? AND status IN ('pending', 'claimed')
               AND current_attempt_id IS NULL",
        )
        .bind(worker_instance_id)
        .bind(&attempt.id)
        .bind(&profile_id)
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(None);
        }
        sqlx::query(
            "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
             WHERE id = ? AND status IN ('pending', 'blocked', 'claimed')",
        )
        .bind(&goal_run_id)
        .execute(&mut *tx)
        .await?;
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            "assigned",
            "system",
            worker_instance_id,
            &format!("Claimed by worker profile {}", profile_id),
        )
        .with_task(Some(task_id), Some(&attempt.id));
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(Some(attempt))
    }

    async fn get_current_task_attempt(&self, task_id: &str) -> anyhow::Result<Option<TaskAttempt>> {
        let row = sqlx::query(
            "SELECT a.id, a.task_id, a.goal_run_id, a.worker_profile_id,
                    a.worker_instance_id, a.lease_token, a.status,
                    a.lease_expires_at, a.last_heartbeat_at, a.workspace_id,
                    a.started_at, a.completed_at
             FROM task_attempts a
             JOIN tasks t ON t.current_attempt_id = a.id
             WHERE t.id = ? AND a.status IN ('claimed', 'running')",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.as_ref().map(task_attempt_from_row))
    }

    async fn bind_task_attempt_worker(
        &self,
        attempt_id: &str,
        lease_token: &str,
        worker_instance_id: &str,
        worker_profile_id: Option<&str>,
    ) -> anyhow::Result<bool> {
        // This operation reads the current lease/profile and then writes the
        // bound worker. A deferred transaction can acquire its read snapshot,
        // lose a race to another WAL writer, and fail on promotion with
        // SQLITE_BUSY_SNAPSHOT (extended code 517). Reserve the writer slot
        // before reading so the snapshot can always be committed.
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let row = sqlx::query(
            "SELECT a.worker_profile_id, g.project_id
             FROM task_attempts a
             JOIN tasks t ON t.current_attempt_id = a.id
             JOIN goals g ON g.id = t.goal_id
             WHERE a.id = ? AND a.lease_token = ?
               AND a.status IN ('claimed', 'running')
               AND datetime(a.lease_expires_at) > datetime('now')",
        )
        .bind(attempt_id)
        .bind(lease_token)
        .fetch_optional(&mut *tx)
        .await?;
        let Some(row) = row else {
            tx.rollback().await?;
            return Ok(false);
        };
        let current_profile_id: Option<String> = row.get("worker_profile_id");
        let project_id: String = row.get("project_id");
        let target_profile_id = worker_profile_id
            .map(str::to_string)
            .or_else(|| current_profile_id.clone());

        if target_profile_id != current_profile_id {
            let Some(target_profile_id) = target_profile_id.as_deref() else {
                tx.rollback().await?;
                return Ok(false);
            };
            let profile = sqlx::query(
                "SELECT max_concurrency FROM worker_profiles
                 WHERE id = ? AND enabled = 1
                   AND (project_id IS NULL OR project_id = ?)",
            )
            .bind(target_profile_id)
            .bind(&project_id)
            .fetch_optional(&mut *tx)
            .await?;
            let Some(profile) = profile else {
                tx.rollback().await?;
                return Ok(false);
            };
            sqlx::query("UPDATE worker_profiles SET updated_at = updated_at WHERE id = ?")
                .bind(target_profile_id)
                .execute(&mut *tx)
                .await?;
            let active = sqlx::query_scalar::<_, i64>(
                "SELECT COUNT(*) FROM task_attempts
                 WHERE worker_profile_id = ? AND id != ?
                   AND status IN ('claimed', 'running')
                   AND datetime(lease_expires_at) > datetime('now')",
            )
            .bind(target_profile_id)
            .bind(attempt_id)
            .fetch_one(&mut *tx)
            .await?;
            let max_concurrency: i64 = profile.get("max_concurrency");
            if active >= max_concurrency {
                tx.rollback().await?;
                return Ok(false);
            }
        }

        let result = sqlx::query(
            "UPDATE task_attempts
             SET worker_instance_id = ?,
                 worker_profile_id = COALESCE(?, worker_profile_id)
             WHERE id = ? AND lease_token = ?
               AND status IN ('claimed', 'running')
               AND datetime(lease_expires_at) > datetime('now')",
        )
        .bind(worker_instance_id)
        .bind(worker_profile_id)
        .bind(attempt_id)
        .bind(lease_token)
        .execute(&mut *tx)
        .await?;
        if result.rows_affected() > 0 {
            sqlx::query(
                "UPDATE tasks
                 SET agent_id = ?,
                     worker_profile_id = COALESCE(?, worker_profile_id),
                     updated_at = datetime('now'), version = version + 1
                 WHERE current_attempt_id = ?",
            )
            .bind(worker_instance_id)
            .bind(worker_profile_id)
            .bind(attempt_id)
            .execute(&mut *tx)
            .await?;
            tx.commit().await?;
            return Ok(true);
        }
        tx.rollback().await?;
        Ok(false)
    }

    async fn heartbeat_task_attempt(
        &self,
        attempt_id: &str,
        lease_token: &str,
        lease_secs: i64,
    ) -> anyhow::Result<bool> {
        let lease_secs = normalized_lease_secs(lease_secs);
        let result = sqlx::query(
            "UPDATE task_attempts
             SET last_heartbeat_at = datetime('now'),
                 lease_expires_at = datetime('now', '+' || ? || ' seconds')
             WHERE id = ? AND lease_token = ?
               AND status IN ('claimed', 'running')
               AND datetime(lease_expires_at) > datetime('now')",
        )
        .bind(lease_secs)
        .bind(attempt_id)
        .bind(lease_token)
        .execute(self.work_pool())
        .await?;
        Ok(result.rows_affected() > 0)
    }

    async fn patch_task_from_attempt(
        &self,
        attempt_id: &str,
        lease_token: &str,
        patch: &TaskAttemptPatch,
    ) -> anyhow::Result<bool> {
        anyhow::ensure!(
            matches!(
                patch.status.as_str(),
                "running" | "completed" | "failed" | "blocked" | "cancelled"
            ),
            "unsupported attempt task transition"
        );
        // Reserve the writer slot before reading the attempt/task fence. A
        // deferred transaction can read a valid lease, lose a race to another
        // WAL writer, and then fail promotion with SQLITE_BUSY_SNAPSHOT. That
        // previously stranded freshly dispatched work in `claimed` state.
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let row = sqlx::query(
            "SELECT a.task_id, a.goal_run_id, a.status AS attempt_status,
                    t.goal_id, g.project_id
             FROM task_attempts a
             JOIN tasks t ON t.id = a.task_id AND t.current_attempt_id = a.id
             JOIN goals g ON g.id = t.goal_id
             WHERE a.id = ? AND a.lease_token = ?
               AND a.status IN ('claimed', 'running')
               AND datetime(a.lease_expires_at) > datetime('now')",
        )
        .bind(attempt_id)
        .bind(lease_token)
        .fetch_optional(&mut *tx)
        .await?;
        let Some(row) = row else {
            return Ok(false);
        };
        let task_id: String = row.get("task_id");
        let goal_run_id: String = row.get("goal_run_id");
        let goal_id: String = row.get("goal_id");
        let project_id: String = row.get("project_id");
        let terminal = matches!(
            patch.status.as_str(),
            "completed" | "failed" | "blocked" | "cancelled"
        );
        let completed_at = terminal.then(|| chrono::Utc::now().to_rfc3339());
        let result = patch
            .result
            .as_deref()
            .filter(|value| !value.trim().is_empty());
        let error = patch
            .error
            .as_deref()
            .filter(|value| !value.trim().is_empty());
        let blocker = patch
            .blocker
            .as_deref()
            .filter(|value| !value.trim().is_empty());
        let updated = sqlx::query(
            "UPDATE tasks
             SET status = ?,
                 result = COALESCE(?, result),
                 error = CASE WHEN ? = 'completed' THEN NULL ELSE COALESCE(?, error) END,
                 blocker = CASE WHEN ? IN ('completed', 'running') THEN NULL ELSE COALESCE(?, blocker) END,
                 context = COALESCE(?, context),
                 current_attempt_id = CASE WHEN ? THEN NULL ELSE current_attempt_id END,
                 completed_at = CASE WHEN ? THEN ? ELSE NULL END,
                 updated_at = datetime('now'), version = version + 1
             WHERE id = ? AND current_attempt_id = ?",
        )
        .bind(&patch.status)
        .bind(result)
        .bind(&patch.status)
        .bind(error)
        .bind(&patch.status)
        .bind(blocker)
        .bind(&patch.context)
        .bind(terminal)
        .bind(terminal)
        .bind(&completed_at)
        .bind(&task_id)
        .bind(attempt_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        sqlx::query(
            "UPDATE task_attempts
             SET status = ?, completed_at = CASE WHEN ? THEN ? ELSE completed_at END
             WHERE id = ? AND lease_token = ?",
        )
        .bind(&patch.status)
        .bind(terminal)
        .bind(&completed_at)
        .bind(attempt_id)
        .bind(lease_token)
        .execute(&mut *tx)
        .await?;

        if patch.status == "completed" {
            sqlx::query(
                "UPDATE goals SET last_useful_action = datetime('now'), updated_at = datetime('now')
                 WHERE id = ?",
            )
            .bind(&goal_id)
            .execute(&mut *tx)
            .await?;
        } else if patch.status == "blocked" {
            // A mandate run's outcome belongs to its task lead (the root
            // task): an executor's blocker is input to that lead, which must
            // keep its live run to call the model and finalize.
            sqlx::query(
                "UPDATE goal_runs SET status = 'blocked', updated_at = datetime('now')
                 WHERE id = ? AND status IN ('pending', 'running')
                   AND (trigger_type <> 'mandate' OR root_task_id IS NULL OR root_task_id = ?)",
            )
            .bind(&goal_run_id)
            .bind(&task_id)
            .execute(&mut *tx)
            .await?;
        }
        if terminal && patch.status != "blocked" {
            close_pending_task_escalations(&mut tx, &task_id).await?;
        }

        if let Some(handoff) = &patch.handoff {
            anyhow::ensure!(
                handoff.task_id == task_id && handoff.attempt_id == attempt_id,
                "handoff does not match current task attempt"
            );
            let artifacts = serde_json::to_string(&handoff.artifacts)?;
            let verification = serde_json::to_string(&handoff.verification)?;
            sqlx::query(
                "INSERT INTO task_handoffs
                    (id, task_id, attempt_id, summary, artifacts_json,
                     verification_json, remaining_risk, next_step, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            )
            .bind(&handoff.id)
            .bind(&handoff.task_id)
            .bind(&handoff.attempt_id)
            .bind(self.redact_secrets(&handoff.summary))
            .bind(artifacts)
            .bind(verification)
            .bind(
                handoff
                    .remaining_risk
                    .as_deref()
                    .map(|text| self.redact_secrets(text)),
            )
            .bind(
                handoff
                    .next_step
                    .as_deref()
                    .map(|text| self.redact_secrets(text)),
            )
            .bind(&handoff.created_at)
            .execute(&mut *tx)
            .await?;
        }

        let entry_type = match patch.status.as_str() {
            "blocked" => "blocked",
            "completed" | "failed" | "cancelled" => "handoff",
            _ => "transition",
        };
        let body = patch
            .handoff
            .as_ref()
            .map(|handoff| handoff.summary.as_str())
            .or(result)
            .or(error)
            .or(blocker)
            .unwrap_or(&patch.status);
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            entry_type,
            "agent",
            attempt_id,
            body,
        )
        .with_task(Some(&task_id), Some(attempt_id));
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(true)
    }

    async fn goal_run_has_live_attempt(&self, run_id: &str) -> anyhow::Result<bool> {
        let live = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM task_attempts
             WHERE goal_run_id = ?
               AND status IN ('claimed', 'running')
               AND datetime(lease_expires_at) > datetime('now')",
        )
        .bind(run_id)
        .fetch_one(self.work_pool())
        .await?;
        Ok(live > 0)
    }

    async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let rows = sqlx::query(
            "SELECT a.id AS attempt_id, a.task_id, a.goal_run_id,
                    t.goal_id, g.project_id, t.idempotent, t.retry_count,
                    t.max_retries, t.current_attempt_id
             FROM task_attempts a
             JOIN tasks t ON t.id = a.task_id
             JOIN goals g ON g.id = t.goal_id
             WHERE a.status IN ('claimed', 'running')
               AND datetime(a.lease_expires_at) <= datetime('now')",
        )
        .fetch_all(&mut *tx)
        .await?;
        let mut affected = Vec::new();
        for row in rows {
            let attempt_id: String = row.get("attempt_id");
            let task_id: String = row.get("task_id");
            let goal_run_id: String = row.get("goal_run_id");
            let goal_id: String = row.get("goal_id");
            let project_id: String = row.get("project_id");
            let is_current = row
                .get::<Option<String>, _>("current_attempt_id")
                .as_deref()
                == Some(attempt_id.as_str());
            let recovery = crate::traits::ExpiredAttemptRecovery::classify(
                row.get::<i64, _>("idempotent") != 0,
                row.get::<i64, _>("retry_count") as i32,
                row.get::<i64, _>("max_retries") as i32,
            );
            let attempt_status = match recovery {
                crate::traits::ExpiredAttemptRecovery::Requeue => "expired",
                crate::traits::ExpiredAttemptRecovery::RequireVerification => "needs_verification",
            };
            let expired = sqlx::query(
                "UPDATE task_attempts
                 SET status = ?, completed_at = datetime('now')
                 WHERE id = ? AND status IN ('claimed', 'running')
                   AND datetime(lease_expires_at) <= datetime('now')",
            )
            .bind(attempt_status)
            .bind(&attempt_id)
            .execute(&mut *tx)
            .await?;
            if expired.rows_affected() == 0 {
                continue;
            }
            sqlx::query(
                "UPDATE task_workspaces SET status = 'preserved'
                 WHERE attempt_id = ? AND status = 'active'",
            )
            .bind(&attempt_id)
            .execute(&mut *tx)
            .await?;
            if is_current {
                if recovery == crate::traits::ExpiredAttemptRecovery::Requeue {
                    sqlx::query(
                        "UPDATE tasks
                         SET status = 'pending', current_attempt_id = NULL, agent_id = NULL,
                             retry_count = retry_count + 1, started_at = NULL,
                             completed_at = NULL, result = NULL, error = NULL, blocker = NULL,
                             updated_at = datetime('now'), version = version + 1
                         WHERE id = ? AND current_attempt_id = ?",
                    )
                    .bind(&task_id)
                    .bind(&attempt_id)
                    .execute(&mut *tx)
                    .await?;
                } else {
                    sqlx::query(
                        "UPDATE tasks
                         SET status = 'blocked', current_attempt_id = NULL,
                             blocker = 'Execution lease expired. Verify external side effects before retrying.',
                             result = NULL, error = NULL,
                             completed_at = datetime('now'), updated_at = datetime('now'),
                             version = version + 1
                         WHERE id = ? AND current_attempt_id = ?",
                    )
                    .bind(&task_id)
                    .bind(&attempt_id)
                    .execute(&mut *tx)
                    .await?;
                    sqlx::query(
                        "UPDATE goal_runs SET status = 'blocked', updated_at = datetime('now')
                         WHERE id = ? AND status IN ('pending', 'running')",
                    )
                    .bind(&goal_run_id)
                    .execute(&mut *tx)
                    .await?;
                }
                affected.push(task_id.clone());
            }
            let body = match recovery {
                crate::traits::ExpiredAttemptRecovery::Requeue => {
                    "Worker lease expired; task re-queued because the task is retryable."
                }
                crate::traits::ExpiredAttemptRecovery::RequireVerification => {
                    "Worker lease expired; task requires human verification before another attempt."
                }
            };
            let journal = TaskJournalEntry::new(
                &project_id,
                &goal_id,
                &goal_run_id,
                "lease_lost",
                "system",
                "lease-recovery",
                body,
            )
            .with_task(Some(&task_id), Some(&attempt_id));
            insert_journal(self, &mut tx, &journal).await?;
        }
        tx.commit().await?;
        Ok(affected)
    }

    async fn append_task_journal(&self, entry: &TaskJournalEntry) -> anyhow::Result<()> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        insert_journal(self, &mut tx, entry).await?;
        tx.commit().await?;
        Ok(())
    }

    async fn get_task_journal(
        &self,
        task_id: &str,
        limit: i64,
    ) -> anyhow::Result<Vec<TaskJournalEntry>> {
        let rows = sqlx::query(
            "SELECT id, project_id, goal_id, goal_run_id, task_id, attempt_id,
                    entry_type, actor_type, actor_id, source_channel, body, payload, created_at
             FROM task_journal WHERE task_id = ?
             ORDER BY julianday(created_at) DESC, id DESC LIMIT ?",
        )
        .bind(task_id)
        .bind(limit.clamp(1, 200))
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows
            .iter()
            .map(|row| TaskJournalEntry {
                id: row.get("id"),
                project_id: row.get("project_id"),
                goal_id: row.get("goal_id"),
                goal_run_id: row.get("goal_run_id"),
                task_id: row.get("task_id"),
                attempt_id: row.get("attempt_id"),
                entry_type: row.get("entry_type"),
                actor_type: row.get("actor_type"),
                actor_id: row.get("actor_id"),
                source_channel: row.get("source_channel"),
                body: row.get("body"),
                payload: row.get("payload"),
                created_at: row.get("created_at"),
            })
            .collect())
    }

    async fn unblock_task(
        &self,
        task_id: &str,
        resolution: &str,
        actor_id: &str,
        source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        anyhow::ensure!(!resolution.trim().is_empty(), "resolution cannot be empty");
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
            return Ok(false);
        };
        let attempt_id = sqlx::query_scalar::<_, Option<String>>(
            "SELECT current_attempt_id FROM tasks
             WHERE id = ? AND status = 'blocked'",
        )
        .bind(task_id)
        .fetch_optional(&mut *tx)
        .await?
        .flatten();
        if let Some(attempt_id) = &attempt_id {
            sqlx::query(
                "UPDATE task_attempts SET status = 'cancelled', completed_at = datetime('now')
                 WHERE id = ? AND status IN ('claimed', 'running')",
            )
            .bind(attempt_id)
            .execute(&mut *tx)
            .await?;
        }
        let updated = sqlx::query(
            "UPDATE tasks
             SET status = 'pending', result = NULL, blocker = NULL, error = NULL, completed_at = NULL,
                 started_at = NULL, current_attempt_id = NULL, agent_id = NULL,
                 updated_at = datetime('now'), version = version + 1
             WHERE id = ? AND status = 'blocked'",
        )
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        close_pending_task_escalations(&mut tx, task_id).await?;
        sqlx::query(
            "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
             WHERE id = ? AND status = 'blocked'",
        )
        .bind(&goal_run_id)
        .execute(&mut *tx)
        .await?;
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            "unblocked",
            "human",
            actor_id,
            resolution.trim(),
        )
        .with_task(Some(task_id), attempt_id.as_deref())
        .with_source_channel(source_channel);
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(true)
    }

    async fn retry_work_task(
        &self,
        task_id: &str,
        actor_id: &str,
        source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
            return Ok(false);
        };
        let updated = sqlx::query(
            "UPDATE tasks
             SET status = 'pending', result = NULL, blocker = NULL, error = NULL, completed_at = NULL,
                 started_at = NULL, current_attempt_id = NULL, agent_id = NULL,
                 retry_count = retry_count + 1,
                 updated_at = datetime('now'), version = version + 1
             WHERE id = ? AND status IN ('failed', 'blocked', 'interrupted', 'cancelled')
               AND current_attempt_id IS NULL",
        )
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        close_pending_task_escalations(&mut tx, task_id).await?;
        sqlx::query(
            "UPDATE goal_runs SET status = 'running', updated_at = datetime('now')
             WHERE id = ? AND status = 'blocked'",
        )
        .bind(&goal_run_id)
        .execute(&mut *tx)
        .await?;
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            "transition",
            "human",
            actor_id,
            "Task explicitly queued for another attempt.",
        )
        .with_task(Some(task_id), None)
        .with_source_channel(source_channel);
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(true)
    }

    async fn cancel_work_task(
        &self,
        task_id: &str,
        actor_id: &str,
        source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
            return Ok(false);
        };
        let attempt_id = sqlx::query_scalar::<_, Option<String>>(
            "SELECT current_attempt_id FROM tasks WHERE id = ?",
        )
        .bind(task_id)
        .fetch_optional(&mut *tx)
        .await?
        .flatten();
        if let Some(attempt_id) = &attempt_id {
            sqlx::query(
                "UPDATE task_attempts SET status = 'cancelled', completed_at = datetime('now')
                 WHERE id = ? AND status IN ('claimed', 'running')",
            )
            .bind(attempt_id)
            .execute(&mut *tx)
            .await?;
        }
        let updated = sqlx::query(
            "UPDATE tasks
             SET status = 'cancelled', current_attempt_id = NULL,
                 completed_at = datetime('now'), updated_at = datetime('now'),
                 version = version + 1
             WHERE id = ? AND status NOT IN ('completed', 'cancelled', 'skipped', 'superseded')",
        )
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        close_pending_task_escalations(&mut tx, task_id).await?;
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            "transition",
            "human",
            actor_id,
            "Task cancelled.",
        )
        .with_task(Some(task_id), attempt_id.as_deref())
        .with_source_channel(source_channel);
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(true)
    }

    async fn upsert_worker_profile(&self, profile: &WorkerProfile) -> anyhow::Result<()> {
        anyhow::ensure!(
            profile.max_concurrency > 0,
            "profile concurrency must be positive"
        );
        anyhow::ensure!(
            matches!(
                profile.workspace_policy.as_str(),
                "shared" | "isolated" | "worktree"
            ),
            "unsupported workspace policy"
        );
        sqlx::query(
            "INSERT INTO worker_profiles
                (id, project_id, name, specialist, model, tools_json, max_iterations,
                 tool_budget, timeout_secs, max_concurrency, workspace_policy,
                 memory_scope, version, enabled, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
             ON CONFLICT(id) DO UPDATE SET
                project_id = excluded.project_id, name = excluded.name,
                specialist = excluded.specialist, model = excluded.model,
                tools_json = excluded.tools_json, max_iterations = excluded.max_iterations,
                tool_budget = excluded.tool_budget, timeout_secs = excluded.timeout_secs,
                max_concurrency = excluded.max_concurrency,
                workspace_policy = excluded.workspace_policy,
                memory_scope = excluded.memory_scope, version = excluded.version,
                enabled = excluded.enabled, updated_at = excluded.updated_at",
        )
        .bind(&profile.id)
        .bind(&profile.project_id)
        .bind(&profile.name)
        .bind(&profile.specialist)
        .bind(&profile.model)
        .bind(&profile.tools_json)
        .bind(profile.max_iterations)
        .bind(profile.tool_budget)
        .bind(profile.timeout_secs)
        .bind(profile.max_concurrency)
        .bind(&profile.workspace_policy)
        .bind(&profile.memory_scope)
        .bind(profile.version)
        .bind(profile.enabled as i64)
        .bind(&profile.created_at)
        .bind(&profile.updated_at)
        .execute(self.work_pool())
        .await?;
        Ok(())
    }

    async fn get_worker_profile(&self, profile_id: &str) -> anyhow::Result<Option<WorkerProfile>> {
        let row = sqlx::query(
            "SELECT id, project_id, name, specialist, model, tools_json,
                    max_iterations, tool_budget, timeout_secs, max_concurrency,
                    workspace_policy, memory_scope, version, enabled, created_at, updated_at
             FROM worker_profiles WHERE id = ?",
        )
        .bind(profile_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.as_ref().map(worker_profile_from_row))
    }

    async fn list_worker_profiles(
        &self,
        project_id: Option<&str>,
    ) -> anyhow::Result<Vec<WorkerProfile>> {
        let rows = sqlx::query(
            "SELECT id, project_id, name, specialist, model, tools_json,
                    max_iterations, tool_budget, timeout_secs, max_concurrency,
                    workspace_policy, memory_scope, version, enabled, created_at, updated_at
             FROM worker_profiles
             WHERE enabled = 1 AND (project_id IS NULL OR project_id = ?)
             ORDER BY name COLLATE NOCASE",
        )
        .bind(project_id.unwrap_or(DEFAULT_PROJECT_ID))
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows.iter().map(worker_profile_from_row).collect())
    }

    async fn assign_task_worker_profile(
        &self,
        task_id: &str,
        profile_id: &str,
        actor_id: &str,
        source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        let Some((project_id, goal_id, goal_run_id)) = task_scope(&mut tx, task_id).await? else {
            return Ok(false);
        };
        let profile_exists = sqlx::query_scalar::<_, i64>(
            "SELECT 1 FROM worker_profiles
             WHERE id = ? AND enabled = 1
               AND (project_id IS NULL OR project_id = ?) LIMIT 1",
        )
        .bind(profile_id)
        .bind(&project_id)
        .fetch_optional(&mut *tx)
        .await?
        .is_some();
        if !profile_exists {
            return Ok(false);
        }
        let updated = sqlx::query(
            "UPDATE tasks SET worker_profile_id = ?, updated_at = datetime('now'),
                              version = version + 1
             WHERE id = ? AND status IN ('pending', 'blocked', 'failed', 'interrupted')",
        )
        .bind(profile_id)
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
        if updated.rows_affected() == 0 {
            tx.rollback().await?;
            return Ok(false);
        }
        let journal = TaskJournalEntry::new(
            &project_id,
            &goal_id,
            &goal_run_id,
            "assigned",
            if source_channel.is_some() {
                "human"
            } else {
                "agent"
            },
            actor_id,
            &format!("Assigned worker profile {}", profile_id),
        )
        .with_task(Some(task_id), None)
        .with_source_channel(source_channel);
        insert_journal(self, &mut tx, &journal).await?;
        tx.commit().await?;
        Ok(true)
    }

    async fn set_task_workspace_policy(&self, task_id: &str, policy: &str) -> anyhow::Result<bool> {
        anyhow::ensure!(
            matches!(policy, "shared" | "isolated" | "worktree"),
            "unsupported workspace policy"
        );
        let result = sqlx::query(
            "UPDATE tasks SET workspace_policy = ?, workspace_policy_explicit = 1,
                              updated_at = datetime('now'),
                              version = version + 1
             WHERE id = ? AND status IN ('pending', 'blocked', 'claimed')
               AND NOT EXISTS (
                   SELECT 1 FROM task_workspaces w
                   WHERE w.task_id = tasks.id AND w.status != 'failed'
               )",
        )
        .bind(policy)
        .bind(task_id)
        .execute(self.work_pool())
        .await?;
        Ok(result.rows_affected() > 0)
    }

    async fn get_task_workspace_policy(&self, task_id: &str) -> anyhow::Result<String> {
        Ok(sqlx::query_scalar::<_, String>(
            "SELECT CASE
                      WHEN t.workspace_policy_explicit = 1
                        THEN t.workspace_policy
                      ELSE COALESCE(wp.workspace_policy, 'shared')
                    END
             FROM tasks t
             LEFT JOIN task_attempts a ON a.id = t.current_attempt_id
             LEFT JOIN worker_profiles wp
               ON wp.id = COALESCE(a.worker_profile_id, t.worker_profile_id)
             WHERE t.id = ?",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?
        .unwrap_or_else(|| "shared".to_string()))
    }

    async fn task_workspace_policy_is_explicit(&self, task_id: &str) -> anyhow::Result<bool> {
        Ok(sqlx::query_scalar::<_, i64>(
            "SELECT COALESCE(workspace_policy_explicit, 0) FROM tasks WHERE id = ?",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?
        .is_some_and(|explicit| explicit == 1))
    }

    async fn create_task_workspace(&self, workspace: &TaskWorkspace) -> anyhow::Result<()> {
        let mut tx = self.work_pool().begin_with("BEGIN IMMEDIATE").await?;
        sqlx::query(
            "INSERT INTO task_workspaces
                (id, task_id, attempt_id, backend_id, policy, root_path,
                 branch_name, base_ref, head_ref, status, created_at, released_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&workspace.id)
        .bind(&workspace.task_id)
        .bind(&workspace.attempt_id)
        .bind(&workspace.backend_id)
        .bind(&workspace.policy)
        .bind(&workspace.root_path)
        .bind(&workspace.branch_name)
        .bind(&workspace.base_ref)
        .bind(&workspace.head_ref)
        .bind(&workspace.status)
        .bind(&workspace.created_at)
        .bind(&workspace.released_at)
        .execute(&mut *tx)
        .await?;
        sqlx::query("UPDATE task_attempts SET workspace_id = ? WHERE id = ?")
            .bind(&workspace.id)
            .bind(&workspace.attempt_id)
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
        Ok(())
    }

    async fn update_task_workspace(&self, workspace: &TaskWorkspace) -> anyhow::Result<()> {
        sqlx::query(
            "UPDATE task_workspaces
             SET root_path = ?, branch_name = ?, base_ref = ?, head_ref = ?,
                 status = ?, released_at = ?
             WHERE id = ? AND task_id = ? AND attempt_id = ?",
        )
        .bind(&workspace.root_path)
        .bind(&workspace.branch_name)
        .bind(&workspace.base_ref)
        .bind(&workspace.head_ref)
        .bind(&workspace.status)
        .bind(&workspace.released_at)
        .bind(&workspace.id)
        .bind(&workspace.task_id)
        .bind(&workspace.attempt_id)
        .execute(self.work_pool())
        .await?;
        Ok(())
    }

    async fn get_task_workspace(&self, task_id: &str) -> anyhow::Result<Option<TaskWorkspace>> {
        let row = sqlx::query(
            "SELECT id, task_id, attempt_id, backend_id, policy, root_path,
                    branch_name, base_ref, head_ref, status, created_at, released_at
             FROM task_workspaces WHERE task_id = ?
             ORDER BY julianday(created_at) DESC, id DESC LIMIT 1",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.map(|row| TaskWorkspace {
            id: row.get("id"),
            task_id: row.get("task_id"),
            attempt_id: row.get("attempt_id"),
            backend_id: row.get("backend_id"),
            policy: row.get("policy"),
            root_path: row.get("root_path"),
            branch_name: row.get("branch_name"),
            base_ref: row.get("base_ref"),
            head_ref: row.get("head_ref"),
            status: row.get("status"),
            created_at: row.get("created_at"),
            released_at: row.get("released_at"),
        }))
    }

    async fn get_latest_task_handoff(&self, task_id: &str) -> anyhow::Result<Option<TaskHandoff>> {
        let row = sqlx::query(
            "SELECT id, task_id, attempt_id, summary, artifacts_json,
                    verification_json, remaining_risk, next_step, created_at
             FROM task_handoffs WHERE task_id = ?
             ORDER BY julianday(created_at) DESC, id DESC LIMIT 1",
        )
        .bind(task_id)
        .fetch_optional(self.work_pool())
        .await?;
        Ok(row.map(|row| {
            let artifacts = row
                .get::<String, _>("artifacts_json")
                .parse::<serde_json::Value>()
                .ok()
                .and_then(|value| serde_json::from_value::<Vec<HandoffArtifact>>(value).ok())
                .unwrap_or_default();
            let verification =
                serde_json::from_str::<Vec<String>>(&row.get::<String, _>("verification_json"))
                    .unwrap_or_default();
            TaskHandoff {
                id: row.get("id"),
                task_id: row.get("task_id"),
                attempt_id: row.get("attempt_id"),
                summary: row.get("summary"),
                artifacts,
                verification,
                remaining_risk: row.get("remaining_risk"),
                next_step: row.get("next_step"),
                created_at: row.get("created_at"),
            }
        }))
    }

    async fn list_work_goals(
        &self,
        project_id: &str,
        include_terminal: bool,
        limit: i64,
    ) -> anyhow::Result<Vec<WorkGoalSummary>> {
        let rows = sqlx::query(
            "WITH ranked_runs AS (
                SELECT gr.*, rg.goal_type,
                       ROW_NUMBER() OVER (
                           PARTITION BY gr.goal_id
                           ORDER BY julianday(gr.started_at) DESC, gr.id DESC
                       ) AS recency,
                       SUM(CASE WHEN gr.status IN ('pending', 'running', 'blocked')
                                THEN 1 ELSE 0 END) OVER (
                           PARTITION BY gr.goal_id
                       ) AS active_count
                FROM goal_runs gr
                JOIN goals rg ON rg.id = gr.goal_id
             ),
             visible_runs AS (
                SELECT * FROM ranked_runs
                WHERE status IN ('pending', 'running', 'blocked')
                   OR (active_count = 0 AND recency = 1
                       AND NOT (trigger_type = 'legacy' AND goal_type = 'continuous'))
             ),
             lanes AS (
                SELECT t.id, t.goal_id, t.goal_run_id,
                    CASE
                        WHEN t.status = 'pending' AND EXISTS (
                            SELECT 1 FROM task_dependencies dep
                            WHERE dep.task_id = t.id
                              AND NOT EXISTS (
                                SELECT 1 FROM tasks d
                                WHERE d.id = dep.depends_on_task_id
                                  AND d.goal_run_id = t.goal_run_id
                                  AND d.status IN ('completed', 'skipped', 'superseded')
                            )
                        ) THEN 'waiting'
                        WHEN t.status = 'pending' THEN 'ready'
                        WHEN t.status IN ('claimed', 'running') AND EXISTS (
                            SELECT 1 FROM task_attempts a
                            WHERE a.id = t.current_attempt_id
                              AND a.status IN ('claimed', 'running')
                              AND datetime(a.lease_expires_at) > datetime('now')
                        ) THEN 'in_progress'
                        WHEN t.status = 'blocked' THEN 'blocked'
                        WHEN t.status IN ('completed', 'cancelled', 'skipped', 'superseded') THEN 'done'
                        ELSE 'needs_attention'
                    END AS lane
                FROM tasks t
             )
             SELECT g.project_id, g.id AS goal_id, g.description, g.status AS goal_status,
                    vr.id AS run_id, vr.status AS run_status,
                    SUM(CASE WHEN l.lane = 'waiting' THEN 1 ELSE 0 END) AS waiting,
                    SUM(CASE WHEN l.lane = 'ready' THEN 1 ELSE 0 END) AS ready,
                    SUM(CASE WHEN l.lane = 'in_progress' THEN 1 ELSE 0 END) AS in_progress,
                    SUM(CASE WHEN l.lane = 'blocked' THEN 1 ELSE 0 END) AS blocked,
                    SUM(CASE WHEN l.lane = 'needs_attention' THEN 1 ELSE 0 END) AS needs_attention,
                    SUM(CASE WHEN l.lane = 'done' THEN 1 ELSE 0 END) AS done,
                    datetime(MAX(julianday(COALESCE(t.updated_at, g.updated_at)))) AS updated_at,
                    MAX(julianday(COALESCE(t.updated_at, g.updated_at))) AS updated_order
             FROM goals g
             LEFT JOIN visible_runs vr ON vr.goal_id = g.id
             LEFT JOIN tasks t ON t.goal_run_id = vr.id
             LEFT JOIN lanes l ON l.id = t.id
             WHERE g.project_id = ? AND g.domain = 'orchestration'
               AND (? OR g.status NOT IN ('completed', 'failed', 'cancelled', 'abandoned'))
             GROUP BY g.id, vr.id
             ORDER BY
                CASE g.priority WHEN 'critical' THEN 1 WHEN 'high' THEN 2
                                WHEN 'medium' THEN 3 ELSE 4 END,
                updated_order DESC
             LIMIT ?",
        )
        .bind(project_id)
        .bind(include_terminal)
        .bind(limit.clamp(1, 200))
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows
            .iter()
            .map(|row| WorkGoalSummary {
                project_id: row.get("project_id"),
                goal_id: row.get("goal_id"),
                description: row.get("description"),
                goal_status: row.get("goal_status"),
                run_id: row.get("run_id"),
                run_status: row.get("run_status"),
                waiting: row.get::<i64, _>("waiting"),
                ready: row.get::<i64, _>("ready"),
                in_progress: row.get::<i64, _>("in_progress"),
                blocked: row.get::<i64, _>("blocked"),
                needs_attention: row.get::<i64, _>("needs_attention"),
                done: row.get::<i64, _>("done"),
                updated_at: row.get("updated_at"),
            })
            .collect())
    }

    async fn list_work_tasks(
        &self,
        project_id: &str,
        lane: Option<&str>,
        limit: i64,
    ) -> anyhow::Result<Vec<WorkTaskSummary>> {
        let rows = sqlx::query(
            "WITH ranked_runs AS (
                SELECT gr.*, rg.goal_type,
                       ROW_NUMBER() OVER (
                           PARTITION BY gr.goal_id
                           ORDER BY julianday(gr.started_at) DESC, gr.id DESC
                       ) AS recency,
                       SUM(CASE WHEN gr.status IN ('pending', 'running', 'blocked')
                                THEN 1 ELSE 0 END) OVER (
                           PARTITION BY gr.goal_id
                       ) AS active_count
                FROM goal_runs gr
                JOIN goals rg ON rg.id = gr.goal_id
             ),
             visible_runs AS (
                SELECT * FROM ranked_runs
                WHERE status IN ('pending', 'running', 'blocked')
                   OR (active_count = 0 AND recency = 1
                       AND NOT (trigger_type = 'legacy' AND goal_type = 'continuous'))
             ),
             projected AS (
                SELECT g.project_id, t.goal_id, g.description AS goal_description,
                       t.goal_run_id, t.id AS task_id, t.description, t.status,
                       t.priority, t.blocker, COALESCE(t.updated_at, t.created_at) AS updated_at,
                       wp.name AS worker_profile, a.worker_instance_id, a.lease_expires_at,
                       CASE
                           WHEN t.status = 'pending' AND EXISTS (
                               SELECT 1 FROM task_dependencies dep
                               WHERE dep.task_id = t.id
                                 AND NOT EXISTS (
                                   SELECT 1 FROM tasks d
                                   WHERE d.id = dep.depends_on_task_id
                                     AND d.goal_run_id = t.goal_run_id
                                     AND d.status IN ('completed', 'skipped', 'superseded')
                               )
                           ) THEN 'waiting'
                           WHEN t.status = 'pending' THEN 'ready'
                           WHEN t.status IN ('claimed', 'running') AND a.id IS NOT NULL
                                AND a.status IN ('claimed', 'running')
                                AND datetime(a.lease_expires_at) > datetime('now')
                               THEN 'in_progress'
                           WHEN t.status = 'blocked' THEN 'blocked'
                           WHEN t.status IN ('completed', 'cancelled', 'skipped', 'superseded') THEN 'done'
                           ELSE 'needs_attention'
                       END AS lane
                FROM tasks t
                JOIN goals g ON g.id = t.goal_id
                JOIN visible_runs vr ON vr.id = t.goal_run_id
                LEFT JOIN task_attempts a ON a.id = t.current_attempt_id
                LEFT JOIN worker_profiles wp ON wp.id = COALESCE(a.worker_profile_id, t.worker_profile_id)
                WHERE g.project_id = ? AND g.domain = 'orchestration'
                  AND g.status NOT IN ('completed', 'failed', 'cancelled', 'abandoned')
             )
             SELECT * FROM projected
             WHERE (? IS NULL OR lane = ?)
             ORDER BY
                CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
                julianday(updated_at) DESC
             LIMIT ?",
        )
        .bind(project_id)
        .bind(lane)
        .bind(lane)
        .bind(limit.clamp(1, 500))
        .fetch_all(self.work_pool())
        .await?;
        Ok(rows
            .iter()
            .map(|row| WorkTaskSummary {
                project_id: row.get("project_id"),
                goal_id: row.get("goal_id"),
                goal_description: row.get("goal_description"),
                goal_run_id: row.get("goal_run_id"),
                task_id: row.get("task_id"),
                description: row.get("description"),
                status: row.get("status"),
                lane: row.get("lane"),
                priority: row.get("priority"),
                worker_profile: row.get("worker_profile"),
                worker_instance_id: row.get("worker_instance_id"),
                lease_expires_at: row.get("lease_expires_at"),
                blocker: row.get("blocker"),
                updated_at: row.get("updated_at"),
            })
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::*;
    use crate::traits::{Goal, GoalSchedule, Task};
    use std::sync::Arc;

    async fn test_store() -> (SqliteWorkStore, tempfile::NamedTempFile) {
        let database = tempfile::NamedTempFile::new().unwrap();
        let store = open_for_tests(database.path().to_str().unwrap()).await;
        (store, database)
    }

    fn task(goal_id: &str, description: &str, depends_on: Option<Vec<String>>) -> Task {
        Task {
            id: uuid::Uuid::new_v4().to_string(),
            goal_id: goal_id.to_string(),
            description: description.to_string(),
            status: "pending".to_string(),
            priority: "medium".to_string(),
            task_order: 0,
            parallel_group: None,
            depends_on: depends_on.map(|deps| serde_json::to_string(&deps).unwrap()),
            agent_id: None,
            context: None,
            result: None,
            error: None,
            blocker: None,
            idempotent: true,
            retry_count: 0,
            max_retries: 2,
            created_at: chrono::Utc::now().to_rfc3339(),
            started_at: None,
            completed_at: None,
        }
    }

    fn handoff(task_id: &str, attempt_id: &str, summary: &str) -> TaskHandoff {
        TaskHandoff {
            id: uuid::Uuid::new_v4().to_string(),
            task_id: task_id.to_string(),
            attempt_id: attempt_id.to_string(),
            summary: summary.to_string(),
            artifacts: vec![HandoffArtifact {
                kind: "path".to_string(),
                reference: "/tmp/result".to_string(),
                digest: None,
                metadata: None,
            }],
            verification: vec!["check passed".to_string()],
            remaining_risk: None,
            next_step: None,
            created_at: chrono::Utc::now().to_rfc3339(),
        }
    }

    #[tokio::test]
    async fn a_deleted_project_leaves_its_sessions_and_bots_in_no_project() {
        let (store, _db) = test_store().await;
        let project = store.create_work_project("Acme site", None).await.unwrap();
        let bot = "telegram:synthetic_coding_bot";
        assert!(
            store
                .set_session_work_project("app:a", &project.id)
                .await
                .unwrap()
        );
        assert!(
            store
                .set_channel_work_project(bot, Some(&project.id))
                .await
                .unwrap()
        );

        assert!(store.delete_work_project(&project.id).await.unwrap());

        assert!(
            store
                .list_work_projects()
                .await
                .unwrap()
                .iter()
                .all(|p| p.id != project.id)
        );
        assert_eq!(
            store.get_session_work_project("app:a").await.unwrap(),
            DEFAULT_PROJECT_ID
        );
        assert!(store.session_work_projects().await.unwrap().is_empty());
        assert!(store.channel_work_projects().await.unwrap().is_empty());
        assert!(!store.delete_work_project(&project.id).await.unwrap());
        assert!(store.delete_work_project(DEFAULT_PROJECT_ID).await.is_err());
    }

    #[tokio::test]
    async fn a_project_keeps_its_folder_and_lists_the_sessions_placed_in_it() {
        let (store, _db) = test_store().await;
        let project = store.create_work_project("Acme site", None).await.unwrap();
        assert_eq!(project.path, None);
        let moved = store
            .update_work_project(&project.id, None, Some(Some("/home/synthetic/acme-site")))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(moved.path.as_deref(), Some("/home/synthetic/acme-site"));
        assert_eq!(moved.name, "Acme site");
        let renamed = store
            .update_work_project(&project.id, Some("Acme Corp site"), None)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            (renamed.name.as_str(), renamed.path.as_deref()),
            ("Acme Corp site", Some("/home/synthetic/acme-site"))
        );
        let cleared = store
            .update_work_project(&project.id, None, Some(None))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(cleared.path, None);
        assert!(
            store
                .update_work_project("project-missing", Some("x"), None)
                .await
                .unwrap()
                .is_none()
        );
        assert!(
            store
                .set_session_work_project("app:a", &project.id)
                .await
                .unwrap()
        );
        assert!(
            store
                .set_session_work_project("app:b", DEFAULT_PROJECT_ID)
                .await
                .unwrap()
        );
        assert_eq!(
            store.session_work_projects().await.unwrap(),
            vec![("app:a".to_string(), project.id.clone())]
        );

        // A bot's chats go to its project, unless placed already: a chat
        // taken out of a project (placed in the default one) stays out.
        let bot = "telegram:synthetic_coding_bot";
        assert!(
            !store
                .place_chat_by_channel("synthetic_coding_bot:1", bot)
                .await
                .unwrap()
        );
        assert!(
            store
                .set_channel_work_project(bot, Some(&project.id))
                .await
                .unwrap()
        );
        assert_eq!(
            store.channel_work_projects().await.unwrap(),
            vec![(bot.to_string(), project.id.clone())]
        );
        assert!(
            store
                .place_chat_by_channel("synthetic_coding_bot:1", bot)
                .await
                .unwrap()
        );
        assert!(
            !store
                .place_chat_by_channel("synthetic_coding_bot:1", bot)
                .await
                .unwrap()
        );
        assert!(!store.place_chat_by_channel("app:b", "app").await.unwrap());
        assert!(
            !store
                .set_channel_work_project(bot, Some("project-missing"))
                .await
                .unwrap()
        );
        assert!(store.set_channel_work_project(bot, None).await.unwrap());
        assert!(store.channel_work_projects().await.unwrap().is_empty());
        assert!(
            !store
                .place_chat_by_channel("synthetic_coding_bot:2", bot)
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn goal_run_is_pending_until_a_worker_claims_its_task() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("execute exactly once", "session-a");
        store.create_goal(&goal).await.unwrap();
        let run = store
            .start_goal_run(&goal.id, "manual", None, None)
            .await
            .unwrap();
        assert_eq!(run.status, "pending");

        let root = task(&goal.id, "manual root", None);
        store.create_task(&root).await.unwrap();
        assert_eq!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .status,
            "pending"
        );

        store
            .claim_task_with_lease(&root.id, "worker-a", Some("profile-task-lead"), 180)
            .await
            .unwrap()
            .expect("claim succeeds");
        assert_eq!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .status,
            "running"
        );
    }

    #[tokio::test]
    async fn live_lease_marks_the_goal_run_owned_until_the_lease_ends() {
        // While any unexpired lease exists on a run's attempt, a worker owns
        // the run's outcome and lifecycle reconciliation must defer to it.
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("execute exactly once", "session-a");
        store.create_goal(&goal).await.unwrap();
        let run = store
            .start_goal_run(&goal.id, "scheduled", None, None)
            .await
            .unwrap();
        let root = task(&goal.id, "scheduled root", None);
        store.create_task(&root).await.unwrap();
        assert!(!store.goal_run_has_live_attempt(&run.id).await.unwrap());

        let attempt = store
            .claim_task_with_lease(&root.id, "worker-a", Some("profile-task-lead"), 180)
            .await
            .unwrap()
            .expect("claim succeeds");
        assert!(store.goal_run_has_live_attempt(&run.id).await.unwrap());

        // A terminal patch ends the attempt and with it the ownership claim.
        assert!(
            store
                .patch_task_from_attempt(
                    &attempt.id,
                    &attempt.lease_token,
                    &TaskAttemptPatch {
                        status: "completed".to_string(),
                        result: Some("done".to_string()),
                        error: None,
                        blocker: None,
                        context: None,
                        handoff: None,
                    },
                )
                .await
                .unwrap()
        );
        assert!(!store.goal_run_has_live_attempt(&run.id).await.unwrap());
    }

    #[tokio::test]
    async fn scheduled_run_terminalization_reconciles_child_obligations() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("synthetic recurrence", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let run = store
            .start_goal_run(&goal.id, "scheduled", None, None)
            .await
            .unwrap();
        let child = task(&goal.id, "unfinished scheduled child", None);
        store.create_task(&child).await.unwrap();

        let premature = store
            .finish_goal_run(&run.id, "completed", Some("premature"))
            .await;
        assert!(premature.is_err());
        assert_eq!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .id,
            run.id
        );

        assert!(
            store
                .finish_goal_run(&run.id, "failed", Some("terminal failure"))
                .await
                .unwrap()
        );
        let reconciled = store.get_tasks_for_goal_run(&run.id).await.unwrap();
        assert_eq!(reconciled[0].status, "cancelled");
        assert!(
            reconciled[0]
                .error
                .as_deref()
                .is_some_and(|error| error.contains("Parent scheduled occurrence"))
        );
    }

    #[tokio::test]
    async fn active_root_lead_can_complete_its_own_scheduled_run() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let root = task(&goal.id, "scheduled lead", None);
        let run = store
            .start_goal_run(&goal.id, "scheduled", None, Some(&root.id))
            .await
            .unwrap();
        store.create_task(&root).await.unwrap();
        store
            .claim_task_with_lease(&root.id, "lead", Some("profile-task-lead"), 180)
            .await
            .unwrap()
            .expect("lead claims its root");
        let mut child = task(&goal.id, "publish one post", None);
        child.status = "completed".to_string();
        child.completed_at = Some(chrono::Utc::now().to_rfc3339());
        store.create_task(&child).await.unwrap();

        // The lead is still running inside its root task when it completes
        // the run; its own root is the caller, not an open obligation.
        assert!(
            store
                .finish_goal_run(&run.id, "completed", Some("published"))
                .await
                .expect("an active root lead must be able to complete its run")
        );
    }

    #[tokio::test]
    async fn superseded_task_with_note_does_not_block_scheduled_completion() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let run = store
            .start_goal_run(&goal.id, "scheduled", None, None)
            .await
            .unwrap();
        let mut replaced = task(&goal.id, "specialist review", None);
        replaced.status = "superseded".to_string();
        replaced.error = Some("timed out; the lead reviewed directly".to_string());
        store.create_task(&replaced).await.unwrap();
        let mut done = task(&goal.id, "publish one post", None);
        done.status = "completed".to_string();
        store.create_task(&done).await.unwrap();

        assert!(
            store
                .finish_goal_run(&run.id, "completed", Some("published"))
                .await
                .expect("superseded work is resolved, as Task::satisfies_run_completion says")
        );
    }

    #[tokio::test]
    async fn failed_root_still_blocks_scheduled_run_completion() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("synthetic daily publication", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let mut root = task(&goal.id, "scheduled lead", None);
        root.status = "failed".to_string();
        root.error = Some("lead crashed".to_string());
        let run = store
            .start_goal_run(&goal.id, "scheduled", None, Some(&root.id))
            .await
            .unwrap();
        store.create_task(&root).await.unwrap();

        assert!(
            store
                .finish_goal_run(&run.id, "completed", Some("premature"))
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn claims_are_dependency_aware_fenced_and_handed_off() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("coordinate a release", "session-a");
        store.create_goal(&goal).await.unwrap();
        let first = task(&goal.id, "prepare", None);
        let second = task(&goal.id, "verify", Some(vec![first.id.clone()]));
        store.create_task(&first).await.unwrap();
        store.create_task(&second).await.unwrap();

        assert!(
            store
                .claim_task_with_lease(&second.id, "worker-b", Some("profile-review"), 180)
                .await
                .unwrap()
                .is_none()
        );
        let first_attempt = store
            .claim_task_with_lease(&first.id, "worker-a", Some("profile-code"), 180)
            .await
            .unwrap()
            .unwrap();
        let patch = TaskAttemptPatch {
            status: "completed".to_string(),
            result: Some("prepared".to_string()),
            handoff: Some(handoff(
                &first.id,
                &first_attempt.id,
                "Preparation complete",
            )),
            ..Default::default()
        };
        assert!(
            store
                .patch_task_from_attempt(&first_attempt.id, &first_attempt.lease_token, &patch,)
                .await
                .unwrap()
        );
        assert_eq!(
            store
                .get_latest_task_handoff(&first.id)
                .await
                .unwrap()
                .unwrap()
                .verification,
            vec!["check passed"]
        );
        assert!(
            store
                .claim_task_with_lease(&second.id, "worker-b", Some("profile-review"), 180)
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            !store
                .patch_task_from_attempt(
                    &first_attempt.id,
                    &first_attempt.lease_token,
                    &TaskAttemptPatch {
                        status: "failed".to_string(),
                        error: Some("late write".to_string()),
                        ..Default::default()
                    },
                )
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn normalized_dependency_edges_are_atomic_and_reject_cycles() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("dependency graph", "session-a");
        store.create_goal(&goal).await.unwrap();
        let first = task(&goal.id, "first", None);
        let second = task(&goal.id, "second", Some(vec![first.id.clone()]));
        store.create_task(&first).await.unwrap();
        store.create_task(&second).await.unwrap();

        let edge_count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM task_dependencies WHERE task_id = ?",
        )
        .bind(&second.id)
        .fetch_one(&store.pool)
        .await
        .unwrap();
        assert_eq!(edge_count, 1);

        let mut cyclic = first.clone();
        cyclic.depends_on = Some(serde_json::json!([second.id]).to_string());
        let error = store.update_task(&cyclic).await.unwrap_err();
        assert!(error.to_string().contains("task dependency cycle"));

        let unchanged = store.get_task(&first.id).await.unwrap().unwrap();
        assert!(unchanged.depends_on.is_none());
        assert_eq!(
            sqlx::query_scalar::<_, i64>(
                "SELECT COUNT(*) FROM task_dependencies WHERE task_id = ?",
            )
            .bind(&first.id)
            .fetch_one(&store.pool)
            .await
            .unwrap(),
            0
        );
    }

    #[tokio::test]
    async fn retries_and_claims_clear_stale_task_outcomes() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("retry cleanly", "session-a");
        store.create_goal(&goal).await.unwrap();

        let failed = task(&goal.id, "failed once", None);
        store.create_task(&failed).await.unwrap();
        sqlx::query(
            "UPDATE tasks
             SET status = 'failed', result = 'old result', error = 'old error',
                 blocker = 'old blocker', completed_at = datetime('now')
             WHERE id = ?",
        )
        .bind(&failed.id)
        .execute(&store.pool)
        .await
        .unwrap();
        assert!(
            store
                .retry_work_task(&failed.id, "owner", Some("telegram"))
                .await
                .unwrap()
        );
        let retried = store.get_task(&failed.id).await.unwrap().unwrap();
        assert_eq!(retried.status, "pending");
        assert!(retried.result.is_none());
        assert!(retried.error.is_none());
        assert!(retried.blocker.is_none());
        assert!(retried.completed_at.is_none());

        let stale_pending = task(&goal.id, "legacy pending", None);
        store.create_task(&stale_pending).await.unwrap();
        sqlx::query(
            "UPDATE tasks
             SET result = 'stale result', error = 'stale error',
                 blocker = 'stale blocker', completed_at = datetime('now')
             WHERE id = ?",
        )
        .bind(&stale_pending.id)
        .execute(&store.pool)
        .await
        .unwrap();
        assert!(
            store
                .claim_task_with_lease(&stale_pending.id, "worker-a", None, 180)
                .await
                .unwrap()
                .is_some()
        );
        let claimed = store.get_task(&stale_pending.id).await.unwrap().unwrap();
        assert_eq!(claimed.status, "claimed");
        assert!(claimed.result.is_none());
        assert!(claimed.error.is_none());
        assert!(claimed.blocker.is_none());
        assert!(claimed.completed_at.is_none());
    }

    #[tokio::test]
    async fn expired_leases_retry_safe_work_and_block_ambiguous_work() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("recover work", "session-a");
        store.create_goal(&goal).await.unwrap();
        let safe = task(&goal.id, "safe read", None);
        let mut ambiguous = task(&goal.id, "external write", None);
        ambiguous.idempotent = false;
        ambiguous.max_retries = 0;
        store.create_task(&safe).await.unwrap();
        store.create_task(&ambiguous).await.unwrap();
        let safe_attempt = store
            .claim_task_with_lease(&safe.id, "worker-a", None, 180)
            .await
            .unwrap()
            .unwrap();
        let ambiguous_attempt = store
            .claim_task_with_lease(&ambiguous.id, "worker-b", None, 180)
            .await
            .unwrap()
            .unwrap();
        sqlx::query(
            "UPDATE task_attempts
             SET lease_expires_at = datetime('now', '-1 second')
             WHERE id IN (?, ?)",
        )
        .bind(&safe_attempt.id)
        .bind(&ambiguous_attempt.id)
        .execute(&store.pool)
        .await
        .unwrap();

        let affected = store.recover_expired_task_attempts().await.unwrap();
        assert_eq!(affected.len(), 2);
        let safe_after = store.get_task(&safe.id).await.unwrap().unwrap();
        assert_eq!(safe_after.status, "pending");
        assert_eq!(safe_after.retry_count, 1);
        let ambiguous_after = store.get_task(&ambiguous.id).await.unwrap().unwrap();
        assert_eq!(ambiguous_after.status, "blocked");
        assert!(
            ambiguous_after
                .blocker
                .unwrap()
                .contains("Verify external side effects")
        );
        assert!(
            !store
                .heartbeat_task_attempt(&safe_attempt.id, &safe_attempt.lease_token, 180,)
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn worker_profile_capacity_is_enforced() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("bounded workers", "session-a");
        store.create_goal(&goal).await.unwrap();
        let first = task(&goal.id, "one", None);
        let second = task(&goal.id, "two", None);
        let third = task(&goal.id, "three", None);
        store.create_task(&first).await.unwrap();
        store.create_task(&second).await.unwrap();
        store.create_task(&third).await.unwrap();
        assert!(
            store
                .claim_task_with_lease(&first.id, "one", Some("profile-code"), 180)
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            store
                .claim_task_with_lease(&second.id, "two", Some("profile-code"), 180)
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            store
                .claim_task_with_lease(&third.id, "three", Some("profile-code"), 180)
                .await
                .unwrap()
                .is_none()
        );
        let generic_attempt = store
            .claim_task_with_lease(&third.id, "three", Some("profile-executor"), 180)
            .await
            .unwrap()
            .unwrap();
        assert!(
            !store
                .bind_task_attempt_worker(
                    &generic_attempt.id,
                    &generic_attempt.lease_token,
                    "three",
                    Some("profile-code"),
                )
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn starting_a_run_waits_out_a_competing_writer() {
        let (store, _database) = test_store().await;
        let mode: String = sqlx::query_scalar("PRAGMA journal_mode = WAL")
            .fetch_one(&store.pool)
            .await
            .unwrap();
        assert_eq!(mode.to_ascii_lowercase(), "wal");

        let goal = Goal::new_finite("start after contention", "session-a");
        store.create_goal(&goal).await.unwrap();

        let mut competing_writer = store.pool.begin_with("BEGIN IMMEDIATE").await.unwrap();
        sqlx::query("UPDATE goals SET updated_at = datetime('now') WHERE id = ?")
            .bind(&goal.id)
            .execute(&mut *competing_writer)
            .await
            .unwrap();

        let store = Arc::new(store);
        let starting = store.clone();
        let goal_id = goal.id.clone();
        let started = tokio::spawn(async move {
            starting
                .start_goal_run(&goal_id, "scheduled", None, None)
                .await
        });

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        competing_writer.commit().await.unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(2), started)
            .await
            .expect("the start should resume after the competing writer commits")
            .unwrap()
            .expect("a competing write must not fail the start");
    }

    #[tokio::test]
    async fn worker_binding_waits_for_a_wal_writer_instead_of_losing_its_snapshot() {
        let (store, _database) = test_store().await;
        let mode: String = sqlx::query_scalar("PRAGMA journal_mode = WAL")
            .fetch_one(&store.pool)
            .await
            .unwrap();
        assert_eq!(mode.to_ascii_lowercase(), "wal");

        let goal = Goal::new_finite("bind after contention", "session-a");
        store.create_goal(&goal).await.unwrap();
        let work = task(&goal.id, "scheduled root", None);
        store.create_task(&work).await.unwrap();
        let attempt = store
            .claim_task_with_lease(&work.id, "heartbeat-dispatch", None, 180)
            .await
            .unwrap()
            .unwrap();

        let mut competing_writer = store.pool.begin_with("BEGIN IMMEDIATE").await.unwrap();
        sqlx::query("UPDATE goals SET updated_at = datetime('now') WHERE id = ?")
            .bind(&goal.id)
            .execute(&mut *competing_writer)
            .await
            .unwrap();

        let store = Arc::new(store);
        let binding_store = store.clone();
        let attempt_id = attempt.id.clone();
        let lease_token = attempt.lease_token.clone();
        let binding = tokio::spawn(async move {
            binding_store
                .bind_task_attempt_worker(
                    &attempt_id,
                    &lease_token,
                    "specialist:task-lead:test",
                    None,
                )
                .await
        });

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        competing_writer.commit().await.unwrap();
        assert!(
            tokio::time::timeout(std::time::Duration::from_secs(2), binding)
                .await
                .expect("binding should resume after the competing writer commits")
                .unwrap()
                .unwrap()
        );

        let rebound = store
            .get_current_task_attempt(&work.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(rebound.worker_instance_id, "specialist:task-lead:test");
    }

    /// Work aimed at the workspace container gets its own folder unless the
    /// task was explicitly given the shared policy; the description's words
    /// ("all my projects") never widen it to the container.
    #[tokio::test]
    async fn container_scope_is_the_explicit_shared_policy_not_the_task_words() {
        let (store, _database) = test_store().await;
        let workspace_root = tempfile::TempDir::new().unwrap();
        let backend =
            aidaemon_tools::execution::local_backend(&aidaemon_tools::execution::ExecutionConfig {
                workspace_root: Some(workspace_root.path().to_string_lossy().into_owned()),
                allow_outside_workspace: Some(false),
                ..Default::default()
            })
            .await
            .unwrap();
        let goal = Goal::new_finite("synthetic workspace scope", "session-a");
        store.create_goal(&goal).await.unwrap();
        let worded = task(
            &goal.id,
            "Inspect all my projects in the projects folder",
            None,
        );
        let explicit = task(&goal.id, "Update one synthetic dependency", None);
        store.create_task(&worded).await.unwrap();
        store.create_task(&explicit).await.unwrap();
        assert!(
            store
                .set_task_workspace_policy(&explicit.id, "shared")
                .await
                .unwrap()
        );

        let mut policies = Vec::new();
        for task in [&worded, &explicit] {
            let attempt = store
                .claim_task_with_lease(&task.id, "worker-a", None, 180)
                .await
                .unwrap()
                .unwrap();
            let workspace = crate::task_workspaces::provision_task_workspace(
                &backend, &store, &task.id, &attempt, None,
            )
            .await
            .unwrap();
            policies.push((workspace.policy, workspace.root_path));
        }
        let container = aidaemon_tools::ExecutionBackend::workspace_root(&backend).to_string();
        assert_eq!(policies[0].0, "isolated");
        assert_ne!(policies[0].1, container);
        assert_eq!(policies[1], ("shared".to_string(), container));
    }

    #[tokio::test]
    async fn explicit_profile_and_workspace_choices_override_fallbacks() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("honor task policy", "session-a");
        store.create_goal(&goal).await.unwrap();
        let assigned = task(&goal.id, "review this", None);
        let workspace = task(&goal.id, "edit safely", None);
        store.create_task(&assigned).await.unwrap();
        store.create_task(&workspace).await.unwrap();

        assert!(
            store
                .assign_task_worker_profile(
                    &assigned.id,
                    "profile-review",
                    "owner",
                    Some("telegram")
                )
                .await
                .unwrap()
        );
        let attempt = store
            .claim_task_with_lease(&assigned.id, "worker-a", Some("profile-code"), 180)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(attempt.worker_profile_id.as_deref(), Some("profile-review"));

        let mut code_profile = store
            .get_worker_profile("profile-code")
            .await
            .unwrap()
            .unwrap();
        code_profile.workspace_policy = "worktree".to_string();
        code_profile.version += 1;
        code_profile.updated_at = chrono::Utc::now().to_rfc3339();
        store.upsert_worker_profile(&code_profile).await.unwrap();
        assert!(
            store
                .assign_task_worker_profile(
                    &workspace.id,
                    "profile-code",
                    "owner",
                    Some("telegram")
                )
                .await
                .unwrap()
        );
        assert_eq!(
            store
                .get_task_workspace_policy(&workspace.id)
                .await
                .unwrap(),
            "worktree"
        );
        assert!(
            store
                .set_task_workspace_policy(&workspace.id, "shared")
                .await
                .unwrap()
        );
        assert_eq!(
            store
                .get_task_workspace_policy(&workspace.id)
                .await
                .unwrap(),
            "shared"
        );
    }

    #[tokio::test]
    async fn projects_runs_profiles_and_human_unblocks_are_isolated() {
        let (store, _database) = test_store().await;
        let project = store
            .create_work_project("Operations", Some("production work"))
            .await
            .unwrap();
        assert!(
            store
                .set_session_work_project("session-ops", &project.id)
                .await
                .unwrap()
        );
        let goal = Goal::new_finite("operate service", "session-ops");
        store.create_goal(&goal).await.unwrap();
        let first_run = store.get_current_goal_run(&goal.id).await.unwrap().unwrap();
        assert_eq!(first_run.project_id, project.id);
        let blocked = task(&goal.id, "needs input", None);
        store.create_task(&blocked).await.unwrap();
        let attempt = store
            .claim_task_with_lease(&blocked.id, "worker-a", None, 180)
            .await
            .unwrap()
            .unwrap();
        assert!(
            store
                .patch_task_from_attempt(
                    &attempt.id,
                    &attempt.lease_token,
                    &TaskAttemptPatch {
                        status: "blocked".to_string(),
                        blocker: Some("Need approval".to_string()),
                        handoff: Some(handoff(&blocked.id, &attempt.id, "Waiting for approval")),
                        ..Default::default()
                    },
                )
                .await
                .unwrap()
        );
        let escalation = crate::traits::NotificationEntry::new(
            &goal.id,
            &goal.session_id,
            "escalation",
            "Approval required",
        )
        .with_task(&blocked.id);
        store.enqueue_notification(&escalation).await.unwrap();
        assert!(
            store
                .get_pending_notifications(20)
                .await
                .unwrap()
                .iter()
                .any(|entry| entry.id == escalation.id)
        );
        assert!(
            store
                .unblock_task(&blocked.id, "Approved by owner", "owner", Some("telegram"))
                .await
                .unwrap()
        );
        assert!(
            !store
                .get_pending_notifications(20)
                .await
                .unwrap()
                .iter()
                .any(|entry| entry.id == escalation.id)
        );
        let journal = store.get_task_journal(&blocked.id, 20).await.unwrap();
        assert!(journal.iter().any(|entry| entry.entry_type == "unblocked"));

        store
            .cancel_work_task(&blocked.id, "owner", Some("telegram"))
            .await
            .unwrap();
        store
            .finish_goal_run(&first_run.id, "cancelled", Some("closed"))
            .await
            .unwrap();
        let second_run = store
            .start_goal_run(&goal.id, "manual", None, None)
            .await
            .unwrap();
        let current = task(&goal.id, "current run", None);
        store.create_task(&current).await.unwrap();
        let current_tasks = store.get_tasks_for_goal_run(&second_run.id).await.unwrap();
        assert_eq!(current_tasks.len(), 1);
        assert_eq!(current_tasks[0].id, current.id);
        let board = store.list_work_tasks(&project.id, None, 100).await.unwrap();
        assert_eq!(board.len(), 1);
        assert_eq!(board[0].task_id, current.id);

        let terminal_goal = Goal::new_finite("archived work", "session-ops");
        store.create_goal(&terminal_goal).await.unwrap();
        let terminal_task = task(&terminal_goal.id, "old completed task", None);
        store.create_task(&terminal_task).await.unwrap();
        sqlx::query(
            "UPDATE goals
             SET status = 'completed', completed_at = datetime('now'),
                 updated_at = datetime('now')
             WHERE id = ?",
        )
        .bind(&terminal_goal.id)
        .execute(&store.pool)
        .await
        .unwrap();
        let terminal_run = store
            .get_current_goal_run(&terminal_goal.id)
            .await
            .unwrap()
            .unwrap();
        store
            .finish_goal_run(&terminal_run.id, "completed", Some("archived"))
            .await
            .unwrap();
        let active_board = store.list_work_tasks(&project.id, None, 100).await.unwrap();
        assert_eq!(active_board.len(), 1);
        assert_eq!(active_board[0].task_id, current.id);
    }

    #[tokio::test]
    async fn board_projection_includes_every_active_scheduled_run() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("process every trigger", "session-a");
        store.create_goal(&goal).await.unwrap();
        let initial = task(&goal.id, "initial work", None);
        store.create_task(&initial).await.unwrap();

        let first_scheduled = store
            .start_goal_run(&goal.id, "scheduled", None, None)
            .await
            .unwrap();
        let first_task = task(&goal.id, "first scheduled work", None);
        store.create_task(&first_task).await.unwrap();
        assert_eq!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .unwrap()
                .id,
            first_scheduled.id
        );

        let second_scheduled = store
            .start_goal_run(&goal.id, "scheduled", None, None)
            .await
            .unwrap();
        let second_task = task(&goal.id, "second scheduled work", None);
        store.create_task(&second_task).await.unwrap();

        let tasks = store
            .list_work_tasks(DEFAULT_PROJECT_ID, None, 100)
            .await
            .unwrap();
        assert!(tasks.iter().any(|item| item.task_id == initial.id));
        assert!(tasks.iter().any(|item| item.task_id == first_task.id));
        assert!(tasks.iter().any(|item| item.task_id == second_task.id));
        let goals = store
            .list_work_goals(DEFAULT_PROJECT_ID, false, 100)
            .await
            .unwrap();
        assert!(
            goals
                .iter()
                .any(|item| item.run_id.as_deref() == Some(first_scheduled.id.as_str()))
        );
        assert!(
            goals
                .iter()
                .any(|item| item.run_id.as_deref() == Some(second_scheduled.id.as_str()))
        );
    }

    #[tokio::test]
    async fn cancelled_tasks_are_archived_in_the_done_lane() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_finite("cancel safely", "session-a");
        store.create_goal(&goal).await.unwrap();
        let cancelled = task(&goal.id, "no longer needed", None);
        store.create_task(&cancelled).await.unwrap();
        assert!(
            store
                .cancel_work_task(&cancelled.id, "owner", Some("telegram"))
                .await
                .unwrap()
        );

        let done = store
            .list_work_tasks(DEFAULT_PROJECT_ID, Some("done"), 100)
            .await
            .unwrap();
        assert_eq!(done.len(), 1);
        assert_eq!(done[0].task_id, cancelled.id);
        assert_eq!(done[0].lane, "done");
        assert!(
            store
                .list_work_tasks(DEFAULT_PROJECT_ID, Some("needs_attention"), 100)
                .await
                .unwrap()
                .is_empty()
        );
    }

    #[tokio::test]
    async fn terminal_legacy_history_is_not_the_current_continuous_run() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("run every day", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let legacy = store
            .start_goal_run(&goal.id, "legacy", None, None)
            .await
            .unwrap();
        let historical = task(&goal.id, "old cycle", None);
        store.create_task(&historical).await.unwrap();
        sqlx::query("UPDATE tasks SET status='completed', completed_at=datetime('now') WHERE id=?")
            .bind(&historical.id)
            .execute(&store.pool)
            .await
            .unwrap();
        store
            .finish_goal_run(&legacy.id, "completed", Some("legacy history"))
            .await
            .unwrap();

        assert!(
            store
                .list_work_tasks(DEFAULT_PROJECT_ID, None, 100)
                .await
                .unwrap()
                .is_empty()
        );
        let goals = store
            .list_work_goals(DEFAULT_PROJECT_ID, false, 100)
            .await
            .unwrap();
        assert_eq!(goals.len(), 1);
        assert!(goals[0].run_id.is_none());
        assert_eq!(goals[0].done, 0);
    }

    #[tokio::test]
    async fn scheduled_failure_budget_escalates_and_resumes_only_owned_pauses() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("publish synthetic report", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let now = chrono::Utc::now().to_rfc3339();
        let active_schedule = GoalSchedule {
            id: uuid::Uuid::new_v4().to_string(),
            goal_id: goal.id.clone(),
            cron_expr: "0 6 * * *".to_string(),
            tz: "local".to_string(),
            original_schedule: Some("daily".to_string()),
            fire_policy: "coalesce".to_string(),
            is_one_shot: false,
            is_paused: false,
            last_run_at: None,
            next_run_at: now.clone(),
            created_at: now.clone(),
            updated_at: now.clone(),
        };
        let owner_paused_schedule = GoalSchedule {
            id: uuid::Uuid::new_v4().to_string(),
            is_paused: true,
            ..active_schedule.clone()
        };
        store.create_goal_schedule(&active_schedule).await.unwrap();
        store
            .create_goal_schedule(&owner_paused_schedule)
            .await
            .unwrap();

        for expected_failures in 1..=3 {
            let run = store
                .start_goal_run(&goal.id, "scheduled", Some(&active_schedule.id), None)
                .await
                .unwrap();
            assert!(
                store
                    .finish_goal_run(&run.id, "failed", Some("synthetic failed run"))
                    .await
                    .unwrap()
            );
            let recovery = store
                .get_scheduled_recovery_state(&goal.id)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(recovery.consecutive_failures, expected_failures);
            assert_eq!(
                recovery.latest_failure_kind,
                Some(crate::traits::ScheduledFailureKind::OutcomeUnproven)
            );
        }

        let escalated = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            escalated.disposition,
            crate::traits::ScheduledRecoveryDisposition::Escalated
        );
        let schedules = store.get_schedules_for_goal(&goal.id).await.unwrap();
        assert!(schedules.iter().all(|schedule| schedule.is_paused));
        assert_eq!(
            store.get_goal(&goal.id).await.unwrap().unwrap().status,
            "active"
        );
        assert!(
            store
                .get_pending_notifications(20)
                .await
                .unwrap()
                .iter()
                .any(|notification| {
                    notification.goal_id == goal.id
                        && notification.notification_type == "escalation"
                })
        );

        let recovery_run = store
            .start_goal_run(&goal.id, "scheduled", Some(&active_schedule.id), None)
            .await
            .unwrap();
        let mut recovery_task = task(&goal.id, "verify synthetic recovery", None);
        recovery_task.context = Some(
            serde_json::json!({
                "recovery_for_run": escalated.last_failed_run_id,
                "terminal_recovery": true
            })
            .to_string(),
        );
        store.create_task(&recovery_task).await.unwrap();
        sqlx::query("UPDATE goal_runs SET root_task_id = ? WHERE id = ?")
            .bind(&recovery_task.id)
            .bind(&recovery_run.id)
            .execute(&store.pool)
            .await
            .unwrap();
        let proof_receipt_id = "synthetic-recovery-proof";
        sqlx::query(
            "INSERT INTO events
                (session_id, event_type, data, created_at, task_id, tool_name)
             VALUES (?, 'tool_result', ?, ?, ?, 'http_request')",
        )
        .bind(&goal.session_id)
        .bind(
            serde_json::json!({
                "task_id": recovery_task.id,
                "tool_call_id": proof_receipt_id,
                "receipt": {
                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
                    "outcome_status": "succeeded",
                    "outcome_evidence": "structured_metadata"
                }
            })
            .to_string(),
        )
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(&recovery_task.id)
        .execute(&store.pool)
        .await
        .unwrap();
        recovery_task.status = "completed".to_string();
        recovery_task.result = Some("synthetic recovery verified".to_string());
        recovery_task.completed_at = Some(chrono::Utc::now().to_rfc3339());
        store.update_task(&recovery_task).await.unwrap();
        assert!(
            store
                .finish_goal_run(
                    &recovery_run.id,
                    "completed",
                    Some("synthetic verified recovery"),
                )
                .await
                .unwrap()
        );
        let healthy = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(healthy.consecutive_failures, 0);
        assert_eq!(
            healthy.disposition,
            crate::traits::ScheduledRecoveryDisposition::Healthy
        );
        let recovery_link: (String, String) = sqlx::query_as(
            "SELECT outcome_status, proof_receipt_ids_json
             FROM goal_run_recovery_links WHERE recovery_run_id = ?",
        )
        .bind(&recovery_run.id)
        .fetch_one(&store.pool)
        .await
        .unwrap();
        assert_eq!(recovery_link.0, "verified");
        assert_eq!(
            serde_json::from_str::<Vec<String>>(&recovery_link.1).unwrap(),
            vec![proof_receipt_id]
        );
        let schedules = store.get_schedules_for_goal(&goal.id).await.unwrap();
        assert!(
            !schedules
                .iter()
                .find(|schedule| schedule.id == active_schedule.id)
                .unwrap()
                .is_paused
        );
        assert!(
            schedules
                .iter()
                .find(|schedule| schedule.id == owner_paused_schedule.id)
                .unwrap()
                .is_paused
        );
    }

    #[tokio::test]
    async fn recovery_proof_matches_receipts_emitted_under_the_bound_worker_session() {
        // Live receipts carry the AGENT-LOOP task id, not the goals-table
        // task id: the proof of a recovery run's work reaches the ledger as
        // tool_result events under the worker session that the root task's
        // attempt was bound to. A verified successful recovery must be
        // recognized through that typed attempt edge — otherwise every real
        // success is recorded as an unproven failure and the schedule never
        // resumes.
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("publish synthetic report", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let now = chrono::Utc::now().to_rfc3339();
        let schedule = GoalSchedule {
            id: uuid::Uuid::new_v4().to_string(),
            goal_id: goal.id.clone(),
            cron_expr: "0 6 * * *".to_string(),
            tz: "local".to_string(),
            original_schedule: Some("daily".to_string()),
            fire_policy: "coalesce".to_string(),
            is_one_shot: false,
            is_paused: false,
            last_run_at: None,
            next_run_at: now.clone(),
            created_at: now.clone(),
            updated_at: now.clone(),
        };
        store.create_goal_schedule(&schedule).await.unwrap();
        for _ in 0..3 {
            let run = store
                .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
                .await
                .unwrap();
            assert!(
                store
                    .finish_goal_run(&run.id, "failed", Some("synthetic failed run"))
                    .await
                    .unwrap()
            );
        }
        let escalated = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            escalated.disposition,
            crate::traits::ScheduledRecoveryDisposition::Escalated
        );

        let recovery_run = store
            .start_goal_run(&goal.id, "recovery", None, None)
            .await
            .unwrap();
        let mut recovery_task = task(&goal.id, "recover the synthetic objective", None);
        recovery_task.context = Some(
            serde_json::json!({
                "recovery_for_run": escalated.last_failed_run_id,
                "terminal_recovery": true
            })
            .to_string(),
        );
        store.create_task(&recovery_task).await.unwrap();
        sqlx::query("UPDATE goal_runs SET root_task_id = ? WHERE id = ?")
            .bind(&recovery_task.id)
            .bind(&recovery_run.id)
            .execute(&store.pool)
            .await
            .unwrap();
        sqlx::query("UPDATE tasks SET goal_run_id = ? WHERE id = ?")
            .bind(&recovery_run.id)
            .bind(&recovery_task.id)
            .execute(&store.pool)
            .await
            .unwrap();

        // Claim the root task and bind its attempt to the worker session, the
        // way spawn_child_inner does for the task lead.
        let worker_session = "specialist:task_lead:synthetic-recovery";
        let attempt = store
            .claim_task_with_lease(&recovery_task.id, "heartbeat-dispatch", None, 180)
            .await
            .unwrap()
            .unwrap();
        assert!(
            store
                .bind_task_attempt_worker(&attempt.id, &attempt.lease_token, worker_session, None)
                .await
                .unwrap()
        );

        // The receipt is emitted under the worker session with an agent-loop
        // task id that exists nowhere in the tasks table.
        let proof_receipt_id = "session-edge-recovery-proof";
        sqlx::query(
            "INSERT INTO events
                (session_id, event_type, data, created_at, task_id, tool_name)
             VALUES (?, 'tool_result', ?, ?, ?, 'terminal')",
        )
        .bind(worker_session)
        .bind(
            serde_json::json!({
                "task_id": uuid::Uuid::new_v4().to_string(),
                "tool_call_id": proof_receipt_id,
                "receipt": {
                    "schema_version": aidaemon_events::ToolReceiptV1::SCHEMA_VERSION,
                    "outcome_status": "succeeded",
                    "outcome_evidence": "tool_reported"
                }
            })
            .to_string(),
        )
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(Option::<String>::None)
        .execute(&store.pool)
        .await
        .unwrap();

        recovery_task.status = "completed".to_string();
        recovery_task.result = Some("synthetic recovery verified".to_string());
        recovery_task.completed_at = Some(chrono::Utc::now().to_rfc3339());
        store.update_task(&recovery_task).await.unwrap();
        assert!(
            store
                .finish_goal_run(
                    &recovery_run.id,
                    "completed",
                    Some("verified via session edge")
                )
                .await
                .unwrap()
        );

        let healthy = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            healthy.disposition,
            crate::traits::ScheduledRecoveryDisposition::Healthy,
            "a recovery proven by receipts under the bound worker session must heal the objective"
        );
        assert_eq!(healthy.consecutive_failures, 0);
    }

    /// A run the scheduler skipped (the daemon was off) is recorded in the
    /// automation's history as `missed`, closed, at the time it was due; it
    /// neither counts toward the failure budget nor resets it, so misses
    /// never pause an automation, and the run after them still opens.
    #[tokio::test]
    async fn a_missed_run_is_history_and_does_not_count_toward_the_failure_budget() {
        let (store, _database) = test_store().await;
        let goal = Goal::new_continuous("synthetic daily digest", "session-a", None, None);
        store.create_goal(&goal).await.unwrap();
        let now = chrono::Utc::now().to_rfc3339();
        let schedule = GoalSchedule {
            id: uuid::Uuid::new_v4().to_string(),
            goal_id: goal.id.clone(),
            cron_expr: "0 9 * * *".to_string(),
            tz: "local".to_string(),
            original_schedule: Some("daily at 9am".to_string()),
            fire_policy: "coalesce".to_string(),
            is_one_shot: false,
            is_paused: false,
            last_run_at: None,
            next_run_at: now.clone(),
            created_at: now.clone(),
            updated_at: now.clone(),
        };
        store.create_goal_schedule(&schedule).await.unwrap();
        // Two real failures: one short of the budget of three.
        for _ in 0..2 {
            let run = store
                .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
                .await
                .unwrap();
            assert!(
                store
                    .finish_goal_run(&run.id, "failed", Some("synthetic failure"))
                    .await
                    .unwrap()
            );
        }
        // Then the daemon is off for three occurrences in a row.
        let due = (chrono::Utc::now() - chrono::Duration::hours(30)).to_rfc3339();
        for _ in 0..3 {
            let missed = store
                .record_missed_goal_run(
                    &goal.id,
                    Some(&schedule.id),
                    &due,
                    "The daemon wasn't running when this was due.",
                )
                .await
                .unwrap();
            assert_eq!(missed.status, GOAL_RUN_MISSED);
            assert_eq!(missed.started_at, due, "a miss is dated when it was due");
            assert!(missed.completed_at.is_some(), "a miss is closed");
        }
        let recovery = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(recovery.consecutive_failures, 2, "misses are not failures");
        assert_eq!(
            recovery.disposition,
            crate::traits::ScheduledRecoveryDisposition::Recovering
        );
        assert!(
            !store.get_schedules_for_goal(&goal.id).await.unwrap()[0].is_paused,
            "misses never pause an automation"
        );
        // The misses are in its history, and none is an open run.
        let runs = store.get_goal_runs(&goal.id).await.unwrap();
        assert_eq!(
            runs.iter().filter(|r| r.status == GOAL_RUN_MISSED).count(),
            3
        );
        assert!(
            store
                .get_current_goal_run(&goal.id)
                .await
                .unwrap()
                .is_none()
        );
        // The next real run opens fresh; its failure is the third, so the
        // budget counts runs that ran, not misses.
        let run = store
            .start_goal_run(&goal.id, "scheduled", Some(&schedule.id), None)
            .await
            .unwrap();
        assert!(runs.iter().all(|r| r.id != run.id));
        store
            .finish_goal_run(&run.id, "failed", Some("synthetic failure"))
            .await
            .unwrap();
        let recovery = store
            .get_scheduled_recovery_state(&goal.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(recovery.consecutive_failures, 3);
    }
}

/// The owner's notice when a scheduled automation pauses itself after
/// failing `failures` runs in a row: which one, why, and what to do.
fn paused_notice(
    name: &str,
    failures: i64,
    kind: crate::traits::ScheduledFailureKind,
    latest: Option<&str>,
) -> String {
    use crate::traits::ScheduledFailureKind as Kind;
    let why = latest
        .map(|text| text.trim().trim_end_matches('.'))
        .filter(|text| !text.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| {
            match kind {
                Kind::AuthorizationBlocked => "a step it needed was not allowed",
                Kind::RetryableTool => "a tool kept failing",
                Kind::PermanentTool => "a tool it needs failed",
                Kind::TaskFailed => "the run could not finish its work",
                Kind::OutcomeUnproven => "it could not show the work was done",
            }
            .to_string()
        });
    format!(
        "Paused \"{name}\" after {failures} failed runs in a row, so it stops retrying. \
         Latest problem: {why}. Fix the cause, then resume it in Automations, or ask me to look into it."
    )
}

#[cfg(test)]
mod paused_notice_tests {
    use super::paused_notice;
    use crate::traits::ScheduledFailureKind;

    #[test]
    fn the_pause_notice_names_the_automation_the_cause_and_what_to_do() {
        let text = paused_notice(
            "Daily report",
            3,
            ScheduledFailureKind::TaskFailed,
            Some("The report file was missing."),
        );
        assert_eq!(
            text,
            "Paused \"Daily report\" after 3 failed runs in a row, so it stops retrying. \
             Latest problem: The report file was missing. Fix the cause, then resume it in \
             Automations, or ask me to look into it."
        );
        let text = paused_notice("Daily report", 3, ScheduledFailureKind::RetryableTool, None);
        assert!(
            text.contains("Latest problem: a tool kept failing."),
            "{text}"
        );
        assert!(
            !text.contains("objective") && !text.contains("budget"),
            "{text}"
        );
    }
}